body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>To ensure there are no naming conflicts within our project (<code>C++</code>) I was tasked with writing a python script to check all of our header files for any occurrences of a <code>using namespace ...</code> within the file. If an occurrence is found, it's appended to a list then written to a log file. It's a fairly simple script, but I feel there could be some optimizations. This script is ran whenever someone commits to the repository.</p> <pre><code>""" Checks all the header files in our project to ensure there aren't occurrences of the namespace string. AUTHOR: Ben Antonellis DATE: April 4th, 2020 """ import os namespace: str = "using namespace" working_directory: str = os.path.dirname(os.path.realpath(__file__)); occurrences: list = [] for file in os.listdir(working_directory): formatted_file = f"{working_directory}/{file}" with open(formatted_file, "r") as source_file: for line_number, line in enumerate(source_file): if namespace in line and file[-3:] != ".py": occurrences.append(f"NAMESPACE FOUND: LINE [{line_number + 1}] IN FILE {formatted_file}") with open("logs/log.txt", "w") as log_file: for line in occurrences: log_file.write(line) </code></pre>
[]
[ { "body": "<p>Your <code>file[-3:] == \".py\"</code> check is later that it should be. It is part of the check executed for every line of a file, instead of only being done once per file. You should use:</p>\n\n<pre><code>for file in os.listdir(working_directory):\n if file[-3:] != \".py\":\n ...\n</code></pre>\n\n<p>Are there other files in the directory? Maybe a <code>README</code>, <code>Makefile.mak</code> or <code>.gitignore</code>? Maybe you want to only examine <code>.h</code> files, and/or <code>.hpp</code> files, instead of every file in the directory?</p>\n\n<pre><code>valid_exts = { \".h\", \".hpp\"}\nfor file in os.listdir(working_directory):\n if os.path.splitext(file)[1] in valid_exts:\n ...\n</code></pre>\n\n<hr>\n\n<p>Using <code>{line_number + 1}</code> in your format string is not very pretty. Line numbers start at one, and <code>enumerate()</code> allows you to specify the starting number:</p>\n\n<pre><code> for line_number, line in enumerate(source_file, 1):\n</code></pre>\n\n<hr>\n\n<p>Why accumulate the results in <code>occurrences</code>, and then write them out afterwords? Why not write them out as they are found?</p>\n\n<pre><code>with open(\"logs/log.txt\", \"w\") as log_file:\n for file in os.listdir(working_directory):\n ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T15:38:28.030", "Id": "239988", "ParentId": "239986", "Score": "5" } }, { "body": "<h2>Working directory</h2>\n\n<pre><code>os.path.dirname(os.path.realpath(__file__))\n</code></pre>\n\n<p>is not the current working directory. The current working directory is available via <code>os.getcwd</code>. Either you should call that instead, or maybe rename your variable.</p>\n\n<h2>Semicolons</h2>\n\n<p>are usually discouraged in Python, so you can drop one here:</p>\n\n<pre><code>working_directory: str = os.path.dirname(os.path.realpath(__file__));\n</code></pre>\n\n<h2>pathlib</h2>\n\n<pre><code>f\"{working_directory}/{file}\"\n</code></pre>\n\n<p>is better represented by making a <code>Path</code> and then using the <code>/</code> operator.</p>\n\n<h2>Overall</h2>\n\n<p>This approach is fragile. You're better off tapping into something like the LLVM/Clang AST, which actually understands how to parse all of the edge cases of C++.</p>\n\n<p>Here is a suggestion that takes care of everything except the AST:</p>\n\n<pre><code>from pathlib import Path\n\nNAMESPACE = 'using namespace'\n\nlog_file_name = Path('logs/log.txt')\n\nif __name__ == '__main__':\n working_dir = Path.cwd()\n with log_file_name.open('w') as log_file:\n for prefix in ('h', 'c'):\n for file_name in working_dir.glob(f'*.{prefix}*'):\n with file_name.open() as source_file:\n for line_number, line in enumerate(source_file):\n if NAMESPACE in line:\n log_file.write(f'NAMESPACE FOUND: LINE [{line_number + 1}] IN FILE {file_name}\\n')\n</code></pre>\n\n<p>This also takes into account @AJNeufeld's feedback which is good.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T11:40:11.363", "Id": "470782", "Score": "0", "body": "Did you mean `suffix` instead of `prefix`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T13:11:20.987", "Id": "470788", "Score": "0", "body": "Nope. It's a prefix of the extension." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T15:40:02.730", "Id": "239989", "ParentId": "239986", "Score": "7" } }, { "body": "<h2>Usage considerations</h2>\n\n<p>Given that file extensions actually mean nothing, and that a script that simply outputs lines with <code>using namespace</code> in its file argument (or <code>stdin</code>) would be more composable, I’d take the following approach:</p>\n\n<p>Have the script read its arguments as files, or <code>stdin</code> if none given. Then just search for <code>using namespace</code> and output line numbers. </p>\n\n<p>Hm, that sounds like <code>grep</code>... you could do</p>\n\n<ol>\n<li><code>git ls-files -z src | xargs -0 grep 'using namespace' &gt; logfile</code></li>\n<li><code>git grep 'using namespace' src &gt; logfile</code></li>\n</ol>\n\n<p>And you probably need some <code>grep</code> flags to control the output you want. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T02:07:57.610", "Id": "470745", "Score": "0", "body": "Git was my invention. The OP just said \"whenever someone commits to the repository\". They could be using Mecurial, Subversion, or even CVS. But excellent alternate outside the Python box solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T03:10:43.593", "Id": "470748", "Score": "0", "body": "@AJNeufeld yeah i realized after I was almost done that OP might not be on git. But this is the design I’d prefer a non-git interface to have in the long term anyway :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T23:25:59.380", "Id": "240012", "ParentId": "239986", "Score": "4" } } ]
{ "AcceptedAnswerId": "239989", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T13:39:13.910", "Id": "239986", "Score": "5", "Tags": [ "python", "python-3.x", "file" ], "Title": "Check header files for namespace usage" }
239986
<p>I've only been learning Python for a few days after a Humble Bundle book sale, but I made a functional Blackjack game on which I'd like some constructive criticism as far as my coding structure and any suggestions for improvement from more experienced coders.</p> <p>Edit: This is coded in Python 3.8.2</p> <pre><code>import random import time deck = [] firstDraw = 0 usedCards = [] playerHand = [] playerHandValue = 0 dealtCard1 = '' dealtCard1Number = 0 dealtCard2 = '' dealtCard2Number = 0 dealerHand = [] dealerHandValue = 0 def dealHand(): global deck global playerHand global playerHandValue global dealerHand global dealerHandValue global firstDraw firstDraw = 0 # The starting deck is created # deck = ['2sp', '3sp', '4sp', '5sp', '6sp', '7sp', '8sp', '9sp', '10sp', 'Jsp', 'Qsp', 'Ksp', 'Asp', '2cl', '3cl', '4cl', '5cl', '6cl', '7cl', '8cl', '9cl', '10cl', 'Jcl', 'Qcl', 'Kcl', 'Acl', '2he', '3he', '4he', '5he', '6he', '7he', '8he', '9he', '10he', 'Jhe', 'Qhe', 'Khe', 'Ahe', '2di', '3di', '4di', '5di', '6di', '7di', '8di', '9di', '10di', 'Jdi', 'Qdi', 'Kdi', 'Asp'] playerHand = [] playerHandValue = 0 dealerHand = [] dealerHandValue = 0 # Two cards are dealt to the player # dealtCard1Number = random.randint(0, len(deck)-1) playerHand.append(deck[dealtCard1Number]) del deck[dealtCard1Number] dealtCard2Number = random.randint(0, len(deck)-1) playerHand.append(deck[dealtCard2Number]) del deck[dealtCard2Number] # Two cards are dealt to the dealer # dealerCard1Number = random.randint(0, len(deck)-1) dealerCard1 = deck[dealerCard1Number] dealerHand.append(dealerCard1) del deck[dealerCard1Number] dealerCard2Number = random.randint(0, len(deck)-1) dealerCard2 = deck[dealerCard2Number] dealerHand.append(dealerCard2) del deck[dealerCard2Number] # The player's starting hand is revealed to the player # print('\n' + 'Your current hand is ' + str(playerHand) + '\n') time.sleep(1) findHandValue() def findHandValue(): global playerHand global playerHandValue # Resets the player's hand value to 0 for new deals # playerHandValue = 0 # The value of the player's cards is determined # if '2sp' in playerHand: playerHandValue = playerHandValue + 2 if '3sp' in playerHand: playerHandValue = playerHandValue + 3 if '4sp' in playerHand: playerHandValue = playerHandValue + 4 if '5sp' in playerHand: playerHandValue = playerHandValue + 5 if '6sp' in playerHand: playerHandValue = playerHandValue + 6 if '7sp' in playerHand: playerHandValue = playerHandValue + 7 if '8sp' in playerHand: playerHandValue = playerHandValue + 8 if '9sp' in playerHand: playerHandValue = playerHandValue + 9 if '10sp' in playerHand: playerHandValue = playerHandValue + 10 if 'Jsp' in playerHand: playerHandValue = playerHandValue + 10 if 'Qsp' in playerHand: playerHandValue = playerHandValue + 10 if 'Ksp' in playerHand: playerHandValue = playerHandValue + 10 if 'Asp' in playerHand: playerHandValue = playerHandValue + 11 if '2cl' in playerHand: playerHandValue = playerHandValue + 2 if '3cl' in playerHand: playerHandValue = playerHandValue + 3 if '4cl' in playerHand: playerHandValue = playerHandValue + 4 if '5cl' in playerHand: playerHandValue = playerHandValue + 5 if '6cl' in playerHand: playerHandValue = playerHandValue + 6 if '7cl' in playerHand: playerHandValue = playerHandValue + 7 if '8cl' in playerHand: playerHandValue = playerHandValue + 8 if '9cl' in playerHand: playerHandValue = playerHandValue + 9 if '10cl' in playerHand: playerHandValue = playerHandValue + 10 if 'Jcl' in playerHand: playerHandValue = playerHandValue + 10 if 'Qcl' in playerHand: playerHandValue = playerHandValue + 10 if 'Kcl' in playerHand: playerHandValue = playerHandValue + 10 if 'Acl' in playerHand: playerHandValue = playerHandValue + 11 if '2he' in playerHand: playerHandValue = playerHandValue + 2 if '3he' in playerHand: playerHandValue = playerHandValue + 3 if '4he' in playerHand: playerHandValue = playerHandValue + 4 if '5he' in playerHand: playerHandValue = playerHandValue + 5 if '6he' in playerHand: playerHandValue = playerHandValue + 6 if '7he' in playerHand: playerHandValue = playerHandValue + 7 if '8he' in playerHand: playerHandValue = playerHandValue + 8 if '9he' in playerHand: playerHandValue = playerHandValue + 9 if '10he' in playerHand: playerHandValue = playerHandValue + 10 if 'Jhe' in playerHand: playerHandValue = playerHandValue + 10 if 'Qhe' in playerHand: playerHandValue = playerHandValue + 10 if 'Khe' in playerHand: playerHandValue = playerHandValue + 10 if 'Ahe' in playerHand: playerHandValue = playerHandValue + 11 if '2di' in playerHand: playerHandValue = playerHandValue + 2 if '3di' in playerHand: playerHandValue = playerHandValue + 3 if '4di' in playerHand: playerHandValue = playerHandValue + 4 if '5di' in playerHand: playerHandValue = playerHandValue + 5 if '6di' in playerHand: playerHandValue = playerHandValue + 6 if '7di' in playerHand: playerHandValue = playerHandValue + 7 if '8di' in playerHand: playerHandValue = playerHandValue + 8 if '9di' in playerHand: playerHandValue = playerHandValue + 9 if '10di' in playerHand: playerHandValue = playerHandValue + 10 if 'Jdi' in playerHand: playerHandValue = playerHandValue + 10 if 'Qdi' in playerHand: playerHandValue = playerHandValue + 10 if 'Kdi' in playerHand: playerHandValue = playerHandValue + 10 if 'Adi' in playerHand: playerHandValue = playerHandValue + 11 # Allows Aces to convert from 11 points to 1 point if the hand value is over 21 # if playerHandValue &gt; 21: if 'Asp' in playerHand: playerHandValue = playerHandValue - 10 if playerHandValue &gt; 21: if 'Acl' in playerHand: playerHandValue = playerHandValue -10 if playerHandValue &gt; 21: if 'Adi' in playerHand: playerHandValue = playerHandValue -10 if playerHandValue &gt; 21: if 'Ahe' in playerHand: playerHandValue = playerHandValue -10 # Displays the player's hand value to the player # print("Player hand value = " + str(playerHandValue) + '\n') hitOrStay() def hitOrStay(): global dealtCard1 global firstDraw # The dealer's first card is revealed to the player # if firstDraw == 0: print('The dealer draws 2 cards and reveals ' + str(dealerHand[0]) + '\n') firstDraw = 1 time.sleep(2) # If the player's hand value is less than or equal to 21, the player has the choice to hit or stay # if playerHandValue &lt;= 21: hitOrStayChoice = '' while hitOrStayChoice != 'hit' or 'stay': hitOrStayChoice = input('Do you \'hit\' or \'stay\'?' '\n') if hitOrStayChoice == 'hit': dealtCard1Number = random.randint(0, len(deck)-1) dealtCard1 = deck[dealtCard1Number] playerHand.append(dealtCard1) del deck[dealtCard1Number] print('You were dealt ' + dealtCard1) findHandValue() if hitOrStayChoice == 'stay': revealDealerHand() # If the player's hand value is over 21, the player loses automatically # elif playerHandValue &gt; 21: loseGame() def revealDealerHand(): global playerHand global playerHandValue global dealerHand global dealerHandValue dealerHandValue = 0 # The value of the dealer's cards is determined in the same manner as the player's cards # if '2sp' in dealerHand: dealerHandValue = dealerHandValue + 2 if '3sp' in dealerHand: dealerHandValue = dealerHandValue + 3 if '4sp' in dealerHand: dealerHandValue = dealerHandValue + 4 if '5sp' in dealerHand: dealerHandValue = dealerHandValue + 5 if '6sp' in dealerHand: dealerHandValue = dealerHandValue + 6 if '7sp' in dealerHand: dealerHandValue = dealerHandValue + 7 if '8sp' in dealerHand: dealerHandValue = dealerHandValue + 8 if '9sp' in dealerHand: dealerHandValue = dealerHandValue + 9 if '10sp' in dealerHand: dealerHandValue = dealerHandValue + 10 if 'Jsp' in dealerHand: dealerHandValue = dealerHandValue + 10 if 'Qsp' in dealerHand: dealerHandValue = dealerHandValue + 10 if 'Ksp' in dealerHand: dealerHandValue = dealerHandValue + 10 if 'Asp' in dealerHand: dealerHandValue = dealerHandValue + 11 if '2cl' in dealerHand: dealerHandValue = dealerHandValue + 2 if '3cl' in dealerHand: dealerHandValue = dealerHandValue + 3 if '4cl' in dealerHand: dealerHandValue = dealerHandValue + 4 if '5cl' in dealerHand: dealerHandValue = dealerHandValue + 5 if '6cl' in dealerHand: dealerHandValue = dealerHandValue + 6 if '7cl' in dealerHand: dealerHandValue = dealerHandValue + 7 if '8cl' in dealerHand: dealerHandValue = dealerHandValue + 8 if '9cl' in dealerHand: dealerHandValue = dealerHandValue + 9 if '10cl' in dealerHand: dealerHandValue = dealerHandValue + 10 if 'Jcl' in dealerHand: dealerHandValue = dealerHandValue + 10 if 'Qcl' in dealerHand: dealerHandValue = dealerHandValue + 10 if 'Kcl' in dealerHand: dealerHandValue = dealerHandValue + 10 if 'Acl' in dealerHand: dealerHandValue = dealerHandValue + 11 if '2he' in dealerHand: dealerHandValue = dealerHandValue + 2 if '3he' in dealerHand: dealerHandValue = dealerHandValue + 3 if '4he' in dealerHand: dealerHandValue = dealerHandValue + 4 if '5he' in dealerHand: dealerHandValue = dealerHandValue + 5 if '6he' in dealerHand: dealerHandValue = dealerHandValue + 6 if '7he' in dealerHand: dealerHandValue = dealerHandValue + 7 if '8he' in dealerHand: dealerHandValue = dealerHandValue + 8 if '9he' in dealerHand: dealerHandValue = dealerHandValue + 9 if '10he' in dealerHand: dealerHandValue = dealerHandValue + 10 if 'Jhe' in dealerHand: dealerHandValue = dealerHandValue + 10 if 'Qhe' in dealerHand: dealerHandValue = dealerHandValue + 10 if 'Khe' in dealerHand: dealerHandValue = dealerHandValue + 10 if 'Ahe' in dealerHand: dealerHandValue = dealerHandValue + 11 if '2di' in dealerHand: dealerHandValue = dealerHandValue + 2 if '3di' in dealerHand: dealerHandValue = dealerHandValue + 3 if '4di' in dealerHand: dealerHandValue = dealerHandValue + 4 if '5di' in dealerHand: dealerHandValue = dealerHandValue + 5 if '6di' in dealerHand: dealerHandValue = dealerHandValue + 6 if '7di' in dealerHand: dealerHandValue = dealerHandValue + 7 if '8di' in dealerHand: dealerHandValue = dealerHandValue + 8 if '9di' in dealerHand: dealerHandValue = dealerHandValue + 9 if '10di' in dealerHand: dealerHandValue = dealerHandValue + 10 if 'Jdi' in dealerHand: dealerHandValue = dealerHandValue + 10 if 'Qdi' in dealerHand: dealerHandValue = dealerHandValue + 10 if 'Kdi' in dealerHand: dealerHandValue = dealerHandValue + 10 if 'Adi' in dealerHand: dealerHandValue = dealerHandValue + 11 # this section is to allow Aces to convert from 11 points to 1 point if the hand value is over 21 # if dealerHandValue &gt; 21: if 'Asp' in dealerHand: dealerHandValue = dealerHandValue - 10 if dealerHandValue &gt; 21: if 'Acl' in dealerHand: dealerHandValue = dealerHandValue -10 if dealerHandValue &gt; 21: if 'Adi' in dealerHand: dealerHandValue = dealerHandValue -10 if dealerHandValue &gt; 21: if 'Ahe' in dealerHand: dealerHandValue = dealerHandValue -10 # The dealer's hand is revealed # print('\n' + 'The dealer\'s hand is ' + str(dealerHand) + ' with a value of ' + str(dealerHandValue) + '\n') time.sleep(2) if dealerHandValue &lt;= 16: dealerHit() if dealerHandValue &gt; 16: dealerStay() def dealerHit(): global dealerHitCard1Number global dealerHitCard1 global dealerHand global dealerHitCard1 global dealerHitCard1Number dealerHitCard1Number = random.randint(0, len(deck)-1) dealerHitCard1 = deck[dealerHitCard1Number] dealerHand.append(dealerHitCard1) del deck[dealerHitCard1Number] print('The dealer hits and draws ' + dealerHitCard1) time.sleep(2) revealDealerHand() def dealerStay(): if playerHandValue &lt;= dealerHandValue: if dealerHandValue &lt;= 21: loseGame() if playerHandValue &gt; 21: loseGame() if dealerHandValue &gt;21 and playerHandValue &lt;= 21: winGame() if playerHandValue &gt; dealerHandValue: if playerHandValue &lt;= 21: winGame() if playerHandValue &gt;21: loseGame() def loseGame(): global playerHandValue if playerHandValue &lt;= 21: print('You lose! Your hand value was ' + str(playerHandValue) + ', while the dealer\'s was ' + str(dealerHandValue) + '\n') elif playerHandValue &gt; 21: print('You busted!' + '\n') askNewGame() def winGame(): global playerHandValue global dealerHandValue print('You won! Your hand value was ' + str(playerHandValue) + ', while the dealer\'s was ' + str(dealerHandValue) + '\n') newGame = '' while newGame != 'yes' or 'no': askNewGame() def askNewGame(): newGame = input('Do you want to play another game? \'Yes\' or \'No\'.') while newGame != 'yes' or 'no': if newGame == 'yes' or 'Yes' or 'y' or 'Y': dealHand() if newGame == 'no' or 'No' or 'n' or 'N': print('Goodbye!') print('Welcome to Blackjack' + '\n') input("Press Enter to deal your first hand.") dealHand() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T15:46:50.670", "Id": "470707", "Score": "0", "body": "What version of python is this written in?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T15:47:56.397", "Id": "470708", "Score": "0", "body": "It is Python version 3.8.2" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T16:44:27.007", "Id": "470830", "Score": "0", "body": "This might be useful: https://stackoverflow.com/questions/41970795/what-is-the-best-way-to-create-a-deck-of-cards/41970851#41970851" } ]
[ { "body": "<p>Two big ones:</p>\n\n<ol>\n<li>Don't use globals. There are lots of good reasons why globals are generally bad practice, and you can either read about them, you can discover them for yourself through painful experience over the course of years, or you can trust all the people who have been there and will tell you the same thing, and just nip that habit in the bud when you're starting out.</li>\n<li>Come up with an easier way to represent your cards. Having separate <code>if</code> statements to check the values of the 6 of spades vs the 6 of diamonds (and so on for every value and every suit) is a <em>lot</em> of unnecessary work.</li>\n</ol>\n\n<p>Check out this answer I wrote a while back on representing a deck of cards in Python code; this is far from the only way to do it, but pay attention to how the suit is separated from the rank, and how simply defining all the possible suits and ranks lets us use the <code>product</code> function to generate a complete deck automatically. The goal is to give yourself less work to do and to not need to copy+paste lots of code to do relatively simple things.</p>\n\n<p><a href=\"https://codereview.stackexchange.com/questions/234880/blackjack-21-in-python3/234890#234890\">Blackjack / 21 in Python3</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T15:50:06.277", "Id": "239991", "ParentId": "239990", "Score": "9" } }, { "body": "<h1>Use augmented assignments</h1>\n\n<p>Because people do things like <code>var = var + updateValue</code> Python supports writing this as <code>var += updateValue</code>. This means you don't have to write the name of the variable twice.</p>\n\n<p>What is even cooler, this works for <a href=\"https://docs.python.org/3/reference/simple_stmts.html#grammar-token-augmented-assignment-stmt\" rel=\"noreferrer\">lots of binary operations</a>, like <code>var *= multiplier</code> is the same as <code>var = var * multiplier</code> and <code>var %= mod</code> is the same as <code>var = var % mod</code>.</p>\n\n<h1>If you are copying and pasting your code, something is wrong</h1>\n\n<ul>\n<li><p>If you have code that is too repetitive, you can probably do it in a smarter way.</p></li>\n<li><p>If you have duplicate code, you can probably factor it in a function.</p></li>\n</ul>\n\n<p>I'm talking particularly about your <code>if</code> trains to update hand values. First of all, you should have a function that computes the value of a given hand and call it twice, instead of writing the trains of <code>if</code>s twice; this reduces the probability of making a mistake!</p>\n\n<p>After factoring your <code>if</code>s into a function, you still have <em>way too many</em> if statements that are too similar... so there might be a better way to do it!</p>\n\n<p>Some suggestions come to mind. Instead of checking if each card is in the hand, use a <code>for</code> loop to go over the cards in the hand:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for card in hand:\n pass\n</code></pre>\n\n<p>then, we need to check the value of each card. Note that the suit doesn't count for the value, so you can ignore the suits and only focus on the first character:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for card in hand:\n cardValue = card[0]\n # ...\n</code></pre>\n\n<p>and then check the value of the card in a smarter way. You could, for example, check if the card is a number or an ace; all the other cards are worth 10.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>handValue = 0\nfor card in hand:\n cardValue = card[0] # a 10 will be \"1\"\n if cardValue in \"23456789\":\n handValue += int(cardValue)\n elif cardValue == \"A\":\n handValue += 11\n else:\n handValue += 10\n\nif handValue &gt; 21:\n # check if there are aces, etc\n</code></pre>\n\n<p>Probably in the first loop you can even count the aces, so that latter on it is easier to handle the case where the hand busts the 21 cap.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T16:37:41.883", "Id": "470716", "Score": "0", "body": "This assigns `Q` the value 11, `K`, the value 12, and `A` the value 13, so is completely wrong. Plus, it will fail when a `10` card is encountered with an Exception." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T18:21:29.770", "Id": "470728", "Score": "0", "body": "@AJNeufeld you are most certainly right... I fixed that problem" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T16:22:37.243", "Id": "239995", "ParentId": "239990", "Score": "10" } }, { "body": "<h1>Dealing from the Middle of the Deck</h1>\n\n<pre><code> dealtCard1Number = random.randint(0, len(deck)-1)\n playerHand.append(deck[dealtCard1Number])\n del deck[dealtCard1Number]\n</code></pre>\n\n<p>Variations of this code is repeated many times.</p>\n\n<p>First, you could simplify this code slightly by using <code>random.randrange(len(deck))</code>.</p>\n\n<p>Second, it could be made into a function:</p>\n\n<pre><code>def deal():\n card_number = random.randrange(len(deck))\n card = deck[card_number]\n del deck[card_number]\n return card\n</code></pre>\n\n<p>And then using statements like:</p>\n\n<pre><code> playerHand.append(deal())\n</code></pre>\n\n<p>But selecting and dealing a random card from the middle of the deck just seems wrong. You want to shuffle the deck once, and then deal cards from the top of the deck:</p>\n\n<pre><code> deck = [...]\n random.shuffle(deck)\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>def deal():\n card = deck[0]\n del deck[0]\n return card\n</code></pre>\n\n<p>Or, as pointed out by <a href=\"https://codereview.stackexchange.com/users/221557/mt-head\">MT_Head</a> in the comments:</p>\n\n<pre><code>def deal():\n return deck.pop(0)\n</code></pre>\n\n<h1>PEP-8</h1>\n\n<p>Follow the Python Style Guidelines in <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a>. For instance, variables should be <code>snake_case</code>, not <code>mixedCase</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T16:32:22.937", "Id": "470715", "Score": "0", "body": "The book I'm learning from has everything in mixed case/camel case, but I'll take your suggestion and start doing snake case with the underscores." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T20:20:15.700", "Id": "470859", "Score": "0", "body": "@JoelV While usually style is up to the individual, python is very strict about its styling conventions, and *all* python programmers follow it. If your book is not following these conventions, then it's a bit of a red flag for the value of the book." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T02:05:27.477", "Id": "470881", "Score": "1", "body": "Try the built-in pop() method: card = deck.pop(index). It returns an item AND removes it from the list in one operation; index defaults to 0." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T16:28:02.230", "Id": "239996", "ParentId": "239990", "Score": "7" } }, { "body": "<p>I'll try and address @Sam's second point since I agree with him. How you have it now is an incredible amount of work and is unsustainable. Lets break it down. Look at these chunks of code:</p>\n\n<pre><code>if '2sp' in playerHand:\n playerHandValue = playerHandValue + 2\nif '3sp' in playerHand:\n playerHandValue = playerHandValue + 3\nif '4sp' in playerHand:\n playerHandValue = playerHandValue + 4\n\n. . .\n\nif '2sp' in dealerHand:\n dealerHandValue = dealerHandValue + 2\nif '3sp' in dealerHand:\n dealerHandValue = dealerHandValue + 3\nif '4sp' in dealerHand:\n dealerHandValue = dealerHandValue + 4\n</code></pre>\n\n<p>There's multiple problems with this setup:</p>\n\n<ul>\n<li><p>Really, the suit of the card doesn't matter. You only actually care about the value of the card.</p></li>\n<li><p>Those two discrete chunks are nearly identical. The only difference between them is the first takes the player's hand and returns the player's total, and the second takes the dealer's hand and returns the dealer's total.</p></li>\n</ul>\n\n<p>Lets deal with the first point, then expand it to fix the second.</p>\n\n<p>Whenever you have <em>nearly</em> exactly the same code repeated over and over, you probably want to use a function and/or loop to reduce the duplication. I'd start with a function that takes a card and returns its value:</p>\n\n<pre><code># This could be simplified since all values are the same\nface_values = {\"K\": 10, \"Q\": 10, \"J\": 10}\n\ndef card_value(card):\n raw_value = card[:-2] # Chop off the suit\n\n if raw_value in face_values:\n return face_values[raw_value]\n\n else:\n return int(raw_value)\n\n&gt;&gt;&gt; card_value(\"Ksp\")\n10\n\n&gt;&gt;&gt; card_value(\"8he\")\n8\n</code></pre>\n\n<p>Then, just loop:</p>\n\n<pre><code>player_hand_value = 0\nfor card in player_hand:\n player_hand_value += card_value(card)\n</code></pre>\n\n<p>There's still the problem though that you'd need to duplicate this code for the dealer. The solution is to make a function:</p>\n\n<pre><code>def hand_value(hand):\n total = 0\n for card in hand:\n total += card_value(card)\n\n return total\n\n&gt;&gt; hand_value([\"Ksp\", \"2he\"])\n12\n</code></pre>\n\n<p>Then just use that function:</p>\n\n<pre><code>def find_hand_value():\n global player_hand\n global player_hand_value\n\n playerHandValue = hand_value(player_hand)\n\n . . .\n</code></pre>\n\n<p>Then, to clean it up further:</p>\n\n<ul>\n<li><p><code>revealDealerHand</code> is also mostly the same as the player version. They could be generalized further by creating a function that handles the identical bits.</p></li>\n<li><p>You'd probably want to represent cards using a cleaner method. Even a tuple of <code>(\"K\", \"Spade\")</code> would be better than what you have now. Needing to parse a string to gets its value as needed isn't very clean</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T17:19:10.517", "Id": "470721", "Score": "0", "body": "Thanks for your suggestion. I still have a lot to learn!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T18:23:02.803", "Id": "470729", "Score": "0", "body": "Why are you wrapping the `face_values[raw_value]` in a call to `int` if the dictionary holds integers?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T18:51:43.100", "Id": "470732", "Score": "1", "body": "@RGS Oops. I did this review as a warm-up before I started working on an essay... but apparently I needed a warm-up before my warm-up." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T18:56:45.287", "Id": "470733", "Score": "0", "body": "@Carcigenicate I just wanted to be sure I wasn't missing anything :P" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T16:35:52.667", "Id": "239998", "ParentId": "239990", "Score": "11" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T15:43:31.760", "Id": "239990", "Score": "13", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Basic Blackjack game in Python" }
239990
<p>I am writing a script that is supposed to retrieve some data from a MYSQL database but I need to make it happen live and after lots of research I learned that this thing can be done using something called "Web Sockets" but since it seemed too complicated and I haven't even learned javascript that well, I chose to keep practicing javascript and use the only other method that I've found during the research and that method is by using a setInterval function.</p> <p>However, almost every example that I found using this method had a side note saying "This method is not recommended since if you have many users constantly sending requests to retrieve data from your server, it may cause the server to slow down or malfunction", which makes a lot of sense, but still I thought, can we optimize this to a minimal level that it doesn't even bother the server that much?</p> <p>Now, I've done some thinking and I believe that I found a possible solution that can help the client request the smallest piece of data on setInterval and only retrieve the big data when there is a change in the database... here is how I did it...</p> <p><strong>connect.php</strong></p> <pre><code>&lt;?php $mysqli = new mysqli('localhost', 'root', '', 'learningajax'); ?&gt; </code></pre> <p><strong>index.html</strong></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt; Learning AJAX &lt;/title&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="script.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="data"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>observer.php</strong></p> <pre><code>&lt;?php include 'connect.php'; $count = mysqli_query($mysqli, "SELECT * FROM users"); $result= mysqli_num_rows($count); echo json_encode($result); ?&gt; </code></pre> <p><strong>display.php</strong></p> <pre><code>&lt;?php include 'connect.php'; $data = mysqli_query($mysqli, "SELECT * FROM users"); echo "&lt;table&gt;&lt;tr&gt; &lt;th&gt;ID&lt;/th&gt; &lt;th&gt;Username&lt;/th&gt; &lt;th&gt;Password&lt;/th&gt; &lt;/tr&gt;"; while($row = $data-&gt;fetch_assoc()){ $user_id = $row['id']; $username = $row['username']; $password = $row['password']; echo "&lt;tr&gt; &lt;td&gt;$user_id&lt;/td&gt; &lt;td&gt;$username&lt;/td&gt; &lt;td&gt;$password&lt;/td&gt;"; } echo "&lt;/tr&gt;&lt;/table&gt;"; ?&gt; </code></pre> <p><strong>script.js</strong></p> <pre><code>$(document).ready(function load(){ $.ajax({ type: "GET", url: "display.php", dataType: "html", success: function(data){ $("#data").html(data); } }); $.ajax({ type: "GET", url: "observer.php", dataType: "html", success: function (primary){ console.log(primary); let check = setInterval(function (){ $.ajax({ type: "GET", url: "observer.php", dataType: "html", success: function(trigger){ console.log(trigger); if(primary != trigger){ clearInterval(check); load(); } } }); }, 1000); } }); }); </code></pre> <p><strong>insert.php</strong></p> <pre><code>&lt;?php include 'connect.php'; $username = $_POST['username']; $password = $_POST['password']; mysqli_query($mysqli, "INSERT INTO users (username,password) VALUES ('$username','$password')"); ?&gt; &lt;form method="POST"&gt; &lt;input type="text" name="username" /&gt; &lt;input type="password" name="password" /&gt; &lt;input type="submit" /&gt; &lt;/form&gt; </code></pre> <p>As you can see there is a script (observer.php) that only retrieves the number of records in the table and I used that script to define one variable and store the retrieved value on page load and then I made a function that will run the same script each second storing the value that the script returns in another variable (updating the value of the variable each second) and then told the code to load the entire code again only if the script retrieved a different value than the one that was stored on page load, I also clear the interval before calling the function because if I don't then it keeps loading the function over and over again after at least one change happened.</p> <p>Now, the point is that the script that runs each second over and over again is so minimal that it takes so little from the server and the big data is only pulled when the script spots a change in the number of records in the table.</p> <p>Now, I have few questions...</p> <ul> <li>Is this a good alternative of WebSockets for a small UI platform that don't have much users?</li> <li>Will the server still slow down or overwhelm by the requests no matter how small the data you retrieve is if you have several copies (per user) of this script continuously running for 16 hours a day?</li> <li>Everybody is saying that if you have too many users constantly sending requests the server may slow down or overwhelm but how many users are too many? (assuming that we use some standard package of some of the popular hosting providers among the web, you give the example)</li> </ul> <p><strong>install.php</strong></p> <pre><code>&lt;?php include 'connect.php'; mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS users( id INT(11) AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL )"); mysqli_query($mysqli, "INSERT INTO users ( username, password ) VALUES ( 'default', 'password' )"); ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T20:12:20.227", "Id": "470857", "Score": "0", "body": "The answers to your questions are likely No, Yes (although your example doesn't make much sense) and They're right but you won't easily find statistics on that." } ]
[ { "body": "<p>I would recommend some modifications.</p>\n\n<p>First, don't use setInterval. Use setTimeout instead. The setInterval function won't wait for the server to answer before sending another request. It will keep sending request to the server even if the server takes more than one second to answer your request. If you do something like:</p>\n\n<pre><code>function displayData(numUsers) {\n $.ajax({\n type: \"GET\",\n url: \"display.php\",\n dataType: \"html\",\n success: function(data){\n $(\"#data\").html(data);\n askObjserver(numUsers);\n }\n });\n}\n\nfunction askObserver(primary) {\n $.ajax({\n type: \"GET\",\n url: \"observer.php\",\n dataType: \"html\",\n success: function(trigger){\n console.log(trigger);\n if(primary != trigger){\n displayData(trigger);\n } else {\n setTimeout(askObserver, 1000, trigger);\n }\n }\n });\n}\n\n$(document).ready(askObserver);\n</code></pre>\n\n<p>The fist time, the script will retrieve the number of elements. As the input <code>primary</code> is undefined, <code>primary !== trigger</code>. This forces the first display of elements and reactivates the observer cycle. While the response is the same than before, the function keeps enqueuing more calls to the observer method. Every time the result differs, the information is updated.</p>\n\n<p>The second point to modify would be the query being used in the observer method. I would suggest using a query like <code>SELECT COUNT(id) FROM users</code>. That will make the query more efficient. The database manager will use the primary key index to make the query more efficient. You only need to read the returned value in the query instead of counting the number of rows returned in the resulting cursor.</p>\n\n<p>For your questions:</p>\n\n<ul>\n<li>Websockets allow your server to be the one notifying to the clients when a change happens avoiding unnecessary HTTP calls. This alternative isn't better. Take into account that you are executing a query to the database for every connection established against your PHP methods. The Websocket alternative would only need one server procedure executing the query internally every second. Whenever a change is detected, the server broadcast to all the clients the information.</li>\n<li>The limitations you will face are the number of connections that can be opened at the same time against the database. That will mark the number of concurrent users you can have using the application.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T08:18:11.183", "Id": "470770", "Score": "1", "body": "...and user input should be valudated and sanitized and the INSERT should be a prepared statement with bound parameters." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T23:04:27.280", "Id": "240009", "ParentId": "239992", "Score": "3" } } ]
{ "AcceptedAnswerId": "240009", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T15:53:18.270", "Id": "239992", "Score": "1", "Tags": [ "php", "ajax", "interval" ], "Title": "The most minimal way to retrieve live data using setInterval" }
239992
<p>Out of boredom, I decided to start my personal project and I've chosen a simple Text Password Manager.</p> <p><strong>Note: For anyone out there, I strongly recommend you NOT to use this for any sensitive storage purposes as it DOESN'T provide encryption yet!</strong>. That'll probably come in a later release.</p> <hr /> <h2>About Safer</h2> <p>My project is going to be called <strong>Safer</strong> and these are the tools I've used so far:</p> <ul> <li>Python 3.8</li> <li>SQLAlchemy</li> <li>SQLite3</li> </ul> <p><strong>Current features:</strong></p> <ul> <li>Retrieve all saved passwords.</li> <li>Create a new password.</li> <li>Retrieve a single password (by its name).</li> <li>Update a single password (by its name).</li> <li>Delete a single password (by its name).</li> </ul> <p><strong>Upcoming features (out of this review's purpose but it gives the reviewer some context):</strong></p> <ul> <li>Do all of the above only if a master password is provided (and it also matches the one from the DB).</li> <li>Create a master password if it doesn't exist.</li> <li>Encrypt all the passwords.</li> </ul> <hr /> <p><strong>What I'd like to get out of this review:</strong></p> <ul> <li>Is there a better way to restructure this project?</li> <li>Are the project files named correctly?</li> <li>Is my code modular enough?</li> <li>What about the logic? Would you use other approach over another when it comes any of the functionality in my code?</li> <li>Did I stick to the DRY principle enough? If not, what can I improve?</li> <li>Have I used SqlAlchemy as I should've?</li> <li>UX - User experience</li> <li>Wherever is room from improvement, please do tell ^_^</li> </ul> <hr /> <p>Right now, my project looks like this:</p> <pre><code>├── README.md ├── backend │   ├── __init__.py // nothing here │   ├── main.py // run program from here (will probably be moved to root dir in the future) │   ├── models.py // all the models used by SQLAlchemy │   └── views.py // not really views, actions for my models. ├── config.py // store all the needed configs here ├── requirements.txt // self-explanatory ├── safer.db // sqlite db file └── setup.cfg // various pep8, style, type-annotations config </code></pre> <h3>The code:</h3> <p><strong>main.py</strong></p> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot;Main entry to our app. Contains all the needed calls. &quot;&quot;&quot; from typing import Optional, Iterable import sys from getpass import getpass from views import ( create_master_password, create_password, delete_password, get_password_by_name, is_master_password_valid, list_all_passwords, update_password, ) VALID_MASTER_PASS_ANSWERS = ( &quot;Y&quot;, &quot;y&quot;, &quot;Yes&quot;, &quot;yes&quot;, &quot;N&quot;, &quot;n&quot;, &quot;No&quot;, &quot;no&quot;, ) VALID_ACTIONS = ( &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;9&quot;, ) def get_name(prompt: str) -&gt; str: &quot;&quot;&quot;Keep asking for a valid name until one is given. Arguments: prompt (str): Prompt message. Returns: string - name of the password &quot;&quot;&quot; while True: name = input(prompt) if not name: print( &quot;Name cannot be empty. We suggest you insert a &quot; &quot;descriptive name for your password.&quot; ) continue return name def get_password(prompt: str) -&gt; str: &quot;&quot;&quot;Keep asking for a valid password until one is given. Arguments: prompt (str): Prompt message. Returns: string - password &quot;&quot;&quot; while True: password = getpass(prompt) if not password: print(&quot;Password cannot be empty.&quot;) continue if len(password) &lt; 8: print(&quot;WARNING! This is a weak password.&quot;) return password def get_option(prompt: str, options: Optional[Iterable[str]] = None) -&gt; str: &quot;&quot;&quot;Keep asking for a valid option until one is given. Arguments: prompt (str): Prompt message. options (tuple): Options to choose from Returns: string - valid option &quot;&quot;&quot; while True: option = input(prompt) if not option: print(&quot;Please enter an option.&quot;) continue if option not in options: valid_options = &quot;, &quot;.join(options) print(f&quot;Invalid option. Valid options: {valid_options}&quot;) continue return option def main() -&gt; None: &quot;&quot;&quot;Main entry to our program.&quot;&quot;&quot; has_master_password = get_option( &quot;Do you have a master password? [Y/n]: &quot;, options=VALID_MASTER_PASS_ANSWERS, ) if has_master_password in (&quot;Y&quot;, &quot;y&quot;, &quot;Yes&quot;, &quot;yes&quot;): master_password = getpass(&quot;Insert your master password: &quot;) if not is_master_password_valid(master_password): raise ValueError(&quot;Please insert a valid master key.&quot;) what_next = get_option( &quot;&quot;&quot;Choose your next action: 1. View all passwords. 2. Create new password. 3. Show password by name. 4. Update password by name. 5. Delete password by name. 9. Quit &gt; &quot;&quot;&quot;, options=VALID_ACTIONS, ) if what_next == &quot;1&quot;: list_all_passwords() if what_next == &quot;2&quot;: name = get_name(&quot;New password name (unique!): &quot;) value = get_password(&quot;New password: &quot;) create_password(name, value) if what_next == &quot;3&quot;: name = get_name(&quot;Password name: &quot;) get_password_by_name(name) if what_next == &quot;4&quot;: name = get_name(&quot;Password name: &quot;) value = get_password(&quot;New password: &quot;) update_password(name, value) if what_next == &quot;5&quot;: name = get_name(&quot;Password name: &quot;) delete_password(name) if what_next == &quot;9&quot;: sys.exit() else: master_password = getpass(&quot;Insert your new master password: &quot;) create_master_password(master_password) if __name__ == &quot;__main__&quot;: main() </code></pre> <p><strong>views.py</strong></p> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot;Views module. Contains basic actions that can be done against MasterPassword and Password models. &quot;&quot;&quot; from typing import Any, Optional, Tuple, Union from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from tabulate import tabulate from config import SQLITE_FILEPATH from models import Base, MasterPassword, Password ENGINE = create_engine(SQLITE_FILEPATH) Base.metadata.create_all(ENGINE) Session = sessionmaker(bind=ENGINE) class SaferSession: &quot;&quot;&quot;Context manager for ease of session management.&quot;&quot;&quot; def __init__( self, record: Optional[Union[MasterPassword, Password]] = None ) -&gt; None: &quot;&quot;&quot;Simple constructor. Arguments: record (tuple): Optional argument used if provided. Returns: None &quot;&quot;&quot; self.record = record def __enter__(self) -&gt; sessionmaker(): &quot;&quot;&quot;Create a session object and return it. Returns: session object &quot;&quot;&quot; self.session = Session() return self.session def __exit__(self, *args: Tuple[None]) -&gt; None: &quot;&quot;&quot;Make sure the session object gets closed properly. Arguments: args (tuple): Not really used. Can be None as well. Returns: None &quot;&quot;&quot; if self.record: self.session.add(self.record) self.session.commit() self.session.close() def create_master_password(master_password: str) -&gt; None: &quot;&quot;&quot;Create a master password. Arguments: master_password (str): Desired master password Returns: None &quot;&quot;&quot; with SaferSession(record=MasterPassword(value=master_password)): print(&quot;Master password has been created!&quot;) def create_password(name: str, value: str) -&gt; None: &quot;&quot;&quot;Create a password and a name for it. Arguments: name (str): Name of the password. value (str): The password. Returns: None &quot;&quot;&quot; with SaferSession(record=Password(name, value)): print(f&quot;Successfully added {name} record.&quot;) def is_master_password_valid(master_password: str) -&gt; Optional[bool]: &quot;&quot;&quot;Check if provided master password is valid or not. Arguments: master_password (str): The master password. Returns: True if the password matches or None otherwise &quot;&quot;&quot; with SaferSession() as session: password_obj = session.query(MasterPassword).one_or_none() return password_obj.value == master_password if password_obj else None def get_password_by_name(name: str) -&gt; Any: &quot;&quot;&quot;Get a password by its name. Arguments: name (str): Name of the password. Returns: password or None &quot;&quot;&quot; with SaferSession() as session: try: password = session.query(Password) password = password.filter_by(name=name).first().value except AttributeError: password = None print(f&quot;{name} could not be found!&quot;) return password def update_password(name: str, new_value: str) -&gt; None: &quot;&quot;&quot;Update a specific password. Arguments: name (str): Name of the password that needs updating. new_value (str): New password. Returns: None &quot;&quot;&quot; with SaferSession() as session: try: password = session.query(Password).filter_by(name=name).first() password.value = new_value print(f&quot;Successfully updated {name} record.&quot;) except AttributeError: print(f&quot;{name} could not be found!&quot;) return def delete_password(name: str) -&gt; None: &quot;&quot;&quot;Delete a specific password. Arguments: name (str): NAme of the password that needs to be deleted. Returns: None &quot;&quot;&quot; with SaferSession() as session: try: session.query(Password).filter(Password.name == name).delete() print(f&quot;Successfully deleted {name} record.&quot;) except AttributeError: print(f&quot;{name} could not be found!&quot;) return def list_all_passwords() -&gt; None: &quot;&quot;&quot;List all passwords. Returns: None &quot;&quot;&quot; with SaferSession() as session: passwords = session.query(Password).all() if not passwords: print(&quot;No passwords stored yet!&quot;) return table = [ [password_obj.name, password_obj.value] for password_obj in passwords ] print(tabulate(table, [&quot;Password Name&quot;, &quot;Password&quot;], tablefmt=&quot;grid&quot;)) </code></pre> <p><strong>models.py</strong></p> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot;Models module. Contains all the needed models. &quot;&quot;&quot; from sqlalchemy import Column, DateTime, Integer, String, func from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Password(Base): &quot;&quot;&quot;Password model.&quot;&quot;&quot; __tablename__ = &quot;passwords&quot; id = Column(Integer, primary_key=True) name = Column(String(128), nullable=False, unique=True) value = Column(String, nullable=False) updated = Column(DateTime, default=func.now()) def __init__(self, name: str, value: str) -&gt; None: &quot;&quot;&quot;Simple constructor Arguments: name (str): Name of the password. value (str): Password. Returns: None &quot;&quot;&quot; self.name = name self.value = value def __repr__(self) -&gt; str: &quot;&quot;&quot;Representation of the Password object. Returns: Representation of the Password object as str &quot;&quot;&quot; return f&quot;&lt;Password(name='{self.name}', value='{self.value}')&gt;&quot; class MasterPassword(Base): &quot;&quot;&quot;Master Password model.&quot;&quot;&quot; __tablename__ = &quot;master_password&quot; id = Column(Integer, primary_key=True) value = Column(String, nullable=False) updated_at = Column(DateTime, default=func.now()) def __init__(self, value: str) -&gt; None: &quot;&quot;&quot;Simple constructor. Arguments: value (str): Master password. Returns: None &quot;&quot;&quot; self.value = value def __repr__(self) -&gt; str: &quot;&quot;&quot;Representation of the Master Password object. Returns: Representation of the Master Password object as str &quot;&quot;&quot; return f&quot;&lt;MasterPassword(value='{self.value}')&gt;&quot; </code></pre> <p><strong>config.py</strong></p> <pre class="lang-py prettyprint-override"><code>SQLITE_FILEPATH = 'sqlite:////path_to_project_root/safer.db' </code></pre> <p><strong>setup.cfg</strong></p> <pre><code>[pylama] linters = mccabe,pep8,pycodestyle,pyflakes,mypy,isort ignore=W293 [pylama:*/__init__.py] ignore=W0611 [pylama:pydocstyle] convention = google [pylama:mccabe] max-complexity = 2 [pydocstyle] convention = google [isort] multi_line_output=3 include_trailing_comma=True force_grid_wrap=0 use_parentheses=True line_length=79 [mypy] check_untyped_defs = true disallow_any_generics = true disallow_untyped_defs = true ignore_missing_imports = true no_implicit_optional = true warn_redundant_casts = true warn_return_any = true warn_unused_ignores = true </code></pre> <p>You can also clone the project from <a href="https://github.com/alexandru-grajdeanu/safer" rel="noreferrer">here</a>. Don't forget to change the path in the <code>config.py</code>!</p>
[]
[ { "body": "<h2>Encryption is not enough</h2>\n\n<p>In addition to your eventual encryption, you need to take measures to protect your data at the operating system level. At the least, make sure that the permissions are restrictive - this is possible on Windows, MacOS and Linux using various methods.</p>\n\n<h2>Sets</h2>\n\n<p><code>VALID_MASTER_PASS_ANSWERS</code> and <code>VALID_ACTIONS</code> should be sets. Also, just store the lower-case versions of your answers, and convert input to lower-case for the purposes of case-insensitive comparison. As for valid actions, they're all integers - so store them as integers, and convert your input to an integer.</p>\n\n<p>The case and set suggestions also apply to</p>\n\n<pre><code>if has_master_password in (\"Y\", \"y\", \"Yes\", \"yes\"):\n</code></pre>\n\n<h2>Password strength</h2>\n\n<p>Length is not enough. Do a basic English word pass at the least. Since this is specifically a password management program you might want to do something more thorough like entropy measurement - there are libraries for this.</p>\n\n<h2>Redundant return</h2>\n\n<p>Drop the <code>return</code> from this:</p>\n\n<pre><code> except AttributeError:\n print(f\"{name} could not be found!\")\n return\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T21:21:25.163", "Id": "240005", "ParentId": "239997", "Score": "3" } }, { "body": "<p>In <code>get_option</code>, you have a <code>while</code> loop:</p>\n\n<pre><code>while True:\n option = input(prompt)\n if not option:\n print(\"Please enter an option.\")\n continue\n\n if option not in options:\n valid_options = \", \".join(options)\n print(f\"Invalid option. Valid options: {valid_options}\")\n continue\n\n return option\n</code></pre>\n\n<p>I think this would make more sense by making use of <code>elif</code> and <code>else</code> and dropping the <code>continue</code>s:</p>\n\n<pre><code>while True:\n option = input(prompt)\n if not option:\n print(\"Please enter an option.\")\n\n elif option not in options:\n valid_options = \", \".join(options)\n print(f\"Invalid option. Valid options: {valid_options}\")\n\n else:\n return option\n</code></pre>\n\n<p>And then similarly in <code>get_password</code>.</p>\n\n<hr>\n\n<p>And then another similar case in <code>get_name</code>:</p>\n\n<pre><code>while True:\n name = input(prompt)\n if not name:\n print(\n \"Name cannot be empty. We suggest you insert a \"\n \"descriptive name for your password.\"\n )\n continue\n\n return name\n</code></pre>\n\n<p>I think it would be much simpler to return at the top, instead of returning at the bottom and trying to divert execution away from the <code>return</code> using <code>continue</code>:</p>\n\n<pre><code>while True:\n name = input(prompt)\n if name:\n return name\n\n else:\n print(\"Name cannot be empty. We suggest you insert a \"\n \"descriptive name for your password.\")\n</code></pre>\n\n<p>I also recommend tightening up the <code>print</code> as I have there. There's a point where spreading things out and making your function longer begins to hurt readability.</p>\n\n<p>A fun party-trick suggestion though: that can actually be made even more succinct if you're using Python3.8+:</p>\n\n<pre><code>while True:\n if name := input(prompt):\n return name\n . . .\n</code></pre>\n\n<p><code>:=</code> is an <a href=\"https://www.python.org/dev/peps/pep-0572/\" rel=\"nofollow noreferrer\">assignment expression</a>.</p>\n\n<hr>\n\n<p>Your menu dispatch in <code>main</code> should be using <code>elif</code>s:</p>\n\n<pre><code>if what_next == \"1\":\n list_all_passwords()\n\nelif what_next == \"2\":\n name = get_name(\"New password name (unique!): \")\n value = get_password(\"New password: \")\n\n. . .\n</code></pre>\n\n<p>You know that those checks will always be exclusive of each other (only one can ever be true). If <code>\"what_next == \"1\"</code> is true, you're still doing all the rest of the checks when<code>list_all_passwords</code> returns, which is wasteful. It'll make a negligible here, but avoiding unnecessary overhead is a good habit to get into.</p>\n\n<hr>\n\n<p>There's no need to include <code>-&gt; None</code>. When type hinting <code>__init__</code>, since it <em>must</em> return <code>None</code>.</p>\n\n<hr>\n\n<p><code>get_password_by_name</code> could be cleaned up a bit too. You have:</p>\n\n<pre><code>with SaferSession() as session:\n try:\n password = session.query(Password)\n password = password.filter_by(name=name).first().value\n except AttributeError:\n password = None\n print(f\"{name} could not be found!\")\n return password\n</code></pre>\n\n<p>I'm not a fan of reassigning variable in most cases. If you want to debug and see intermittent results, you need to catch it before the second reassignment happens. I don't know what <code>session.query(Password)</code> returns, but is it itself a <code>password</code>? I think I'd give it a different name. This can be simplified though to remove that need:</p>\n\n<pre><code>with SaferSession() as session:\n try:\n result = session.query(Password)\n return result.filter_by(name=name).first().value\n\n except AttributeError:\n print(f\"{name} could not be found!\")\n return None\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T14:13:17.343", "Id": "470793", "Score": "1", "body": "`print(\"WARNING! This is a weak password.\")` wasn't really a bug because I didn't want to impose to the user to enter a stronger password but just to warn him and still let him do the action. Anyway, I'm still trying to decide if I want to impose the security to the users or just use w/e they'd like. Any opinion on this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T14:15:37.060", "Id": "470794", "Score": "0", "body": "@GrajdeanuAlex.You could allow them to initially pass in some kind of \"policy\" object that indicates a strictness level. It could just be an `Enum` with different levels like `STRICT`, `LENIANT`, `NO_RESTRICTIONS`. Then check for that internally and change your tests accordingly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T22:46:01.207", "Id": "240008", "ParentId": "239997", "Score": "3" } }, { "body": "<h1>BUG</h1>\n\n<p>Your code doesn't execute right now, I'm guessing because you recently moved source code: <em>ModuleNotFoundError: No module named 'config'</em>. (Works again if you move <code>config.py</code> to <code>backend/</code>.)</p>\n\n<hr>\n\n<h1>Your questions</h1>\n\n<p><strong>Is there a better way to restructure this project? Are the project files named correctly?</strong></p>\n\n<p>I would move: the entry file (<code>main.py</code>; which you either could call that or rename to something like <code>safer.py</code>) out of your source directory (to the root dir), the database (<code>safer.db</code>) as well as the config file (<code>config.py</code>) out of the root dir. The config file may currently only have a single entry, but I would expect it to grow with the project. You can additionally use <a href=\"https://docs.python.org/3/library/configparser.html\" rel=\"nofollow noreferrer\">configparser</a> for the config, and <a href=\"https://docs.python.org/3/library/logging.html\" rel=\"nofollow noreferrer\">logging</a> instead of some of your info and debug messages.</p>\n\n<p>I also think that <code>views.py</code> is poorly named, given that you yourself write \"not really views, actions for my models\" about it.</p>\n\n<p>Since some of your functions are \"private\", you could consider naming them with a leading underscore to signal this.</p>\n\n<p><strong>Is my code modular enough?</strong></p>\n\n<p>You should replace the URI in <code>config.py</code> to a relative path if the database comes with the project. Look at <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\">pathlib</a> and be careful about different operating systems.</p>\n\n<p><strong>What about the logic? Would you use other approach over another when it comes any of the functionality in my code?</strong></p>\n\n<p>I would prefer to have the \"front-end\" more object-oriented (especially since you already use OOP), and I would separate the \"back-end\" from the inputs and outputs. It would make it easier if the project grows (say you wanted to add a GUI later), but also for troubleshooting and testing. I would expect a method for getting a list of all passwords instead of having a function that simply prints to stdout the list of all passwords (<code>list_all_passwords()</code>). I would also look at <a href=\"https://docs.python.org/3/library/re.html\" rel=\"nofollow noreferrer\">regular expressions</a> for validation of inputs.</p>\n\n<p>I think you missed an opportunity to use dundermethods for accessing members (your methods <code>get_password_by_name</code>, <code>delete_password</code>, etc.).</p>\n\n<p>I also find it a little strange that you draw your menu and have your switch cases in one place, but you have a separate function for taking the input (<code>get_option()</code>).</p>\n\n<p><strong>Did I stick to the DRY principle enough? If not, what can I improve?</strong></p>\n\n<p>Your global variables (<code>VALID_...</code>) and their usage is a bit repeated.</p>\n\n<p><strong>UX - User experience</strong></p>\n\n<p>It's a bit annoying that it prints out the menu again after each invalid choice, so that the screen eventually stacks up with duplicates. It's also a bit surprising that the app exits after choosing an option in the menu (at least with choice #1).</p>\n\n<hr>\n\n<h1>Other things</h1>\n\n<p><strong>Readability, standard practises</strong></p>\n\n<p>Code looks pythonic and nice in <code>models.py</code> and <code>view.py</code>, slightly less good in the \"front-end\" (entry) file. I would also have liked to see some tests.</p>\n\n<p>I think you over-document a little, a good example being:</p>\n\n<pre><code> def __repr__(self) -&gt; str:\n \"\"\"Representation of the Password object.\n Returns:\n Representation of the Password object as str\n \"\"\"\n return f\"&lt;Password(name='{self.name}', value='{self.value}')&gt;\"\n</code></pre>\n\n<p>I think you can assume that most readers will know what repr is and does.</p>\n\n<p>I also saw that you only have three commits on your repo. You may want to work on your version control workflow.</p>\n\n<p><strong>Security</strong></p>\n\n<p>I don't think you should allow any type of password, and I think you should more than just notify the user that they've selected an insecure password. If you don't want to force strict passwords, you can just ask them to enter an insecure one again to confirm.</p>\n\n<p><strong>Context manager</strong></p>\n\n<p>I like the idea of a context manager your sessions, but be careful to handle potential errors in your <code>__exit__</code> function.</p>\n\n<p><strong>Surprising behaviour/prompt</strong></p>\n\n<p>In the same vein, raise errors in your back-end but deal with them yourself in the front-end; don't do this:</p>\n\n<pre><code> if not is_master_password_valid(master_password):\n raise ValueError(\"Please insert a valid master key.\")\n</code></pre>\n\n<p><strong>Refactoring</strong></p>\n\n<p>Some of your <code>if</code>-clauses should be <code>elif</code> (or you could refactor to dicts), and I would prefer to see your loops reworked.</p>\n\n<hr>\n\n<h1>PS.</h1>\n\n<ul>\n<li><p>Since you use <code>typing</code> anyway, you can use <code>typing.NoReturn</code> for your side-effect-only type-hints.</p></li>\n<li><p>You don't need the <code>__init__.py</code> since Python3.3.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-12T19:14:13.030", "Id": "478537", "Score": "0", "body": "Hey, thanks for this answer! You might also be interested in [this](https://codereview.stackexchange.com/q/243095/61966) _pseudo_ follow-up question ^^" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T08:04:30.027", "Id": "240130", "ParentId": "239997", "Score": "1" } } ]
{ "AcceptedAnswerId": "240130", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T16:31:14.710", "Id": "239997", "Score": "5", "Tags": [ "python", "python-3.x", "sqlite", "sqlalchemy" ], "Title": "Simple Python and SQLAlchemy Text Password Manager" }
239997
<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>// TODO: https://codereview.stackexchange.com/questions/240011/js-schedule-conflict-detection-algorithm-logic-length // List with handle Sortable.create(dashboard, { handle: '.fa-bars', animation: 150 }); // To Instantiate &amp; Control the Modal var modal = document.getElementById("modal"); var addSchedule = document.getElementById('add'); var scheduleCount = 0; var trackedSchedule; addSchedule.addEventListener('click', function (event) { scheduleCount += 1; // console.log(event.target.id); // Anomoly Here trackedSchedule = `schedule-${scheduleCount}`; console.log(trackedSchedule); // Change modal to load with default values (prefill name with scheduleCount) // Change Text to Read "Create Schedule" instead of "Edit Schedule" modal.style.display = "block"; }); var span = document.getElementsByClassName("close")[0]; span.onclick = function() { modal.style.display = "none"; scheduleCount -= 1; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; scheduleCount -= 1; } } function getDate() { var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); var mm = String(today.getMonth() + 1).padStart(2, '0'); var yyyy = today.getFullYear(); today = `${yyyy}-${mm}-${dd}`; return today; } var savedSchedules = {}; var data = []; var layout = { showlegend: false, xaxis: {range: ['2020-01-01 00:00:00', '2020-01-01 23:59:59'], showgrid: false, zeroline: false, showline: true, tickformat: '%H:%M:%S' }, yaxis: {rangemode: 'tozero', range: [-0.75, 6.5], showline: true, zeroline: false, tickvals: [0, 1, 2, 3, 4, 5, 6], ticktext: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] } }; // To Save the Schedule Data from the Modal var scheduleName = document.getElementById('schedule-name'); var warningMsg = document.getElementById('warning'); var saveButton = document.getElementById('submit-schedule'); var overwriteButton = document.getElementById('overwrite-schedule'); var sunday = document.getElementById('Sunday'); var monday = document.getElementById('Monday'); var tuesday = document.getElementById('Tuesday'); var wednesday = document.getElementById('Wednesday'); var thursday = document.getElementById('Thursday'); var friday = document.getElementById('Friday'); var saturday = document.getElementById('Saturday'); var daysOfWeek = {'Sunday': sunday, 'Monday': monday, 'Tuesday': tuesday, 'Wednesday': wednesday, 'Thursday': thursday, 'Friday': friday, 'Saturday': saturday} var startTime; var endTime; document.getElementById('startTime').addEventListener("input", function (event) { startTime = event.target.value; }); document.getElementById('endTime').addEventListener("input", function (event) { endTime = event.target.value; }); function editSchedule(event) { console.log(event.target.id); // Init Modal from saved dict schedule = savedSchedules[event.target.id]; Object.entries(schedule).forEach(function([key, value]) { if (value) { if (key != 'Name') { var day = document.getElementById(key); day.checked = true; } else { scheduleName.value = value; } var startTime_ = document.getElementById('startTime'); var endTime_ = document.getElementById('endTime'); startTime_.value = value.StartTime; endTime_.value = value.EndTime; } }); modal.style.display = 'block'; }; // Need to validate logical comparators for provided time format? function checkForConflict(c1s, c1e, c2s, c2e) { // case 1 start time, case 1 end time, case 2 start time, case 2 end time // if (c1 intersects c2) or (c2 intersects c1) or (c2 contained in c1) or (c1 contained in c2) or (anything else?) if ( (c1s &gt;= c2s &amp;&amp; c1e &gt;= c2s) || (c1s &lt;= c2s &amp;&amp; c1e &lt;= c2e) || (c1s &lt;= c2s &amp;&amp; c1e &gt;= c2e) || (c1s &gt;= c2s &amp;&amp; c1e &lt;= c2e) ) { return true; } else {return false}; } saveButton.onclick = function() { // Disable save if not all reqd fields filled -&gt; https://stackoverflow.com/questions/39880389/disable-button-until-fields-are-full-pure-js // while (!scheduleName || !startTime || !endTime || !(sunday.checked&amp;&amp;monday.checked&amp;&amp;tuesday.checked&amp;&amp;wednesday.checked&amp;&amp;thursday.checked&amp;&amp;friday.checked&amp;&amp;saturday.checked)) { // saveButton.disabled = true; // } // Check that fields are filled if (!scheduleName || !startTime || !endTime || !sunday.checked&amp;&amp;!monday.checked&amp;&amp;!tuesday.checked&amp;&amp;!wednesday.checked&amp;&amp;!thursday.checked&amp;&amp;!friday.checked&amp;&amp;!saturday.checked) { warningMsg.textContent = "All required fields must contain data"; } // Try to Save the Schedule else { // Check for Schedule Conflicts var conflictData; if (savedSchedules &amp;&amp; Object.keys(savedSchedules).length &gt;= 1) { console.log("At least one schedule detected"); // Loop through saved schedules (key = 'schedule-x') Object.entries(savedSchedules).forEach(function([key, value]) { schedule_ = savedSchedules[key]; // Loop through the schedule (key_ = 'Name', 'Sunday', ...) Object.entries(schedule_).forEach(function([key_, value_]) { // Only check if weekday has a time value and weekdays that are selected if (key_ != 'Name' &amp;&amp; value_ &amp;&amp; daysOfWeek[key_].checked) { // if there is conflict -&gt; store to variable var conflict = checkForConflict(value_.StartTime, value_.EndTime, startTime, endTime); if (conflict) { console.log('Conflict Detected'); conflictData = [key_, `Start: ${value_.StartTime}/${startTime}`, `End: ${value_.EndTime}/${endTime}`]; } } }); }); } // Alert User of Conflict if (conflictData) { console.log(conflictData); warningMsg.textContent = `There is a scheduling conflict ${conflictData}`; overwriteButton.style.display = 'block'; // Handle Conflict Resolution -&gt; Overwrite Schedule, etc } // Save the Schedule else { var dict = { Name: scheduleName.value, Sunday: sunday.checked &amp;&amp; startTime &amp;&amp; endTime ? {StartTime: startTime, EndTime: endTime} : null, Monday: monday.checked &amp;&amp; startTime &amp;&amp; endTime ? {StartTime: startTime, EndTime: endTime} : null, Tuesday: tuesday.checked &amp;&amp; startTime &amp;&amp; endTime ? {StartTime: startTime, EndTime: endTime} : null, Wednesday: wednesday.checked &amp;&amp; startTime &amp;&amp; endTime ? {StartTime: startTime, EndTime: endTime} : null, Thursday: thursday.checked &amp;&amp; startTime &amp;&amp; endTime ? {StartTime: startTime, EndTime: endTime} : null, Friday: friday.checked &amp;&amp; startTime &amp;&amp; endTime ? {StartTime: startTime, EndTime: endTime} : null, Saturday: saturday.checked &amp;&amp; startTime &amp;&amp; endTime ? {StartTime: startTime, EndTime: endTime} : null, } savedSchedules[trackedSchedule] = dict; console.log(savedSchedules); // Add to the graph var randomColor = Math.floor(Math.random()*16777215).toString(16); // Make color indicative of temperature Object.entries(dict).forEach(function([key, value]) { if (key != 'Name' &amp;&amp; value) { data.push({ x: [`${getDate()} ${value.StartTime}`, `${getDate()} ${value.EndTime}`], y: [key, key], hovertext: dict.Name, type: 'scatter', mode: 'markers', marker: { size: 30, color: [randomColor, randomColor], } }); data.push({ x: [`${getDate()} ${value.StartTime}`, `${getDate()} ${value.EndTime}`], y: [key, key], hovertext: scheduleName.value, type: 'scatter', mode: "lines", line: { width: 30, color: randomColor, }, }); }; }); Plotly.newPlot('graph', data, layout); // Create the Dashboard Entry var newLine = document.createElement('div'); newLine.classList.add('list-group-item'); var newButton = document.createElement('div'); newButton.classList.add('add-button'); newButton.id = trackedSchedule; newButton.addEventListener('click', editSchedule); var newTemp = document.createElement('a'); var newName = document.createElement('a'); newName.textContent = scheduleName.value; newName.classList.add('name-font'); var newWeekSet = document.createElement('div'); newWeekSet.classList.add('right-align'); Object.entries(dict).forEach(function([key, value]) { if (key != 'Name') { var newDay = document.createElement('label') // newDay.classList.add('day-font'); newDay.style.display = 'inline-block'; newDay.style.margin = '5px'; newDay.style.fontStyle = 'italic'; var newDayIcon; newDay.textContent = key.charAt(0); if (value) { newDayIcon = document.createElement('i'); newDayIcon.classList.add('far', 'fa-check-circle', 'fa-xs'); // Why doesn't class work for this? newDayIcon.style.display = 'block'; newDayIcon.style.color = 'Blue'; } else { newDayIcon = document.createElement('i'); newDayIcon.classList.add('far', 'fa-times-circle', 'fa-xs'); // Why doesn't class work for this? newDayIcon.style.display = 'block'; newDayIcon.style.color = 'Orange'; } newDay.append(newDayIcon); newWeekSet.appendChild(newDay); }; }); var newMoveIcon = document.createElement('i'); newMoveIcon.classList.add('fas', 'fa-bars'); newMoveIcon.style.display = 'inline-block'; newMoveIcon.style.paddingTop = '10px'; newMoveIcon.style.paddingLeft = '20px' newLine.appendChild(newButton); newLine.appendChild(newName); newLine.appendChild(newWeekSet); newWeekSet.appendChild(newMoveIcon); dashboard.appendChild(newLine); modal.style.display = "none"; } } }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(https://fonts.googleapis.com/css?family=Open+Sans:700,300); body { background: white; font-family: 'Open Sans', Helvetica, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .add-button { display: inline-block; height: 50px; width: 50px; color: orange; padding-left: 18px; padding-top: 10px; background: white; border: 2px solid orange; border-radius: 25px; cursor: pointer; } .name-font { font-size: 2em; padding-left: 35px; } .submit-button { display: inline-block; border: 1px solid orange; border-radius: 5px; height: 40px; background-color: white; cursor: pointer; } .submit-button:hover { background-color: #ffd796 } .clickable { cursor: pointer; } .right-align { float: right; } /* The Modal (background) */ .modal { position: fixed; display: none; padding-left: 75%; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(255,255,255,0.5); } /* Modal Content */ .modal-content { padding: 20px; border: 2px solid orange; height: 100%; overflow: auto; } /* The Close Button */ .close { display: inline; color: gray; float: right; } .close:hover, .close:focus { color: #000; text-decoration: none; cursor: pointer; } /* Checkboxes */ .form-group { display: block; margin-bottom: 5px; } .form-group input { padding: 0; height: initial; width: initial; margin-bottom: 0; display: none; cursor: pointer; } .form-group label { position: relative; cursor: pointer; } .form-group label:before { content:''; -webkit-appearance: none; background-color: transparent; border: 2px solid orange; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05), inset 0px -15px 10px -12px rgba(0, 0, 0, 0.05); padding: 10px; display: inline-block; position: relative; vertical-align: middle; cursor: pointer; margin-right: 5px; } .form-group input:checked + label:after { content: ''; display: block; position: absolute; top: 4px; left: 9px; width: 6px; height: 14px; border: solid orange; border-width: 0 2px 2px 0; transform: rotate(45deg); } /* Clocklet */ .labels { display: block; } .clock { display: block; z-index: 10000; } /* minute - dial, hand, selected tick, hovered tick */ .clocklet-color-example .clocklet-plate { box-shadow: 1px 2px 4px 0 rgba(0, 0, 0, 0.2); border: 1px solid gray; } .clocklet-color-example[data-clocklet-placement="bottom"] { background-color: transparent; border: none; box-shadow: none; } .clocklet-color-example .clocklet-dial--minute { background-color: orange; color: white;} .clocklet-color-example .clocklet-hand--minute { background-color: white; border: 1px solid gray; width: 3px;} .clocklet-color-example .clocklet-tick--minute.clocklet-tick--selected { background-color: white; color: orange;} .clocklet-color-example.clocklet--hoverable:not(.clocklet--dragging) .clocklet-tick--minute:hover { background-color: white; color: orange;} /* hour - dial, hand, selected tick, hovered tick */ .clocklet-color-example .clocklet-dial--hour { background-color: white; } .clocklet-color-example .clocklet-hand--hour { background-color: white; border: 1px solid gray; width: 3px;} .clocklet-color-example .clocklet-tick--hour.clocklet-tick--selected { background-color: orange; } .clocklet-color-example.clocklet--hoverable:not(.clocklet--dragging) .clocklet-tick--hour:hover { background-color: orange; } /* hand origin */ .clocklet-color-example .clocklet-hand-origin { background-color: gray; } /* ampm */ .clocklet-color-example .clocklet-ampm::before { background-color: orange; } .clocklet-color-example .clocklet-ampm:hover::before { background-color: white; color: orange; border: 1px solid orange;} .clocklet-color-example .clocklet-ampm[data-clocklet-ampm="pm"]::before { background-color: orange; } .clocklet-color-example .clocklet-ampm[data-clocklet-ampm="pm"]:hover::before { background-color: white; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://kit.fontawesome.com/6873aa3c17.js" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;!-- Sortable --&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.10.1/Sortable.min.js"&gt;&lt;/script&gt; &lt;!-- Plotly --&gt; &lt;script src="https://cdn.plot.ly/plotly-latest.min.js"&gt;&lt;/script&gt; &lt;!-- Clocklet --&gt; &lt;link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/clocklet@0.2.4/css/clocklet.min.css"&gt; &lt;script src="https://cdn.jsdelivr.net/npm/clocklet@0.2.4"&gt;&lt;/script&gt; &lt;!-- List with handle --&gt; &lt;div id="dashboard" class="list-group"&gt; &lt;div class="list-group-item"&gt; &lt;div id='add' class='add-button'&gt;&lt;i class="fas fa-plus fa-xs"&gt;&lt;/i&gt;&lt;/div&gt; &lt;a style="font-size: 1em; padding-left: 35px"&gt;Add Schedule&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="modal" class="modal"&gt; &lt;div class="modal-content"&gt; &lt;div&gt; &lt;h1 style='display: inline'&gt;Edit Schedule&lt;/h1&gt; &lt;div class="close"&gt;&lt;i class="fas fa-times"&gt;&lt;/i&gt;&lt;/div&gt; &lt;/div&gt; &lt;form&gt; &lt;input id='schedule-name' type='text' value='Test'&gt;&lt;/input&gt; &lt;label class='labels' for='startTime'&gt;Start Time&lt;/label&gt; &lt;input id='startTime' class="clock" value="12:34 A.M." data-clocklet="class-name: clocklet-color-example; format: h:mm AA; alignment: right; placement: bottom;" placeholder="h:mm AA"&gt; &lt;label class='labels' for='endTime'&gt;End Time&lt;/label&gt; &lt;input id='endTime' class="clock" value="1:35 P.M." data-clocklet="class-name: clocklet-color-example; format: h:mm AA; alignment: right; placement: bottom;" placeholder="h:mm AA"&gt; &lt;br&gt;&lt;br&gt; &lt;div class="form-group"&gt; &lt;input type="checkbox" id="Sunday" checked='true'&gt; &lt;label for="Sunday"&gt;Sunday&lt;/label&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="checkbox" id="Monday"&gt; &lt;label for="Monday"&gt;Monday&lt;/label&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="checkbox" id="Tuesday"&gt; &lt;label for="Tuesday"&gt;Tuesday&lt;/label&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="checkbox" id="Wednesday"&gt; &lt;label for="Wednesday"&gt;Wednesday&lt;/label&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="checkbox" id="Thursday"&gt; &lt;label for="Thursday"&gt;Thursday&lt;/label&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="checkbox" id="Friday"&gt; &lt;label for="Friday"&gt;Friday&lt;/label&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="checkbox" id="Saturday"&gt; &lt;label for="Saturday"&gt;Saturday&lt;/label&gt; &lt;/div&gt; &lt;/form&gt; &lt;!-- Add temperature selector =&gt; slider? --&gt; &lt;!-- Add ability to select room/zones for schedule --&gt; &lt;a id='warning' style='color: Red'&gt;&lt;/a&gt; &lt;button id='submit-schedule' class="submit-button"&gt;Create Schedule&lt;/button&gt; &lt;button id='overwrite-schedule' class="submit-buttom" style='display: none'&gt;Overwrite Schedule&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id='graph'&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p>First post here - I hope I understand the purpose/intent of the community. I am trying to create a temperature scheduler for HVAC management WebUI using Js (although you wont find anything in the code currently about setting the temperature). The purpose of the code review is associated with the scheduling conflict algorithm &amp; code. I.e. at no point should there be a duplicate temperature setting for a given day of the week or time (or room - to come later).</p> <p>I am hoping to see if there are any suggestions for improving my schedule conflict detecting algorithm - I'm not entirely happy with it since the logic is difficult to read in my opinion. Find code (lots of omissions so if something is unclear let me know) and CodePen link (with no omissions) below - thanks in advance for any answers! </p> <pre><code> var scheduleName = document.getElementById('schedule-name'); var warningMsg = document.getElementById('warning'); var saveButton = document.getElementById('submit-schedule'); var sunday = document.getElementById('Sunday'); // checkbox var monday = document.getElementById('Monday'); // checkbox var tuesday = document.getElementById('Tuesday'); // checkbox var wednesday = document.getElementById('Wednesday'); // checkbox var thursday = document.getElementById('Thursday'); // checkbox var friday = document.getElementById('Friday'); // checkbox var saturday = document.getElementById('Saturday'); // checkbox var daysOfWeek = {'Sunday': sunday, 'Monday': monday, 'Tuesday': tuesday, 'Wednesday': wednesday, 'Thursday': thursday, 'Friday': friday, 'Saturday': saturday} function checkForConflict(c1s, c1e, c2s, c2e) { // case 1 start time, case 1 end time, case 2 start time, case 2 end time // if (c1 intersects c2) or (c2 intersects c1) or (c2 contained in c1) or (c1 contained in c2) or (anything else?) if ( (c1s &gt;= c2s &amp;&amp; c1e &gt;= c2s) || (c1s &lt;= c2s &amp;&amp; c1e &lt;= c2e) || (c1s &lt;= c2s &amp;&amp; c1e &gt;= c2e) || (c1s &gt;= c2s &amp;&amp; c1e &lt;= c2e) ) { return true; } else {return false}; } saveButton.onclick = function() { // Check that fields are filled if (!scheduleName || !startTime || !endTime || !sunday.checked&amp;&amp;!monday.checked&amp;&amp;!tuesday.checked&amp;&amp;!wednesday.checked&amp;&amp;!thursday.checked&amp;&amp;!friday.checked&amp;&amp;!saturday.checked) { warningMsg.textContent = "All required fields must contain data"; } // Try to Save the Schedule else { // Check for Schedule Conflicts var conflictData; if (savedSchedules &amp;&amp; Object.keys(savedSchedules).length &gt;= 1) { console.log("At least one schedule detected"); // Loop through saved schedules (key = 'schedule-x') Object.entries(savedSchedules).forEach(function([key, value]) { schedule_ = savedSchedules[key]; // Loop through the schedule (key_ = 'Name', 'Sunday', ...) Object.entries(schedule_).forEach(function([key_, value_]) { // Only check if weekday has a time value and weekdays that are selected if (key_ != 'Name' &amp;&amp; value_ &amp;&amp; daysOfWeek[key_].checked) { // if there is conflict -&gt; store to variable var conflict = checkForConflict(value_.StartTime, value_.EndTime, startTime, endTime); if (conflict) { console.log('Conflict Detected'); conflictData = [key_, `Start: ${value_.StartTime}/${startTime}`, `End: ${value_.EndTime}/${endTime}`]; } } }); }); } // Alert User of Conflict if (conflictData) { console.log(conflictData); warningMsg.textContent = `There is a scheduling conflict ${conflictData}: - Cannot proceed...`; // Handle Conflict Resolution -&gt; Overwrite Schedule, etc } // Save the Schedule else {...} </code></pre> <p>The format of <code>savedSchedules</code> looks like this:</p> <pre><code>{ schedule-1: { Name: &lt;Some String&gt;, Sunday: null, Monday: null, Tuesday: null, Wednesday: null, Thursday: null, Friday: null, Saturday: {StartTime: 12:55 A.M., EndTime: 1:35 P.M.} }, schedule-2: {...}, ... } </code></pre> <p>To me, the <code>// Check for Schedule Conflicts</code> block is pretty rough in terms of being concise both in logic and in length. I would appreciate a second set of more experienced eyes that might confirm that this is pretty sound logic/structure or provide a much better alternative.</p> <p>Link to <a href="https://codepen.io/sterlingbutters/pen/BaNqVPJ" rel="nofollow noreferrer">CodePen</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T20:46:02.807", "Id": "470866", "Score": "0", "body": "Please can you add more description on what this is achieving. Currently it's unclear from the text what this is doing. Are you scheduling flights, a holiday, time out with friends, business meetings... How do the schedules interact with each other?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T21:17:21.797", "Id": "470870", "Score": "1", "body": "@Graipher I added full code in snippet" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T21:17:46.530", "Id": "470871", "Score": "1", "body": "@Peilonrayz I added a little more to description in edit, let me know if still unclear" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T21:48:15.557", "Id": "470874", "Score": "0", "body": "It seems more clear. Whether others agree and don't add more close votes / retract existing ones I can't say." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T22:44:39.597", "Id": "470876", "Score": "0", "body": "@Peilonrayz Thanks, I care less about my rep here thankfully - was just happy to get a good answer" } ]
[ { "body": "<p>Your retrieval of checkboxes is a bit verbose. Consider using a single selector to get all of them instead, instead of having to select each one individually.</p>\n\n<pre><code>const daysOfWeek = {};\nfor (const input of document.querySelectorAll('.form-group &gt; input[type=\"checkbox\"]') {\n daysOfWeek[input.id] = input;\n}\n</code></pre>\n\n<p>Then, rather than examining each separate variable to see if it's checked, iterate over that object to see if any values are checked.</p>\n\n<p>To avoid indentation hell, consider <code>return</code>ing early when an error is encountered, rather than a very large <code>else</code> block when there isn't an error.</p>\n\n<p>Your <code>savedSchedules</code> is an object which is never reassigned:</p>\n\n<pre><code>var savedSchedules = {};\n</code></pre>\n\n<p>So it'll always be truthy - the <code>if (savedSchedules &amp;&amp;</code> check is superfluous, since it'll always be true.</p>\n\n<p>There's also no need to check how many keys the object has beforehand - just iterate through them all regardless. If there aren't any, then no conflicts will be detected. So the <code>Object.keys(savedSchedules).length &gt;= 1</code> can be removed.</p>\n\n<p><code>Object.entries</code>'s callback accepts an entry array parameter of the key and the value. Since you already have the value as a variable, there's no need to select it <em>again</em> by going through the <code>[key]</code>:</p>\n\n<pre><code>Object.entries(savedSchedules).forEach(function([key, value]) {\n schedule_ = savedSchedules[key];\n</code></pre>\n\n<p>simplifies to</p>\n\n<pre><code>Object.entries(savedSchedules).forEach(function([key, schedule_]) {\n</code></pre>\n\n<p>But since you aren't actually using the schedule name (the <code>key</code>), you may as well remove it and use <code>Object.values</code> instead:</p>\n\n<pre><code>Object.values(savedSchedules).forEach(function(schedule_) {\n</code></pre>\n\n<p>But since you're trying to find whether there are <em>any</em> conflicts, it would be more appropriate to short-circuit when a problem is found. Consider using a <code>for</code> loop instead. When a problem is found, tell the user about it and <code>return</code>.</p>\n\n<p>The underscores after the variable names are confusing - they don't match a convention I know of. It looks like they're meant to distinguish a single schedule's object from the day and object value for the day. I think it would be appropriate to note this in the variable names explicitly, eg <code>schedule</code>, <code>day</code>, and <code>dayObj</code>.</p>\n\n<p>Also, since you're using <code>Object.entries</code>, your environment supports ES6 - in ES6, you should <a href=\"https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75\" rel=\"nofollow noreferrer\">always use <code>const</code></a> to declare variables when possible, never <code>var</code> (and <code>let</code> only when you have to reassign).</p>\n\n<p>The <code>startTime</code> variable name (which comes from the input) is a bit unclear once you're deep into the verification stage and are comparing against <code>value_.StartTime</code> variable name. Maybe call the input variable <code>inputStartTime</code> (and the same for <code>endTime</code>) to reduce possible confusion?</p>\n\n<p>The conflict checker is a decent chunk of code that probably deserves to be in its own function. This allows you to see a decent overview of the whole click process from the click listener without having to scroll through large amounts of code to get a general idea.</p>\n\n<p>Assigning to <code>onclick</code> should usually be avoided. It can work if done <em>once</em>, but if <em>any other</em> code follows the same bad practices and ever tries to do the same thing, your prior listener will be overwritten. Best to always use <code>addEventListener</code> instead.</p>\n\n<p>In full:</p>\n\n<pre><code>const daysOfWeek = {};\nfor (const input of document.querySelectorAll('.form-group &gt; input[type=\"checkbox\"]')) {\n daysOfWeek[input.id] = input;\n}\nconst getConflicts = () =&gt; {\n for (const schedule of Object.values(savedSchedules)) {\n // Loop through the schedule (key_ = 'Name', 'Sunday', ...)\n for (const [day, dayObj] of Object.entries(schedule)) {\n // Only check if weekday has a time value and weekdays that are selected\n if (day === 'Name' || !dayObj || !daysOfWeek[day].checked) {\n continue;\n }\n // if there is conflict, return it\n const conflict = checkForConflict(dayObj.StartTime, dayObj.EndTime, inputStartTime, inputEndTime);\n if (conflict) {\n console.log('Conflict Detected');\n const conflictData = [day, `Start: ${dayObj.StartTime}/${inputStartTime}`, `End: ${dayObj.EndTime}/${inputEndTime}`];\n return `There is a scheduling conflict ${conflictData}: - Cannot proceed...`;\n }\n }\n }\n};\nsaveButton.addEventListener('click', () =&gt; {\n // Check that fields are filled\n if (!scheduleName || !inputStartTime || !inputEndTime || Object.values(daysOfWeek).every(input =&gt; !input.checked)) {\n warningMsg.textContent = 'All required fields must contain data';\n return;\n }\n // Check for Schedule Conflicts\n const conflictsMessage = getConflicts();\n if (conflictsMessage) {\n // Handle Conflict Resolution -&gt; Overwrite Schedule, etc\n // Probably CALL A FUNCTION HERE, don't write it all inside this click listener\n return;\n }\n // Save the Schedule\n\n // ...\n});\n</code></pre>\n\n<p>The generation of the <code>schedule</code> object isn't shown, but it would be great not to have to do the <code>if (day === 'Name'</code> check - rather than combining the schedule name with the day keys, consider putting the days into a completely separate property, eg:</p>\n\n<pre><code>{\n scheduleName: 'schedule-1',\n days: {\n Sunday: ...\n Monday: ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T00:54:05.040", "Id": "470743", "Score": "0", "body": "Wow thank you for such a detailed answer! Definitely the kind of input I was hoping to find on this forum. Very very helpful - thanks again!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T00:10:49.817", "Id": "240014", "ParentId": "240011", "Score": "3" } } ]
{ "AcceptedAnswerId": "240014", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-05T23:18:21.660", "Id": "240011", "Score": "3", "Tags": [ "javascript" ], "Title": "(Js) Schedule Conflict Detection Algorithm Logic & Length" }
240011
<p>I always try to port the roman numeral conversion algorithm to learn new languages. Reading the Go manual as a beginner, this is the most idiomatic way I've been able to write it.</p> <p>I would love it if you could give me comments/advice on the following code, and also maybe on some questions I have regarding it:</p> <ul> <li>About the <code>found := false</code> flag, is there a better way of doing this? And by that I mean: breaking from a loop while storing a value? Because I cannot assign the variable <code>matchingGlyph</code> to <code>nil</code> to display <em>not-found-ness</em>, the only way I could think of was to have a separate flag.</li> <li>At what spots am I under-doing it or over-doing it?</li> <li>How does it look from a modern Go perspective?</li> <li>How is my error management?</li> </ul> <p>What I know could be improved, but chose not to implement: roman glyphs order validation. Right now the code implements error handling for invalid glyphs, but doesn't handle invalid ordering like <code>XIVMM</code> (in lieu of <code>MMXIV</code>). Both would produce <code>2014</code>, but the ordering of the former is invalid.</p> <p>Thank you!</p> <p><strong>roman.go</strong></p> <pre class="lang-golang prettyprint-override"><code>package main import ( "fmt" "strings" ) // RomanGlyph contains a roman numeral and its base 10 integer equivalent type RomanGlyph struct { numeral string value int } // RomanGlyphsByNumeral is a dictionary of roman numeral glyphs to their base 10 integer equivalents // Ordered for efficient matching in RomanNumberToInt var RomanGlyphsByNumeral = []RomanGlyph{ {"CM", 900}, {"M", 1000}, {"CD", 400}, {"D", 500}, {"XC", 90}, {"C", 100}, {"XL", 40}, {"L", 50}, {"IX", 9}, {"X", 10}, {"IV", 4}, {"V", 5}, {"I", 1}, } // RomanGlyphsByValue is a dictionary of roman numeral glyphs to their base 10 integer equivalents // Ordered for efficient matching in IntToRomanNumber var RomanGlyphsByValue = []RomanGlyph{ {"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400}, {"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40}, {"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4}, {"I", 1}, } // RomanNumberToInt converts a roman number to its base 10 integer equivalent func RomanNumberToInt(romanNumber string) (result int, err error) { count := len(romanNumber) runes := []rune(romanNumber) i := 0 for i &lt; count { substring := string(runes[i:count]) found := false var matchingGlyph RomanGlyph for _, glyph := range RomanGlyphsByNumeral { if strings.HasPrefix(substring, glyph.numeral) { found = true matchingGlyph = glyph break } } if !found { return 0, fmt.Errorf("Cannot find valid roman numeral at %v", substring) } result += matchingGlyph.value i += len(matchingGlyph.numeral) } return result, nil } // IntToRomanNumber converts a base 10 integer to its roman number equivalent func IntToRomanNumber(number int) (result string, err error) { if number &lt; 1 { return "", fmt.Errorf("Integer argument `number` should be greater than 1. Received %v", number) } for _, romanGlyph := range RomanGlyphsByValue { for number &gt;= romanGlyph.value { result += romanGlyph.numeral number -= romanGlyph.value } } return result, nil } </code></pre> <p><strong>roman_test.go</strong></p> <pre class="lang-golang prettyprint-override"><code>package main import "testing" var samples = []struct { value int numeral string }{ {2014, "MMXIV"}, {1993, "MCMXCIII"}, {1111, "MCXI"}, {444, "CDXLIV"}, } func TestRoman(t *testing.T) { // Test failure for converting integer 0 to a roman numeral _, zeroErr := IntToRomanNumber(0) if zeroErr == nil { t.Error("Converting int 0 to roman should have failed") } // Test failure for converting invalid roman numerals to int _, invalidNumeralErr := RomanNumberToInt("XAV") if invalidNumeralErr == nil { t.Error("Converting roman 'XAV' to int should have failed because A is not a valid roman numeral") } // Test samples for _, sample := range samples { result, err := IntToRomanNumber(sample.value) if err != nil { t.Errorf("Sample int %v should have produced numeral %v. Failed with %v", sample.value, sample.numeral, err) } else if result != sample.numeral { t.Errorf("Sample int %v should have produced numeral %v. Got %v", sample.value, sample.numeral, result) } } // Test roundtrip conversion for numbers 1..2000 for i := 1; i &lt;= 2000; i++ { roman, err := IntToRomanNumber(i) if err != nil { t.Fatal(err) } backToI, err := RomanNumberToInt(roman) if err != nil { t.Fatal(err) } if i != backToI { t.Errorf("Number %v failed roundtrip: %v &gt; %v &gt; %v", i, i, roman, backToI) } } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<blockquote>\n <p>How is my error management? </p>\n</blockquote>\n\n<p><a href=\"https://github.com/golang/go/wiki/CodeReviewComments#error-strings\" rel=\"nofollow noreferrer\">Error</a> strings should not be capitalized (unless beginning with proper nouns or acronyms) or end with punctuation, since they are usually printed following other context. That is, use <code>fmt.Errorf(\"something bad\")</code> not <code>fmt.Errorf(\"Something bad\")</code>, so that <code>log.Printf(\"Reading %s: %v\", filename, err)</code> formats without a spurious capital letter mid-message. This does not apply to logging, which is implicitly line-oriented and not combined inside other messages.</p>\n\n<p>And see standard library <code>src/io/io.go</code> examples: </p>\n\n<pre><code>// ErrShortBuffer means that a read required a longer buffer than was provided.\nvar ErrShortBuffer = errors.New(\"short buffer\")\n\n// EOF is the error returned by Read when no more input is available.\n// Functions should return EOF only to signal a graceful end of input.\n// If the EOF occurs unexpectedly in a structured data stream,\n// the appropriate error is either ErrUnexpectedEOF or some other error\n// giving more detail.\nvar EOF = errors.New(\"EOF\")\n</code></pre>\n\n<p>You don't need <code>found := false</code> flag, see 5, and for the final polished code see 8:</p>\n\n<hr>\n\n<p>Code review:<br>\n1. Inside <code>func IntToRomanNumber(number int)</code>, the: </p>\n\n<pre><code>return \"\", fmt.Errorf(\"Integer argument `number` should be greater than 1. Received %v\", number)\n</code></pre>\n\n<p>Should be greater than <strong>zero</strong>: </p>\n\n<pre><code>return \"\", fmt.Errorf(\"integer argument `number` should be greater than 0, received %v\", number)\n</code></pre>\n\n<ol start=\"2\">\n<li>Using <code>strings.Builder</code> is a good habit.</li>\n<li>Use <code>(string, error)</code> instead of <code>(result string, err error)</code> for function return values. </li>\n<li>See standard library for sub-string <code>s = strings.TrimPrefix(s, glyph.numeral)</code>: </li>\n</ol>\n\n<pre><code>// TrimPrefix returns s without the provided leading prefix string.\n// If s doesn't start with prefix, s is returned unchanged.\nfunc TrimPrefix(s, prefix string) string {\n if HasPrefix(s, prefix) {\n return s[len(prefix):]\n }\n return s\n}\n</code></pre>\n\n<ol start=\"5\">\n<li>About the <code>found := false</code> flag: </li>\n</ol>\n\n<pre><code>func RomanNumberToInt(s string) (int, error) {\n result := 0\nScanningGlyphs:\n for len(s) &gt; 0 {\n for _, glyph := range RomanGlyphsByNumeral {\n if strings.HasPrefix(s, glyph.numeral) {\n s = s[len(glyph.numeral):] // s = strings.TrimPrefix(s, glyph.numeral)\n result += glyph.value\n continue ScanningGlyphs\n }\n }\n return 0, fmt.Errorf(\"cannot find valid roman numeral at %v\", s)\n }\n return result, nil\n}\n</code></pre>\n\n<ol start=\"6\">\n<li><a href=\"https://www.crosswordunclued.com/2010/06/roman-numerals.html\" rel=\"nofollow noreferrer\">The Classic Roman Numeral Mistake</a>: \n\n<blockquote>\n <p>On the face of it, IL and IC appear to follow the same subtractive principle as IV and IX, i.e. IL = L (50) - I (1) = 49.<br>\n This is actually not valid.<br>\n The subtractive principle for Roman numbers has these restrictions:<br>\n You can only subtract a power of ten, and only from the next two higher \"digits\", where the digits are {I, V, X, L, C, D, M}.<br>\n That is, only I, X and C can be subtracted, AND I can be subtracted only from V and X; X can be subtracted only from L and C; C can be subtracted only from D and M.<br>\n By these rules, the Roman numerals IL for 49 and IC for 99 do not work.<br>\n The correct representation for 49 is XLIX, for 99 is XCIX.</p>\n</blockquote></li>\n</ol>\n\n<p>So the <code>RomanNumberToInt(\"IC\")</code> should return error not 101:</p>\n\n<pre><code>// 0 value means invalid glyph.\nvar RomanGlyphsByNumeral = []RomanGlyph{\n {\"IM\", 0}, {\"VM\", 0}, {\"XM\", 0}, {\"LM\", 0}, {\"CM\", 900}, {\"DM\", 0}, {\"M\", 1000},\n {\"ID\", 0}, {\"VD\", 0}, {\"XD\", 0}, {\"LD\", 0}, {\"CD\", 400}, {\"D\", 500},\n {\"IC\", 0}, {\"VC\", 0}, {\"XC\", 90}, {\"LC\", 0}, {\"C\", 100},\n {\"IL\", 0}, {\"VL\", 0}, {\"XL\", 40}, {\"L\", 50},\n {\"IX\", 9}, {\"VX\", 0}, {\"X\", 10},\n {\"IV\", 4}, {\"V\", 5},\n {\"I\", 1},\n}\nfunc RomanNumberToInt(s string) (int, error) {\n result := 0\nScanningGlyphs:\n for len(s) &gt; 0 {\n for _, glyph := range RomanGlyphsByNumeral {\n if strings.HasPrefix(s, glyph.numeral) {\n if glyph.value == 0 {\n return 0, fmt.Errorf(\"invalid roman glyph %q\", glyph.numeral)\n }\n s = s[len(glyph.numeral):] // s = strings.TrimPrefix(s, glyph.numeral)\n result += glyph.value\n continue ScanningGlyphs\n }\n }\n return 0, fmt.Errorf(\"cannot find valid roman numeral at %v\", s)\n }\n return result, nil\n}\n</code></pre>\n\n<ol start=\"7\">\n<li><a href=\"https://en.wikipedia.org/wiki/Glyph\" rel=\"nofollow noreferrer\">In typography, a glyph is an elemental symbol within an agreed set of symbols</a>, so naming the <code>RomanGlyph</code> struct:</li>\n</ol>\n\n<pre><code>type RomanGlyph struct {\n numeral string\n value int\n}\n</code></pre>\n\n<p>Is more readable this way:</p>\n\n<pre><code>// Roman struct contains a roman glyph and its base 10 integer equivalent.\ntype Roman struct {\n glyph string\n value int\n}\n</code></pre>\n\n<hr>\n\n<ol start=\"8\">\n<li>If you are in the <code>main</code> you don't need to export (Capitalize) anything, otherwise only export intended items, and name the package <code>roman</code> then function name will be used as <code>roman.RomanGlyphToInt</code> by other packages, and that stutters; consider calling this <code>GlyphToInt</code>:</li>\n</ol>\n\n<p><code>roman/roman.go</code> file:</p>\n\n<pre><code>// Package roman implements simple functions to convert roman glyphs to and from int.\n// See example.\npackage roman\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\n// roman struct contains a roman glyph and its base 10 integer equivalent.\ntype roman struct {\n glyph string\n value int\n}\n\n// romanGlyphs is a list of roman glyphs and their base 10 integer equivalents.\n// Ordered for efficient matching in RomanGlyphToInt.\n// 0 value means invalid glyph.\nvar romanGlyphs = []roman{\n {\"IM\", 0}, {\"VM\", 0}, {\"XM\", 0}, {\"LM\", 0}, {\"CM\", 900}, {\"DM\", 0}, {\"M\", 1000},\n {\"ID\", 0}, {\"VD\", 0}, {\"XD\", 0}, {\"LD\", 0}, {\"CD\", 400}, {\"D\", 500},\n {\"IC\", 0}, {\"VC\", 0}, {\"XC\", 90}, {\"LC\", 0}, {\"C\", 100},\n {\"IL\", 0}, {\"VL\", 0}, {\"XL\", 40}, {\"L\", 50},\n {\"IX\", 9}, {\"VX\", 0}, {\"X\", 10},\n {\"IV\", 4}, {\"V\", 5},\n {\"I\", 1},\n}\n\n// GlyphToInt returns an equivalent integer number in base 10 with error value.\n// You can only subtract a power of ten, and only from the next two higher \"digits\",\n// where the digits are {I, V, X, L, C, D, M}.\n// only I, X and C can be subtracted, AND I can be subtracted only from V and X;\n// X can be subtracted only from L and C; C can be subtracted only from D and M.\nfunc GlyphToInt(s string) (int, error) {\n s = strings.ToUpper(s)\n result := 0\nScanningGlyphs:\n for len(s) &gt; 0 {\n for _, glyph := range romanGlyphs {\n if strings.HasPrefix(s, glyph.glyph) {\n if glyph.value == 0 {\n return 0, fmt.Errorf(\"invalid roman glyph %q\", glyph.glyph)\n }\n s = s[len(glyph.glyph):] // s = strings.TrimPrefix(s, glyph.glyph)\n result += glyph.value\n continue ScanningGlyphs\n }\n }\n return 0, fmt.Errorf(\"cannot find valid roman glyph at %q\", s)\n }\n return result, nil\n}\n\n// romanGlyphsByValue is a list of roman glyphs to their base 10 integer equivalents.\n// Ordered for efficient matching in IntToGlyph.\nvar romanGlyphsByValue = []roman{\n {\"M\", 1000}, {\"CM\", 900}, {\"D\", 500}, {\"CD\", 400},\n {\"C\", 100}, {\"XC\", 90}, {\"L\", 50}, {\"XL\", 40},\n {\"X\", 10}, {\"IX\", 9}, {\"V\", 5}, {\"IV\", 4},\n {\"I\", 1},\n}\n\n// IntToGlyph converts a base 10 integer to its roman equivalent glyph.\nfunc IntToGlyph(n int) (string, error) {\n if n &lt;= 0 {\n return \"\", fmt.Errorf(\"integer number should be greater than 0, received %d\", n)\n }\n var result strings.Builder\n for _, roman := range romanGlyphsByValue {\n for n &gt;= roman.value {\n n -= roman.value\n result.WriteString(roman.glyph)\n }\n }\n // if n != 0 || result.Len() == 0 {\n // panic(\"needs developer attention: romanGlyphsByValue list values must be &gt; 1\") // or test all values and remove this\n // }\n return result.String(), nil\n}\n</code></pre>\n\n<p><code>roman/roman_test.go</code> file:</p>\n\n<pre><code>package roman\n\nimport \"testing\"\n\nvar samples = []struct {\n value int\n glyph string\n}{\n {2014, \"MMXIV\"},\n {1993, \"MCMXCIII\"},\n {1111, \"MCXI\"},\n {444, \"CDXLIV\"},\n}\n\nfunc TestRoman(t *testing.T) {\n // Test failure for converting integer 0 to a roman glyph\n _, zeroErr := IntToGlyph(0)\n if zeroErr == nil {\n t.Error(\"Converting int 0 to roman should have failed\")\n }\n\n // Test failure for converting invalid roman glyphs to int\n _, invalidNumeralErr := GlyphToInt(\"XAV\")\n if invalidNumeralErr == nil {\n t.Error(\"Converting roman 'XAV' to int should have failed because A is not a valid roman glyph\")\n }\n\n // Test failure for converting invalid roman glyphs to int\n _, invalidNumeralErr = GlyphToInt(\"IC\")\n if invalidNumeralErr == nil {\n t.Error(\"Converting roman 'IC' to int should have failed because A is not a valid roman glyph\")\n }\n\n // Test samples\n for _, sample := range samples {\n result, err := IntToGlyph(sample.value)\n if err != nil {\n t.Errorf(\"Sample int %v should have produced glyph %v. Failed with %v\", sample.value, sample.glyph, err)\n } else if result != sample.glyph {\n t.Errorf(\"Sample int %v should have produced glyph %v. Got %v\", sample.value, sample.glyph, result)\n }\n }\n\n // Test roundtrip conversion for numbers 1..2000\n for i := 1; i &lt;= 2000; i++ {\n roman, err := IntToGlyph(i)\n if err != nil {\n t.Fatal(err)\n }\n backToI, err := GlyphToInt(roman)\n if err != nil {\n t.Fatal(err)\n }\n if i != backToI {\n t.Errorf(\"Number %v failed roundtrip: %v &gt; %v &gt; %v\", i, i, roman, backToI)\n }\n }\n}\n</code></pre>\n\n<p>Test output:</p>\n\n<pre><code>ok roman 0.038s coverage: 100.0% of statements\nSuccess: Tests passed.\n</code></pre>\n\n<ol start=\"9\">\n<li>Usage example (<code>example/main.go</code> file):</li>\n</ol>\n\n<pre><code>func main() {\n n, err := roman.GlyphToInt(\"CC\")\n if err != nil {\n log.Fatal(err)\n }\n fmt.Println(n) // 200\n\n s, err := roman.IntToGlyph(2020)\n if err != nil {\n log.Fatal(err)\n }\n fmt.Println(s) // MMXX\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T14:41:28.110", "Id": "471386", "Score": "0", "body": "Additionally, [error strings should not be capitalized or end with punctuation](https://github.com/golang/go/wiki/CodeReviewComments#error-strings)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T14:46:15.897", "Id": "471387", "Score": "0", "body": "In `IntToGlyph` it might also be better to remove the initial check for `n <= 0` and instead, after the loop check `if n != 0 || result.Len() == 0 { return \"\", errors.New(\"some failure message here\") }`. Among other things it catches more failures (e.g. an algorithm or table error)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T14:47:44.980", "Id": "471388", "Score": "0", "body": "In `GlyphToInt` I'd make the first step be `s = strings.ToUpper(s)` to support arbitrarily cased input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T16:02:48.817", "Id": "471397", "Score": "0", "body": "@DaveC: First and last comments applied, for the second comment putting `if n<= 0` at top is performance wise and lean, so I would keep it, then the option is to add another `if n != 0 || result.Len() == 0 { return \"\", errors.New(\"some failure message here\") }` after the loop which makes coverage: below 100.0%, since coverage tests this problem so it is redundant. and makes coverage below 100.0%. Thank you for the comment." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T14:03:09.300", "Id": "240338", "ParentId": "240019", "Score": "3" } } ]
{ "AcceptedAnswerId": "240338", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T03:12:04.147", "Id": "240019", "Score": "5", "Tags": [ "beginner", "go", "roman-numerals" ], "Title": "Roman numerals isomorphic conversion in Go" }
240019
<p>After some hours of coding trying to implement "algorithms" to make a Tic-Tac-Toe game, I came up with something I'm not really proud of.</p> <p>Here's the code:</p> <pre><code>const TicTacToe = (function(){ const grids = document.querySelectorAll(".box"); const winning_combinations = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ]; let turn = 'X'; let marks = 0; let currPos = void 0; for(let i = 0, len = grids.length; i &lt; len; ++i) grids[i].addEventListener("click", () =&gt; mark( (currPos=i) ) ); function mark(pos){ if(grids[currPos].textContent != '') return alert("grid taken!"); grids[currPos].textContent = turn; if(!foundWinner()) turn = (turn === 'X') ? 'O' : 'X'; else win(); } function foundWinner(){ for(let currSet = 0, len = winning_combinations.length; currSet &lt; len; ++currSet){ winning_combinations[currSet].forEach(pos =&gt; { if(grids[pos].textContent == turn){ marks++; } }); if(marks == 3){ return true; } else{ marks = 0; } } return false; } function win(){ return alert(turn + " won!"); } return{ reset: function(){ // todo } } }) (); </code></pre> <p>The issue is that I am pretty sure this code has <code>O(n log n)</code> time complexity, and I would love to make it at least <code>O(n)</code>. I've tried creating possible combinations based on what grid the player pressed—opposed to trying all the winning combinations—but no avail.</p> <p>If there is any way I can better this code or make it more efficient, please let me know!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T03:33:16.000", "Id": "470750", "Score": "0", "body": "Computational complexity is *usually* only something to worry about when you have inputs of significant sizes. If you have a static 3x3 grid with a static 8 possible winning positions to iterate over, I don't see what a theoretical bottleneck could be; those numbers are very small. (unless something is auto-clicking and restarting games in a very tight loop, which sounds like it isn't the case)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T05:36:03.057", "Id": "470755", "Score": "0", "body": "Can you clarify the sort of performance improvements you're looking for?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T03:14:00.387", "Id": "240020", "Score": "3", "Tags": [ "javascript", "tic-tac-toe" ], "Title": "Simple Tic-Tac-Toe game in Javascript (NO A.I.)" }
240020
<p><a href="https://i.stack.imgur.com/b1D9y.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b1D9y.jpg" alt="enter image description here"></a></p> <p>I'm working towards plotting a large GIS dataset of which I've shown a sample above of about 1/6 of the data. I'm happy with how quickly the data loads in, and <code>bokeh</code> renders the html nearly instantaneously. However, I've encountered a pretty hot loop in my code that is not scaling well as I increase the 1) number of rows and 2) resolution of the polygons. I'm just getting killed in the <code>#count points</code> loop and am wondering if there isn't a better way of doing this? </p> <p>I found the suggestion for a loop off a GIS readthedoc.io and was happy with its performance for a few thousand points a couple months ago. But now the project needs to process a <code>GeoDataFrame</code> with >730000 rows. Is there a better method I'm suppose to be using to count the number of points in each polygon? I'm on a modern desktop to do the computation but the project has access to Azure resources so maybe that's most people professionally do this sort of computation? I'd prefer to do the computation locally but it means my desktop might have to sit at max cpu cycles overnight or longer which isn't a thrilling prospect. I'm using Python 3.8.2 &amp; Conda 4.3.2.</p> <pre><code>from shapely.geometry import Polygon import pysal.viz.mapclassify as mc import geopandas as gpd def count_points(main_df, geo_grid, levels=5): """ outputs a gdf of polygons with a columns of classifiers to be used for color mapping """ pts = gpd.GeoDataFrame(main_df["geometry"]).copy() #counts points pts_in_polys = [] for i, poly in geo_grid.iterrows(): pts_in_this_poly = [] for j, pt in pts.iterrows(): if poly.geometry.contains(pt.geometry): pts_in_this_poly.append(pt.geometry) pts = pts.drop([j]) nums = len(pts_in_this_poly) pts_in_polys.append(nums) geo_grid['number of points'] = gpd.GeoSeries(pts_in_polys) #Adds number of points in each polygon # Adds Quantiles column classifier = mc.Quantiles.make(k=levels) geo_grid["class"] = geo_grid[["number of points"]].apply(classifier) # Adds Polygon grid points to new geodataframe geo_grid["x"] = geo_grid.apply(getPolyCoords, geom="geometry", coord_type="x", axis=1) geo_grid["y"] = geo_grid.apply(getPolyCoords, geom="geometry", coord_type="y", axis=1) polygons = geo_grid.drop("geometry", axis=1).copy() return polygons </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T07:02:05.437", "Id": "470898", "Score": "0", "body": "can you share a small sample of (dummy) data so we can test what happens and see whether alternative approaches result in the same outcome?" } ]
[ { "body": "<p>The nested loop compares each poly to each point, so the complexity is (Npoly * Npts). </p>\n\n<p>If the grid is regular, that is each square in a row has the same top and bottom coordinate, and each square in a column has the same left and right coordinate, then binary searches (bisect in std library) could be used to determine which grid row and column a point falls in. This would be Npts * log Npoly. I think this could be combined with <code>.groupby()</code> to eliminate any explicit loops. I don't have time to post code now, maybe tomorrow.</p>\n\n<p>(It's tomorrow)</p>\n\n<p>Better yet, use numpy.histogram2d. On my laptop, it takes about 220ms to bin 2M points:</p>\n\n<pre><code>import numpy as np\n\nmin_lat, max_lat = 49.22, 49.30\nnum_lat_bins = 10\n\nmin_long, max_long = -123.23, -122.92\nnum_long_bins = 20\n\nnum_points = 2_000_000\n\n# random coordinates for testing\nlats = np.random.uniform(min_lat, max_lat, num_points)\nlongs = np.random.uniform(min_long, max_long, num_points)\n\n\nh, lat_edges, long_edges = np.histogram2d(lats, longs,\n bins=(10,20),\n range=[(min_lat,max_lat), (min_long, max_long)]) \n</code></pre>\n\n<p>Where, <code>h</code> is the histogram, or count in each grid square and <code>lat_edges</code> and <code>'long_edges</code> are the grid lines. They look like:</p>\n\n<pre><code># h (10 rows by 20 columns)\n[[ 9982. 10126. 10124. ... 10218. 10140. 9844.]\n [ 9971. 10096. 10035. ... 10057. 9844. 9923.]\n [ 9940. 10036. 9982. ... 9966. 10034. 9872.]\n ... \n [10025. 10011. 10027. ... 9870. 9942. 9985.]]\n\n# lat_edges\n[49.22 , 49.228, 49.236, 49.244, 49.252, 49.26 , 49.268, 49.276,\n 49.284, 49.292, 49.3 ]\n\n# long_edges\n[-123.23 , -123.2145, -123.199 , -123.1835, -123.168 , -123.1525,\n -123.137 , -123.1215, -123.106 , -123.0905, -123.075 , -123.0595,\n -123.044 , -123.0285, -123.013 , -122.9975, -122.982 , -122.9665,\n -122.951 , -122.9355, -122.92 ]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:46:25.120", "Id": "471923", "Score": "0", "body": "A well deserved checkmark for you. It brought the algorithm down from 1200 min for 200,000 rows to ~15 secs for the full set of 750,000 rows. Nicely done." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T07:03:58.040", "Id": "240031", "ParentId": "240023", "Score": "1" } } ]
{ "AcceptedAnswerId": "240031", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T04:48:01.883", "Id": "240023", "Score": "1", "Tags": [ "python", "performance", "geospatial" ], "Title": "Advice on taming a slow loop required for visualization of large GIS dataset" }
240023
<p>I have come up with a sequence of steps to find the maximum product of <code>y</code> positive numbers which add up to <code>x</code>. But the program is highly inefficient.</p> <p>Here's my code:</p> <pre class="lang-py prettyprint-override"><code>from itertools import product from functools import reduce from operator import mul for i in range(int(input())): # &lt;-- number of pairs of input lgr = 1 k = set() x, y = tuple(map(int, input().split())) # &lt;-- the input pairs p = product(range(1, x+1), repeat=y) # &lt;-- gets the cross product for i in p: if sum(i) == x: # &lt;-- checks if sum is equal to x k.add(i) # &lt;-- adds it to a set() to remove duplicates for i in k: tmp = reduce(mul, i, 1) # &lt;-- multiplies the items in the tuple to get the largest if tmp &gt; lgr: lgr = tmp print(lgr) </code></pre> <p>But say for an input like <code>14 7</code> it just takes too long (around 20s). Is there a better way to do it?</p> <p><strong>Update 1:</strong> I've managed to improve a bit by using <code>combinations_with_replacement</code> and <code>set &amp; list comprehension</code>... but I believe it can be done better... any suggestions...?</p> <pre class="lang-py prettyprint-override"><code>from itertools import combinations_with_replacement from functools import reduce from operator import mul for i in range(int(input())): lgr = 1 x, y = tuple(map(int, input().split())) k = {i for i in combinations_with_replacement(range(1, x+1), y) if sum(i) == x} lgr = max([max(reduce(mul, i, 1), lgr) for i in k]) print(lgr) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T11:24:03.577", "Id": "470780", "Score": "2", "body": "I was able to solve the problem for (14, 7) = 128 in 5 seconds without the help of a computer. The product is biggest when all numbers are equal, which is easy to prove." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T13:57:34.213", "Id": "470789", "Score": "0", "body": "@RainerP. It would be interesting to see this proof, it's easy with \\$(x + a)(x + b)\\$ where \\$a + b = 0\\$ however I'm unable to do so with \\$(x + a)(x + b)(x + c)\\$ where \\$a + b + c = 0\\$." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T14:01:50.607", "Id": "470790", "Score": "1", "body": "@Peilonrayz - Start with an array of all ones, then repeatedly add one to the smallest number (because that gives the largest percentual increase) until you reach the maximum allowed sum. This can be fomulated as a proof by induction." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T14:04:10.733", "Id": "470791", "Score": "0", "body": "@RainerP. Oh, yeah that sounds rather easy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T14:11:07.987", "Id": "470792", "Score": "3", "body": "@Peilonrayz, if the product contains two factors which differ by more than one, then it is not optimal: Say these are x and y with x < y, then replace them by x + 1 and y - 1. Now (x+1)(y-1) = xy + (y - x - 1) > xy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T14:30:48.937", "Id": "470796", "Score": "0", "body": "@CarstenS Please post that as an answer :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T14:31:39.913", "Id": "470798", "Score": "1", "body": "I do not think that this kind of algorithmic question is right for code review SE." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T14:34:18.940", "Id": "470799", "Score": "0", "body": "@CarstenS I don't think anyone is going to vote to close the question. Additionally comments are temporary and your comment contains information that can improve the question's code. To ensure it stays around I'll post an answer if you don't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T14:38:24.290", "Id": "470800", "Score": "0", "body": "@Peilonrayz, I am not a regular here, so I do not know whether answers that are only about a completely different algorithm are a good fit here. I don't think that they are. Feel free to answer, though, mathematics belong to no-one, and this is definitely not an original result :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T15:01:23.707", "Id": "470804", "Score": "1", "body": "I agree with Carsten that this is not a code review, which is also why I started this thread in the comments. OP brute forced a trivial math exercise and I wanted to highlight that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T15:40:01.503", "Id": "470817", "Score": "1", "body": "@RainerP. & CarstenS Pretty much all [tag:performance] and even more so [tag:complexity] questions come down to trivial math problems. The amount of times I've posted an answer saying \\$O(n^2) < O(n^3)\\$ is starting to not be funny. Most [tag:programming-challenge] questions also just come down to using math rather than brute-force." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T18:52:09.437", "Id": "470840", "Score": "1", "body": "This can easily be solved with a closed formula, no loops needed: `ceiling(y/x)^remainder(y/x) * floor(y/x)^(x-remainder(y/x))`. This is O(1)." } ]
[ { "body": "<p>One immediate improvement is realizing that for e.g the input <code>14 7</code>, all combinations like <code>x x x x x x 9</code> and above can never sum to <code>14</code>, because even for the minimal case <code>x = 1</code>, <code>9 + 6*1 = 15</code>. So you can vastly reduce the number of combinations you need to check by using </p>\n\n<pre><code>k = {i for i in combinations_with_replacement(range(1, x - y + 2), y) if sum(i) == x}\n</code></pre>\n\n<p>For the input <code>14 7</code> this constitutes a difference of 77520 possible combinations down to 3432.</p>\n\n<p>This adds a constraint only on the last number, but you could take this to its logical extreme and write code that always aborts the combinations once the sum has been reached.</p>\n\n<p>One other thing you should do is use better names and use functions. I have no idea that <code>k</code> is a list of combinations of numbers, or what this means. Also, using <code>i</code> (and <code>j</code>, <code>k</code>, <code>n</code>, too, for that matter) for anything other than an integer is not helpful either.</p>\n\n<p>I would at least rewrite your code to this:</p>\n\n<pre><code>from itertools import combinations_with_replacement\ntry: # Python 3.8+\n from math import prod\nexcept ImportError:\n from functools import reduce\n from operator import mul\n def prod(x):\n \"\"\"Returns the product of all elements of `x`, similar to `sum`.\"\"\"\n return reduce(mul, x, 1)\n\ndef maximum_product_with_sum(x, n):\n \"\"\"Return the maximum product of all `n` positive numbers that sum to `x`.\"\"\"\n r = range(1, x - n + 2)\n candidates = {candidate \n for candidate in combinations_with_replacement(r, n)\n if sum(candidate) == x}\n return max(map(prod, candidates), default=1)\n\nif __name__ == \"__main__\":\n for _ in range(int(input())):\n x, n = tuple(map(int, input().split()))\n print(maximum_product_with_sum(x, n))\n</code></pre>\n\n<p>Note that I also added some short <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\"><code>docstring</code></a>s to describe what each function does and simplified getting the maximum, your inner call to <code>max</code> was not needed. The optional keyword argument argument <code>default</code> of <code>max</code> is the default value if the iterable is empty.</p>\n\n<p>I also added a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script from another script without the code being run.</p>\n\n<p>Here is the performance measured against your second function (the first one is way too slow) once for the input <code>x 7</code> and once for <code>14 n</code>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/ozoxN.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ozoxN.png\" alt=\"enter image description here\"></a></p>\n\n<p>You can see that this code is not only faster in general, it also becomes much faster if <code>n &gt; x / 2</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T12:43:02.787", "Id": "470786", "Score": "2", "body": "If you're on 3.8 you can use [`math.prod`](https://docs.python.org/3/library/math.html#math.prod)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T15:12:22.240", "Id": "470807", "Score": "0", "body": "@MaartenFabré: Ah, yes, I had forgotten they finally added that :) Edited to include it, albeit under a guard since quite a few systems don't have 3.8 yet as a default (Ubuntu 18.04 LTS, looking at you)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T09:35:55.087", "Id": "240038", "ParentId": "240025", "Score": "7" } }, { "body": "<p>The comments contain two proofs that a better solution exists.</p>\n\n<ol>\n<li><blockquote>\n <p>Start with an array of all ones, then repeatedly add one to the smallest number (because that gives the largest percentual increase) until you reach the maximum allowed sum. This can be fomulated as a proof by induction. – <a href=\"https://codereview.stackexchange.com/users/105198/rainer-p\">Rainer P.</a></p>\n</blockquote>\n\n<p>This can be proven rather simply by using Python, but it can also be proven with a basic formula.\nIf we start with the array <span class=\"math-container\">\\$y, y-1\\$</span> and we have to increase one of the values by one then we can deduce adding one to the <span class=\"math-container\">\\$y-1\\$</span> value results in a larger product.</p>\n\n<p><span class=\"math-container\">$$\nyy \\gt (y + 1)(y-1)\\\\\ny^2 \\gt y^2 - 1\\\\\n$$</span></p>\n\n<p>This change works regardless of what the rest of the array is. And so we know adding one to the lowest value always nets the biggest increase.<br>\nI used to not be very good with math, and so a more hands on proof using Python may be easier to follow and agree with.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import math\n\n\ndef inc_1(numbers, pos):\n nums = numbers[:]\n nums[pos] += 1\n return nums\n\n\ndef proof(total, amount):\n if total &lt; amount:\n return 0\n numbers = [1] * amount\n for i in range(total - amount):\n d = i % amount\n if d:\n larger = math.prod(inc_1(numbers, d - 1))\n smaller = math.prod(inc_1(numbers, d))\n if smaller &lt; larger:\n raise ValueError('proof does not hold')\n numbers[d] += 1\n return numbers, math.prod(numbers)\n\n\nprint(proof(14, 7))\nprint(proof(302, 5))\n</code></pre></li>\n<li><blockquote>\n <p>if the product contains two factors which differ by more than one, then it is not optimal: Say these are <span class=\"math-container\">\\$x\\$</span> and <span class=\"math-container\">\\$y\\$</span> with <span class=\"math-container\">\\$x &lt; y\\$</span>, then replace them by <span class=\"math-container\">\\$x + 1\\$</span> and <span class=\"math-container\">\\$y - 1\\$</span>. Now <span class=\"math-container\">\\$(x+1)(y-1) = xy + (y - x - 1) &gt; xy\\$</span>. – <a href=\"https://codereview.stackexchange.com/users/81034/carsten-s\">Carsten S</a></p>\n</blockquote>\n\n<p><sup>Changed to use mathjax</sup></p>\n\n<p>With this description the factors are the array of numbers. With this we can start with a random assortment of numbers that total the desired number, and we can continuously improve the product.</p>\n\n<p><span class=\"math-container\">$$\n3, 8\\\\\n3 &lt; 8\\\\\n4 \\times 7 \\gt 3 \\times 8\\\\\n28 \\gt 24\\\\\n5 \\times 6 \\gt 4 \\times 7\\\\\n30 \\gt 24\n$$</span></p></li>\n</ol>\n\n<hr>\n\n<p>In all the fastest solution is to just use <code>divmod</code>, and produce the product once.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def maximum_product_with_sum(total, count):\n q, r = divmod(total, count)\n return (q+1)**r * q**(count-r)\n\n\nprint(maximum_product_with_sum(14, 7))\nprint(maximum_product_with_sum(302, 5))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T15:11:35.760", "Id": "240055", "ParentId": "240025", "Score": "6" } }, { "body": "<p>Thanks <a href=\"https://codereview.stackexchange.com/users/98493/graipher\">@Graipher</a> &amp; <a href=\"https://codereview.stackexchange.com/users/42401/peilonrayz\">@Peilonrayz</a> for taking time to answer my question. Yesterday around 7PM IST I discussed this with my brilliant friend Abhay, who gave me a clue on how this can be solved with just <span class=\"math-container\">\\$O(n)\\$</span> complexity.</p>\n\n<p>To keep the question in mind:</p>\n\n<blockquote>\n <p>Find the maximum product of <code>y</code> positive numbers which adds up to <code>x</code>.</p>\n</blockquote>\n\n<p>This is how he explained it to me:</p>\n\n<blockquote>\n <p>If we observe the pattern of tuples that qualify for the output, we can easily see that all the values lie closer to <span class=\"math-container\">\\$\\frac{x}{y}\\$</span>.\n See for the pairs:</p>\n\n<pre><code>| Pairs | Solution Tuple | Max Product |\n|----------|-----------------------------------------------|-------------|\n| (14, 7) | (2, 2, 2, 2, 2, 2, 2) | 128 |\n| (20, 15) | (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2) | 32 |\n| (13, 4) | (3, 3, 3, 4) | 108 |\n| (5, 3) | (1, 2, 2) | 4 |\n</code></pre>\n \n <p>If we take a even closer look we find that those values in the tuple are either <a href=\"https://en.wikipedia.org/wiki/Floor_and_ceiling_functions\" rel=\"nofollow noreferrer\">ceil(<span class=\"math-container\">\\$\\frac{x}{y}\\$</span>)</a> or <a href=\"https://en.wikipedia.org/wiki/Floor_and_ceiling_functions\" rel=\"nofollow noreferrer\">floor(<span class=\"math-container\">\\$\\frac{x}{y}\\$</span>)</a>.\n And the last individual element is what is left off in sum.</p>\n</blockquote>\n\n<p>Hence the program according to him was:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from math import floor, ceil\n\nfor t in range(int(input()):\n x, y = map(int, input().split())\n psum, product = 0, 1\n for i in range(y):\n if i == y-1: product *= x - psum\n else:\n num = x/y\n num1, num2 = floor(num), ceil(num)\n psums, product = (psum+num1, product*num1) if abs(num - num1) &lt; abs(num - num2) else (psum+num2, product*num2)\n print(product)\n</code></pre>\n\n<p><a href=\"https://codereview.stackexchange.com/users/13301/rbarryyoung\">@RBarryYoung</a>'s comment came close but I think x's and y's got messed up... (please correct me if it is not so).</p>\n\n<p>I've never seen how well this answer fares @Peilonrayz's solution, but I would love to get some insight on it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T10:19:40.190", "Id": "470915", "Score": "2", "body": "Peilonrayz's solution is the same as yours. `solve(17, 5) = product(4, 4, 3, 3, 3) = 4² * 3³ = (3+1)² * 3³` where `q = 3, r = 2`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T06:32:09.623", "Id": "240088", "ParentId": "240025", "Score": "1" } } ]
{ "AcceptedAnswerId": "240055", "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T05:37:23.127", "Id": "240025", "Score": "7", "Tags": [ "python", "performance", "algorithm", "programming-challenge", "combinatorics" ], "Title": "Refactor the code which performs \"cross-product\", \"reduce\", \"product of list\" and \"sum of list\"" }
240025
<p>I am trying to validate a HTTP REST API request in my python code. It checks for some request headers (<code>X-Foo</code> and <code>X-Bar</code>) and two keys in the json body/payload (<code>someKey</code> and <code>someNestedKey</code>). I have written this code with if/else conditions as well as a simple try-catch. </p> <pre><code>headers = event["headers"] if "X-Foo" not in headers or "X-Bar" not in headers: return { 'statusCode': 401, 'body': '{"message":"Some error message"}' } # Do something with request headers here payload = json.loads(event["body"]) if "someKey" not in payload: some_flag = False else: if "someNestedKey" not in payload["someKey"]: some_flag = False else: some_flag = True if not some_flag: return { 'statusCode': 400, 'body': '{"message":"Some other error message"}' } # if we get this far, then its ok foo_bar = payload["someKey"]["someNestedKey"] </code></pre> <p>vs</p> <pre><code>try: headers = event["headers"] # Do something with request headers here payload = json.loads(event["body"]) foo_bar = payload["someKey"]["someNestedKey"] except KeyError: return { 'statusCode': 401, 'body': '{"message":"Some error message"}' } </code></pre> <p>I'd like a review on all aspects of this code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T06:23:22.317", "Id": "470759", "Score": "0", "body": "In the second alternative you don't check for the headers X-Foo and X-Bar. Is that on purpose?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T06:26:40.207", "Id": "470760", "Score": "0", "body": "@RGS Sorry, that was a mistake - I have updated both code snippets." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T06:49:52.987", "Id": "470763", "Score": "0", "body": "in the second alternative you still don't check for the headers...!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T06:51:30.173", "Id": "470764", "Score": "0", "body": "Yes, I just dive into using them, the idea is that if they dont exist, it will throw the `KeyError` and return 401." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T07:24:24.077", "Id": "470766", "Score": "0", "body": "I think there's an indent issue with the `else` of `if some_key not in payload`: could you confirm and/or correct accordingly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T07:40:38.060", "Id": "470767", "Score": "0", "body": "@avazula Thanks, that was not intended, fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T14:48:11.943", "Id": "470801", "Score": "0", "body": "We need more contextual code - this is just an excerpt. Please show all of your code, or I'm afraid that it is off-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T15:08:16.450", "Id": "470805", "Score": "0", "body": "What does the JSON payload look like ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T15:08:18.783", "Id": "470806", "Score": "0", "body": "`I'd like a review on all aspects of this code.` as of the [3rd revision](https://codereview.stackexchange.com/revisions/240028/3), I think that difficult for lack of context. Whoever was so inclined could offer advice and opinion in a [tag:comparative-review] of the snippets shown - which may well be of little importance in a slightly bigger context." } ]
[ { "body": "<p>I am not sure this question can still be salvaged as some relevant details are missing.</p>\n<p>One opening remark though: HTTP header fields are <strong>case-insensitive</strong>, as stipulated by several RFCs, including <a href=\"https://www.rfc-editor.org/rfc/rfc7230#section-3.2\" rel=\"nofollow noreferrer\">RFC 7230</a> (See 3.2. Header Fields).</p>\n<blockquote>\n<p>Each header field consists of a case-insensitive field name followed\nby a colon (&quot;:&quot;), optional leading whitespace, the field value, and\noptional trailing whitespace.</p>\n</blockquote>\n<p>If you are using the <code>requests</code> module to collect your headers with key values you would have an object of type <code>requests.structures.CaseInsensitiveDict</code>, and you don't have to take care of this aspect. Therefore, <code>&quot;X-Foo&quot; in req.headers</code> and <code>&quot;x-foo&quot; in req.headers</code> will both match the same.</p>\n<p>But it is good to keep this in mind as some clients may take some liberty and decide on a different casing like all-lowercase - after all they are still RFC-compliant, and so should you.</p>\n<p>This aspect is also discussed in the doc for the requests module: <a href=\"https://requests.readthedocs.io/en/master/user/quickstart/#response-headers\" rel=\"nofollow noreferrer\">Response Headers</a></p>\n<p>So you are checking the existence of two headers but aren't you interested in their values ? What is the point of using those two headers ? Is the code slightly incomplete or did I miss something ?</p>\n<hr />\n<p><strong>Exception handling</strong>: your whole procedure should be covered by a comprehensive exception handling routine.\nFor specific tasks like decoding the JSON payload, watch out for <code>JSONDecodeError</code> exception. It will be triggered if an invalid JSON string is sent to your script (could be an attacker). See below.</p>\n<p>An unhandled exception could in certain circumstances defeat or bypass the various checks you make. Bottom line: identify the sensitive parts of your code (in particular those processing <strong>external input</strong>), always handle exceptions, never ignore them.</p>\n<hr />\n<p>The code can be simplified, for example:</p>\n<pre><code>if &quot;someKey&quot; not in payload:\n some_flag = False\nelse:\n if &quot;someNestedKey&quot; not in payload[&quot;someKey&quot;]:\n some_flag = False\n else:\n some_flag = True\n\nif not some_flag:\n return {\n 'statusCode': 400,\n 'body': '{&quot;message&quot;:&quot;Some other error message&quot;}'\n }\n</code></pre>\n<p>If the goal is to check for the existence of a key in a JSON string and extract the corresponding value you could wrap the functionality in small functions to declutter the code.</p>\n<p>In the example below I am using a simplistic JSON string like <code>{&quot;AuthToken&quot;: &quot;abcdef&quot;, &quot;UserID&quot;: 1234}</code>. Since you've mentioned <strong>nested</strong> keys you'll have to adapt the code a little bit but you get the idea.</p>\n<pre><code>def parse_json(json_string):\n try:\n # return dict - maybe (see later)\n return json.loads(json_string)\n except json.JSONDecodeError:\n # stop immediately or alternatively return an empty dict\n print('JSONDecodeError triggered, do something')\n #logger.error('JSONDecodeError triggered', exc_info=True)\n #sys.exit(1)\n\ndef get_value_from_key(payload, key_to_check):\n if key_to_check in payload.keys():\n # key found, get the matching value\n return payload[key_to_check]\n else:\n return None\n</code></pre>\n<p>Testing the functions:</p>\n<pre><code>json_string = &quot;&quot;&quot;{&quot;AuthToken&quot;: &quot;abcdef&quot;, &quot;UserID&quot;: 1234}&quot;&quot;&quot;\npayload = parse_json(json_string)\n\ninvalid_json_string = &quot;&quot;&quot;{&quot;AuthToken&quot;: &quot;UserID&quot;: 1234}&quot;&quot;&quot;\n# this will trigger an handled exception, and you should not proceed any further\ninvalid_payload = parse_json(invalid_json_string)\n\nkey_to_check = 'AuthToken'\n# value will be None if the key was not found, then you could raise your 401 error or whatever\nprint(get_value_from_key(payload, key_to_check))\n</code></pre>\n<p>If you don't want to choke on the exception but proceed as casually as possible you could return an empty dict but at least you've handled the invalid input.</p>\n<p>It seems to me that the way you are handling <code>KeyError</code> in your code will therefore not suffice to handle all the possible bad situations. The best is of course to test your script in adverse conditions, feed it garbage and see how it reacts.</p>\n<p><strong>NB</strong>: unlike the headers collection routine <code>get_value_from_key</code> <em>is</em> <strong>case-sensitive</strong>. So if I want to retain the ability of doing case-insensitive searching on the keys I would probably do this, reusing structures already available to us:</p>\n<pre><code>from requests.structures import CaseInsensitiveDict\n\nif key_to_check in CaseInsensitiveDict(payload):\n ...\n</code></pre>\n<p>If your code is already using <code>requests</code> you are not adding extra dependencies</p>\n<p>But wait. Actually, <code>json.loads</code> will not always return a <code>dict</code>, than depends.</p>\n<blockquote>\n<p>Deserialize s (a str, bytes or bytearray instance containing a JSON\ndocument) to a Python object using this <a href=\"https://docs.python.org/3/library/json.html#json-to-py-table\" rel=\"nofollow noreferrer\">conversion\ntable</a>.</p>\n</blockquote>\n<p>Source: <a href=\"https://docs.python.org/3/library/json.html#json.loads\" rel=\"nofollow noreferrer\">json — JSON encoder and decoder</a></p>\n<p>So I would advise you to check that the return value is actually of a suitable type like <code>dict</code> or <code>list</code>. It's always important to read the doc so that there is no ambiguity as to the data type returned by a given function, because there may be several possibilities.</p>\n<p>The proposed code is for demonstration purposes but not comprehensive, hopefully it can help you avoid a few pitfalls.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T18:57:38.713", "Id": "240069", "ParentId": "240028", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T06:09:58.543", "Id": "240028", "Score": "0", "Tags": [ "python", "api", "http" ], "Title": "Python code for checking request headers" }
240028
<p>I am trying to plot the standing wave modes in a 2D box over time. The equation for this is:</p> <p><span class="math-container">$$ A(x,y,t) = \sum\limits_{n,m} sin \left( \frac{n \pi x}{L_x} \right) sin \left( \frac{m \pi y}{L_y} \right) cos \left( w_{n,m}t + \phi_{n,m} \right) $$</span> where <span class="math-container">$$ w_{n,m} = \sqrt{ {\left( \frac{n \pi}{L_x}\right)}^2 + {\left( \frac{m \pi}{L_y}\right)}^2 }$$</span></p> <p>The code I have used is given below:</p> <pre><code>Nx = 384 Ny = 384 Nt = 360 # function to calculate standing wave def s_wave(ll, xx, yy, tt, pp, max_modes): tot_amp = 0 Mm = 1000 # a constant relevant to my problem k = 0 for m in range (1,max_modes): for n in range (1,max_modes): omega = ((m*np.pi/(ll*Mm))**2 + (n*np.pi/(ll*Mm))**2)**0.5 amp = np.sin(m*np.pi*xx/ll)*np.sin(n*np.pi*yy/ll)*np.cos(omega*tt-pp[k]) tot_amp = tot_amp + amp k = k + 1 return (tot_amp) # building grid points in x and y direction L = 6.144 # Length of the Box along each axis T = 10 # delta_T x = np.linspace(-L/2, L/2, Nx) y = np.linspace(-L/2, L/2, Ny) t = np.linspace(0, (Nt-1)*T, Nt) modes = 60 #number of standing wave modes phase = np.random.uniform(0,2*np.pi,modes*modes) # to introduce random phase in each mode ustand = s_wave(L,x[None,None,:],y[None,:,None],t[:,None,None],phase,modes) </code></pre> <p>This approach works quantitatively fine with my problem. But the execution time is pretty slow. Is there any way to accelerate the execution time?</p> <p>Thanks in advance. </p>
[]
[ { "body": "<p>A few things to consider:</p>\n\n<ol>\n<li>Loops in python are very inefficient. To optimize performance, when\nit is possible to vectorize code, you should do so. </li>\n<li>Avoid calculating the same thing multiple times. For example, the term <span class=\"math-container\">$$ cos(\\omega_{n,m}t + \\phi_{n,m}) $$</span> does not depend on x and y, so there is no need to calculate it during every iteration of the loop.</li>\n<li>The number of calculations you are performing is huge. Nx * Ny * Nt * n_max * m_max is roughly 191 billion iterations, and on each of those iterations, multiple calculations are performed. I am not sure about the reason for using so many points on your x,y,t grid, but for adequate visualization, much fewer are required. If the goal is numerical precision, I would recommend checking out SciPy's interp2D function. What you could do is calculate a smaller number of grid points, and if you need to sample a value that is not on the grid, you can use the 2d interpolation function.</li>\n</ol>\n\n<p>I have altered your code to vectorize it as much as possible. I did not completely vectorize out the loops, because my laptop does not have RAM capacity in the triple digits of gigabytes.</p>\n\n<p>Reducing the number of grid points in the X and Y directions results in a huge speedup, and the resulting plot is shown after the code.</p>\n\n<pre><code>import numpy as np\n\n#Nx = 384\n#Ny = 384\n#Nt = 360\n\nNx = 38\nNy = 37\nNt = 360\n\n#########################################################\n# function to calculate standing wave (original code had error in amp line)\n#########################################################\ndef s_wave(lx, ly, xx, yy, tt, pp, max_modes):\n tot_amp = 0 # Initialize total amplitude to 0\n Mm = 1000 # a constant relevant to my problem\n p_idx = 0 # The index for accessing the phase noise\n\n for m in range (0,max_modes):\n for n in range (0,max_modes):\n #############################\n # Calculating Omega\n #############################\n omega1 = n*np.pi/(lx*Mm)\n omega2 = m*np.pi/(ly*Mm)\n\n omega = np.sqrt(omega1**2 + omega2**2)\n\n #############################\n # Calculating Amplitude\n #############################\n amp1 = np.sin(n*np.pi*xx/lx)\n amp2 = np.sin(m*np.pi*yy/ly)\n amp3 = np.cos(omega*tt - pp[p_idx])\n\n amp = amp1 * amp2 * amp3\n\n #############################\n # Update total amplitude\n #############################\n tot_amp = tot_amp + amp\n p_idx = p_idx + 1\n\n return tot_amp\n\ndef s_wave_opt(lx, ly, xx, yy, tt, pp, max_n, max_m):\n tot_amp = 0 # Initialize total amplitude to 0\n Mm = 1000 # a constant relevant to my problem\n\n #############################\n # Initialize total amplitudes at all points to 0\n #############################\n A_total = np.zeros([len(xx), len(yy), len(tt)])\n\n #############################\n # Calculate omega\n #############################\n n,m = np.mgrid[1:max_n+1:1, 1:max_m+1:1]\n omega_n = n * np.pi / ( lx * Mm )\n omega_m = m * np.pi / ( ly * Mm )\n omega = np.sqrt(omega_n**2 + omega_m**2)\n\n #############################\n # Vactorize calculation of term3\n #############################\n term3 = np.multiply.outer(t,omega)\n term3 = np.add(pp,term3)\n term3 = np.cos(term3)\n\n #############################\n # Calculating A[x,y,:]\n #############################\n nr = np.arange(1,max_n+1)\n term1 = np.multiply.outer(xx, nr*np.pi/(lx*Mm))\n term1 = np.sin(term1)\n\n mr = np.arange(1,max_m+1)\n term2 = np.multiply.outer(yy, mr*np.pi/(ly*Mm))\n term2 = np.sin(term2)\n\n for y_idx in range(len(yy)):\n xy = np.multiply.outer(term1, term2[y_idx])\n xyt = np.multiply(xy[:,None,:,:],term3[None,:,:,:])\n tot = np.sum(xyt, axis=(2,3))\n A_total[:,y_idx,:] = tot\n\n return A_total\n\n\n# building grid points in x and y direction\nLx = 6.144 # Length of the Box along each axis\nLy = 6.144\nT = 10 # delta_T \nx = np.linspace(-Lx/2, Lx/2, Nx)\ny = np.linspace(-Ly/2, Ly/2, Ny)\nt = np.linspace(0, (Nt-1)*T, Nt)\n\nmodes_n = 60\nmodes_m = 61\nphase2 = np.random.uniform(0,2*np.pi, [modes_n,modes_m])\nustand = s_wave_opt(Lx, Ly, x, y, t, phase2, modes_n, modes_m)\n</code></pre>\n\n<p>The resulting plot was too large to attach as a gif, but attached is a screenshot of one frame:\n<a href=\"https://i.stack.imgur.com/MVOoL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MVOoL.png\" alt=\"One frame of plot\"></a></p>\n\n<p>The code to produce the gif plot:</p>\n\n<pre><code>##################################################\n# Plotting the results\n##################################################\nfrom mpl_toolkits import mplot3d\nimport matplotlib.pyplot as plt\n\nimport os\nif not os.path.isdir(\"./images\"):\n os.system(\"mkdir images\")\n\nfor i in range(Nt):\n fig = plt.figure()\n ax = plt.axes(projection='3d')\n X,Y = np.meshgrid(y,x)\n ax.plot_surface(X, Y, ustand[:,:,i])\n\n ax.set_xlim3d(x.min(), x.max())\n ax.set_ylim3d(y.min(), y.max())\n ax.set_zlim3d(ustand.min(), ustand.max())\n ax.set_title(\"Standing Wave at Time {}\".format(t[i]))\n plt.savefig(\"./images/frame{}.png\".format(i))\n plt.close()\n\n\nos.system(\"ffmpeg -i ./images/frame%d.png -vf palettegen -y paletter.png &amp;&amp; ffmpeg -framerate 20 -loop 0 -i ./images/frame%d.png -i paletter.png -lavfi paletteuse -y plot.gif\")\n</code></pre>\n\n<p>The code runs in about 4 minutes. Roughly 1 minute are the calculations, and the rest is time spent creating the graph.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-29T02:28:07.027", "Id": "241408", "ParentId": "240034", "Score": "3" } } ]
{ "AcceptedAnswerId": "241408", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T07:27:42.443", "Id": "240034", "Score": "3", "Tags": [ "python", "performance", "numpy" ], "Title": "Fast way to calculate Standing Wave modes in NumPy" }
240034
<p>I have the following code that transforms a string to upper/lowercase:</p> <pre><code>#include &lt;iterator&gt; #include &lt;algorithm&gt; #include &lt;type_traits&gt; #include &lt;vector&gt; #include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;locale&gt; #include &lt;functional&gt; namespace ae { template &lt;typename StrT&gt; auto toLower(StrT&amp; str) { std::transform(str.begin(), str.end(), str.begin(), [](const auto&amp; c) { static const auto loc{ std::locale() }; return std::tolower(c, loc); }); } template &lt;typename StrT&gt; auto toUpper(StrT&amp; str) { std::transform(str.begin(), str.end(), str.begin(), [](const auto&amp; c) { static const auto loc{ std::locale() }; return std::toupper(c, loc); }); } template &lt;typename StrT&gt; auto toLowerCopy(StrT&amp; str) { auto newStr{ str }; std::transform(str.begin(), str.end(), newStr.begin(), [](const auto&amp; c) { static const auto loc{ std::locale() }; return std::tolower(c, loc); }); return newStr; } template &lt;typename StrT&gt; auto toUpperCopy(StrT&amp; str) { auto newStr{ str }; std::transform(str.begin(), str.end(), newStr.begin(), [](const auto&amp; c) { static const auto loc{ std::locale() }; return std::toupper(c, loc); }); return newStr; } } // Example usage int main() { std::wstring my_str{ L"Test" }; ae::toLower(my_str); std::wcout &lt;&lt; my_str &lt;&lt; std::endl; std::string my_str2{ "This is a test aswell" }; auto new_str{ ae::toUpperCopy(my_str2) }; std::cout &lt;&lt; new_str &lt;&lt; std::endl; return 0; } </code></pre> <p>All of the 4 functions are pretty much exact copies of each other, just minor variations. I dont want to repeat myself in this way, but im unsure how to make one function that does all of this functionality. How can I improve the code?</p>
[]
[ { "body": "<p>What you can do is combine the two methods <code>toLower</code> and <code>toUpper</code> into one method, say <code>transform</code>, to which you pass the method by which to transform (<code>std::tolower</code> or <code>std::toupper</code>) as arguments. The same can be done for <code>toUpperCopy</code> and <code>toLowerCopy</code>. Passing functions allows you to be more flexible as you are now able to not only use <code>std::tolower</code> and <code>std::toupper</code> but also any other function which transforms a character.</p>\n\n<p>You can combine everything into one method and use something like a boolean parameter to tell if it should copy or not but I would advise against it. The functions are short functions so they will still be readable and you keep the responsibility for copying in a separate function.</p>\n\n<p>Passing the functions would look something like this:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>namespace ae\n{\n template &lt;typename charT&gt;\n auto transform(std::basic_string&lt;charT&gt;&amp; str, charT charMap(charT, const std::locale&amp;))\n {\n std::transform(str.begin(), str.end(), str.begin(), [&amp;charMap](const auto&amp; c)\n {\n static const auto loc{ std::locale() };\n return charMap(c, loc);\n });\n }\n\n template &lt;typename charT&gt;\n auto transformCopy(std::basic_string&lt;charT&gt;&amp; str, charT charMap(charT, const std::locale&amp;))\n {\n auto newStr{ str };\n std::transform(str.begin(), str.end(), newStr.begin(), [&amp;charMap](const auto&amp; c)\n {\n static const auto loc{ std::locale() };\n return charMap(c, loc);\n });\n return newStr;\n }\n}\n\nint main()\n{\n std::wstring my_str{ L\"Test\" };\n ae::transform(my_str, std::tolower);\n std::wcout &lt;&lt; my_str &lt;&lt; std::endl;\n\n std::string my_str2{ \"This is a test aswell\" };\n auto new_str{ ae::transformCopy(my_str2, std::toupper) };\n std::cout &lt;&lt; new_str &lt;&lt; std::endl;\n\n return 0;\n}\n</code></pre>\n\n<p>Note that I changed the template variable from <code>StrT</code> to <code>charT</code> as the <code>charT</code> was needed for the <code>charMap</code>. Using both <code>StrT</code> and <code>charT</code>, the compiler was not able to infer the template argument for <code>charT</code> so you had to manually add the template arguments each time you called <code>ae::transform</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T10:18:34.557", "Id": "240041", "ParentId": "240035", "Score": "1" } }, { "body": "<p>A way to shorten your code is to extract common parts &mdash; the <code>tolower</code> and <code>toupper</code> closures and general <code>transform</code> and <code>transform_copy</code> utilities, in this case: (note that I used <code>std::locale::classic()</code> instead of the recently installed global locale)</p>\n\n<pre><code>namespace ae {\n struct to_lower_t {\n template &lt;typename CharT&gt;\n CharT operator()(CharT c) const\n {\n return std::tolower(c, std::locale::classic());\n }\n };\n inline constexpr to_lower_t to_lower;\n\n struct to_upper_t {\n template &lt;typename CharT&gt;\n CharT operator()(CharT c) const\n {\n return std::toupper(c, std::locale::classic());\n }\n };\n inline constexpr to_upper_t to_upper;\n\n template &lt;typename CharT, typename Traits, typename Functor&gt;\n void transform(std::basic_string&lt;CharT, Traits&gt;&amp; str, Functor&amp;&amp; functor)\n {\n for (auto&amp; c : str) {\n c = std::invoke(functor, c);\n }\n }\n\n template &lt;typename CharT, typename Traits, typename Functor&gt;\n auto transform_copy(std::basic_string_view&lt;CharT, Traits&gt;&amp; str, Functor&amp;&amp; functor)\n {\n std::basic_string result{str};\n transform(str, functor);\n return result;\n }\n}\n</code></pre>\n\n<p>Now the converter functions can be provided as wrappers around these.</p>\n\n<p>Also, please apply <code>remove_if(std::not_fn(needed))</code>, <code>sort</code>, and <code>unique</code> to these include directives:</p>\n\n<blockquote>\n<pre><code>#include &lt;iterator&gt;\n#include &lt;algorithm&gt;\n#include &lt;type_traits&gt;\n#include &lt;vector&gt;\n#include &lt;vector&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;locale&gt;\n#include &lt;functional&gt;\n</code></pre>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T13:23:48.073", "Id": "240048", "ParentId": "240035", "Score": "1" } }, { "body": "<ol>\n<li><p>Passing (most likely) chars by const-ref is, generally, inefficient.</p></li>\n<li><p>In-place can be done in-place, i.e. via <code>std::for_each</code>, or a range-for.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T21:02:34.197", "Id": "470997", "Score": "0", "body": "In what way is it inefficient?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T14:57:58.497", "Id": "240053", "ParentId": "240035", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T08:18:23.603", "Id": "240035", "Score": "4", "Tags": [ "c++", "template" ], "Title": "Copy and in-place transformation of strings to lowercase/uppercase" }
240035
<p>I have a sample code and some question. </p> <p>Simple type property</p> <pre><code>member val CabinetNetworkState : uint8 = 0uy with get, set member this.CabinetNetworkStateAsValues : (CabinetNetworkStateHosts * uint8) array = let cabinetNetworkStateMap = new ResizeArray&lt;(CabinetNetworkStateHosts * uint8)&gt; () let extNetworkState = (this.CabinetNetworkState &gt;&gt;&gt; 0) &amp;&amp;&amp; uint8 2 match Enum.IsDefined(typeof&lt;CabinetNetworkState&gt;, extNetworkState) with | true -&gt; cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.EXT, extNetworkState) | false -&gt; cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.EXT, 0uy) let canNetworkState = (this.CabinetNetworkState &gt;&gt;&gt; 3) &amp;&amp;&amp; uint8 2 match Enum.IsDefined(typeof&lt;CabinetNetworkState&gt;, canNetworkState) with | true -&gt; cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.CAN, canNetworkState) | false -&gt; cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.CAN, 0uy) let net1NetworkState = (this.CabinetNetworkState &gt;&gt;&gt; 5) &amp;&amp;&amp; uint8 2 match Enum.IsDefined(typeof&lt;CabinetNetworkState&gt;, net1NetworkState) with | true -&gt; cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.NET1, net1NetworkState) | false -&gt; cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.NET1, 0uy) let net2NetworkState = (this.CabinetNetworkState &gt;&gt;&gt; 7) &amp;&amp;&amp; uint8 2 match Enum.IsDefined(typeof&lt;CabinetNetworkState&gt;, net2NetworkState) with | true -&gt; cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.CAN, net2NetworkState) | false -&gt; cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.CAN, 0uy) cabinetNetworkStateMap.ToArray() </code></pre> <p>What it does it converts a value into array of bit value and enum that value represents My question is should I use Map instead of tuple array, or it does not matter?</p>
[]
[ { "body": "<p>A Map would have a roughly constant time lookup on keys but if there only going to be 4 entries then checking each item in an array will probably be quicker anyway.</p>\n\n<p>I think a much bigger issue is the repetition in the code and use of a <code>ResizeArray</code> to write in an imperative style when that can be easily avoided. Both of those issues are covered in this refactor (note that the names I used are quite arbitrary and you can probably come up with better ones):</p>\n\n<pre><code>member this.CabinetNetworkStateAsValues : (CabinetNetworkStateHosts * uint8) array =\n let makeStatePair state stateType =\n let networkState = (this.CabinetNetworkState &gt;&gt;&gt; state) &amp;&amp;&amp; 2uy\n if Enum.IsDefined(typeof&lt;CabinetNetworkState&gt;, networkState)\n then stateType, networkState\n else stateType, 0uy\n [|\n makeStatePair 0 CabinetNetworkStateHosts.EXT \n makeStatePair 3 CabinetNetworkStateHosts.CAN\n makeStatePair 5 CabinetNetworkStateHosts.NET1\n makeStatePair 7 CabinetNetworkStateHosts.CAN\n |]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T12:24:18.003", "Id": "240043", "ParentId": "240037", "Score": "3" } } ]
{ "AcceptedAnswerId": "240043", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T09:28:23.597", "Id": "240037", "Score": "2", "Tags": [ "f#" ], "Title": "F# Array with tuples or Map" }
240037
<p>I just started learning Rust and my first project is a command line tool generating a pairwise distance matrix for binary data while ignoring missing values. The input files look like so: </p> <pre><code>001N0 011N0 10N10 </code></pre> <p>with <code>N</code> denoting missing values that should be ignored. The example yields</p> <pre><code>0,1,1 1,0,2 1,2,0 </code></pre> <p>After parsing the command line args with <code>clap</code> each sample (i.e. line in input file) is parsed into a struct <code>BitArrNA</code> holding 2 <code>bitvec</code>; one called <code>bits</code> for the data (with <code>N</code> as <code>0</code>) and one called <code>not_nas</code> specifying the positions of not-NA-values (<code>0</code> if <code>N</code>, else <code>1</code>). To get the hamming distance between two <code>BitArrNA</code> three bitwise operations are necessary: I chose <code>^</code> between the two <code>bits</code>, <code>&amp;</code> between the two <code>not_nas</code> and <code>&amp;</code> between the two results. All samples are compared with each other and the distances are stored in a triangular matrix (a vector of vectors) in the struct <code>TriMat</code> before being written as comma-separated symmetric matrix to the output file.</p> <h3>Errors</h3> <p>After some reading about error handling philosophies in Rust, I decided to go with two strategies: </p> <ul> <li>Errors caused by invalid input are handled with <code>unwrap_or_else</code> and <code>std::process::exit</code> </li> <li>Other errors indicate internal bugs in my code/logic and should throw a <code>panic</code> with <code>expect</code></li> </ul> <h3>Questions</h3> <ul> <li>What could have been done in a more idiomatic way?</li> <li>Are there any low-hanging fruits in terms of performance / efficiency / concurrency?</li> <li>Is the error-handling suitable? </li> </ul> <h3>Code</h3> <p>main.rs</p> <pre><code>use binary_hamming_dist::bitarr::BitArrNa; use binary_hamming_dist::cli::parse_cmd_line; use binary_hamming_dist::trimat::TriMat; use indicatif::{ProgressBar, ProgressStyle}; use rayon::prelude::*; use std::fs; use std::io; use std::io::BufRead; type Dist = u32; fn main() { // get command line arguments let (infname, na_char, output, threads): (String, char, Option&lt;String&gt;, usize) = parse_cmd_line(); // create thread pool rayon::ThreadPoolBuilder::new() .num_threads(threads) .build_global() .expect("Error initializing threadpool"); // parse file into bitarr vec let mut bitarrs: Vec&lt;BitArrNa&gt; = Vec::new(); let infile = fs::File::open(infname).unwrap_or_else(|err| { eprintln!("Error opening input file: {}", err); std::process::exit(1); }); let infile = io::BufReader::new(infile); for (i, line) in infile.lines().enumerate() { if let Ok(line) = line { bitarrs.push(BitArrNa::from_string(&amp;line, na_char).unwrap_or_else(|err| { eprintln!("Error generating bitarr at line {}: {}", i + 1, err); std::process::exit(1); })); } else { eprintln!("Error reading input file at line {}", i + 1); std::process::exit(1); } } // create Vec of Vecs for holding the distances (resembling a triangular matrix) let n = bitarrs.len(); let mut dists: TriMat&lt;Dist&gt; = TriMat::new(n - 1); // setup progress bar let pb = ProgressBar::new(n as u64); pb.set_style( ProgressStyle::default_bar() .template("[{elapsed_precise}] [{bar:50.cyan/blue}] {pos}/{len} ({eta})") .progress_chars("#&gt;-"), ); // get the distances dists .mat .par_iter_mut() .zip(bitarrs[..n - 1].par_iter()) // skip last sample .enumerate() .for_each(|(i, (dists_i, bitarr_i))| { for bitarr_j in &amp;bitarrs[i + 1..] { dists_i.push(bitarr_i.dist(bitarr_j)); } pb.inc(1); }); pb.finish_with_message("done"); // write result to file if let Some(outfname) = output { let mut file = fs::File::create(&amp;outfname).unwrap_or_else(|err| { eprintln!("Error opening output file: {}", err); std::process::exit(1); }); dists.write_symmetric(&amp;mut file); println!("Result written to {}", outfname); } else { dists.write_symmetric(&amp;mut io::stdout()); } } </code></pre> <p>lib.rs -- only declaring modules for other lib files</p> <pre><code>pub mod bitarr; pub mod cli; pub mod trimat; </code></pre> <p>cli.rs -- holds function for command line parsing</p> <pre><code>pub fn parse_cmd_line() -&gt; (String, char, Option&lt;String&gt;, usize) { let matches = clap::App::new("Binary Hamming Distance Calculator") .about( "Calculates the pairwise distance matrix of binary strings and \ tolerates missing values. \n\ The input file should hold one sample per line and look like: \n\n\ 001X0 \n\ 011X0 \t where 'X' denotes a missing value. This yields \n\ 10X10 \n\n\ 0,1,1 \n\ 1,0,2 \t as result.\n\ 1,2,0 \n", ) .version(clap::crate_version!()) .arg( clap::Arg::with_name("input") .help("input file") .takes_value(true) .short("i") .long("input") .required(true) .value_name("FILE") .display_order(1), ) .arg( clap::Arg::with_name("NA-char") .help("the character [A-Za-z2-9] specifying missing values") .takes_value(true) .default_value("X") .possible_values(&amp;[ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "2", "3", "4", "5", "6", "7", "8", "9", ]) .hide_possible_values(true) .short("n") .long("NA-value") .value_name("CHAR") .display_order(2), ) .arg( clap::Arg::with_name("output") .help("output file; if missing, result is printed to STDOUT") .takes_value(true) .short("o") .long("output") .value_name("FILE") .display_order(3), ) .arg( clap::Arg::with_name("threads") .help("number of threads; '0' will use all available CPUs") .takes_value(true) .short("t") .long("threads") .default_value("1") .value_name("NUM"), ) .get_matches(); // calling unwrap is safe here because `input` was `required` by clap // and `NA-char` has a default as well as allowed arguments. let infname = matches.value_of("input").unwrap().to_string(); let na_char = matches.value_of("NA-char").unwrap().chars().next().unwrap(); let output = match matches.value_of("output") { None =&gt; None, Some(fname) =&gt; Some(fname.to_string()), }; let threads: usize = matches .value_of("threads") .unwrap() .parse() .unwrap_or_else(|err| { eprintln!( "Error parsing command line arguments: {}. \n\ Please provide a valid integer value for the threads argument", err ); std::process::exit(1); }); (infname, na_char, output, threads) } </code></pre> <p>bitarr.rs -- holds <code>BitArrNA</code> struct</p> <pre><code>use bitvec::prelude as bv; use itertools::izip; use std::fmt; pub struct BitArrNa { pub bits: bv::BitVec&lt;bv::Local, usize&gt;, pub not_nas: bv::BitVec&lt;bv::Local, usize&gt;, } impl BitArrNa { // create new `BitArrNa` with all-zero bits and all-one not_nas pub fn new(size: usize) -&gt; BitArrNa { let bits = bv::bitvec![0; size]; let not_nas = bv::bitvec![1; size]; BitArrNa { bits, not_nas } } pub fn from_string(string: &amp;str, na_char: char) -&gt; Result&lt;BitArrNa, String&gt; { let mut bitarr = BitArrNa::new(string.len()); for (i, c) in string.chars().enumerate() { if c == '0' { continue; } else if c == '1' { bitarr.bits.set(i, true); } else if c == na_char { bitarr.not_nas.set(i, false); } else { return Err(format!( "Char at position {} was \'{}\'; expected \'0\', \'1\' or \'{}\'.", i + 1, c, na_char )); } } Ok(bitarr) } pub fn dist&lt;T&gt;(&amp;self, other: &amp;BitArrNa) -&gt; T where T: num_traits::Num + num_traits::cast::FromPrimitive, { let mut result: T = T::zero(); for (bits, not_nas, other_bits, other_not_nas) in izip!( self.bits.as_slice(), self.not_nas.as_slice(), other.bits.as_slice(), other.not_nas.as_slice() ) { let res_bits = bits ^ other_bits; let res_not_nas = not_nas &amp; other_not_nas; let incr = T::from_u32((res_bits &amp; res_not_nas).count_ones()) .expect("Error converting distance to requested type"); result = result + incr; } result } } impl fmt::Display for BitArrNa { fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result { write!(f, "bits:\t\t{}\nnot_nas:\t{}", self.bits, self.not_nas) } } </code></pre> <p>trimat.rs -- holds <code>TriMat</code> struct</p> <pre><code>use std::cmp; use std::io; use std::ops; #[derive(Debug)] pub struct TriMat&lt;T&gt; { pub mat: Vec&lt;Vec&lt;T&gt;&gt;, } impl&lt;T&gt; TriMat&lt;T&gt; { pub fn new(n: usize) -&gt; TriMat&lt;T&gt; { let mut mat: Vec&lt;Vec&lt;T&gt;&gt; = Vec::with_capacity(n); for i in 0..n { mat.push(Vec::with_capacity(n - i)); } TriMat { mat } } } impl&lt;T&gt; TriMat&lt;T&gt; where T: num_traits::Zero + std::string::ToString + Copy, { pub fn write_symmetric&lt;Buffer: io::Write&gt;(&amp;self, buffer: &amp;mut Buffer) { let n = self.mat.len(); for i in 0..n + 1 { let mut line: Vec&lt;T&gt; = Vec::with_capacity(n); for j in 0..n + 1 { let dist: T; if i == j { dist = T::zero(); } else { let smaller = cmp::min(i, j); let larger = cmp::max(i, j); dist = self[smaller][larger - smaller - 1]; } line.push(dist); } let line: Vec&lt;String&gt; = line.into_iter().map(|i| i.to_string()).collect(); writeln!(buffer, "{}", &amp;line.join(",")) .expect(&amp;format!("Error writing result at i: {}", i)); } } } impl&lt;T&gt; ops::Index&lt;usize&gt; for TriMat&lt;T&gt; { type Output = Vec&lt;T&gt;; fn index(&amp;self, i: usize) -&gt; &amp;Self::Output { &amp;self.mat[i] } } impl&lt;T&gt; ops::IndexMut&lt;usize&gt; for TriMat&lt;T&gt; { fn index_mut(&amp;mut self, i: usize) -&gt; &amp;mut Self::Output { &amp;mut self.mat[i] } } </code></pre> <p>cargo.toml</p> <pre><code>[package] name = "binary_hamming_dist" version = "0.1.0" edition = "2018" [dependencies] bitvec = "0.17.4" itertools = "0.9.0" rayon = "1.3.0" indicatif = "0.14.0" clap = "~2.27.0" num-traits = "0.2.11" <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T09:59:53.787", "Id": "240039", "Score": "3", "Tags": [ "rust" ], "Title": "Pairwise hamming distance for binary data with missing values" }
240039
<p>When coding in C# I often miss some functions from the F# world. </p> <p>One of them is <a href="https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/seq.fs#L477" rel="nofollow noreferrer"><code>Seq.initInfinite</code></a>, others are its counterparts with the <code>AsyncSeq</code> library: </p> <ul> <li><p><a href="https://github.com/fsprojects/FSharp.Control.AsyncSeq/blob/28fe3c3ce9a8adbe3c914852b70f8fef120ec04b/src/FSharp.Control.AsyncSeq/AsyncSeq.fs#L933" rel="nofollow noreferrer"><code>AsyncSeq.initInfiniteAsync</code></a></p></li> <li><p><a href="https://github.com/fsprojects/FSharp.Control.AsyncSeq/blob/28fe3c3ce9a8adbe3c914852b70f8fef120ec04b/src/FSharp.Control.AsyncSeq/AsyncSeq.fs#L950" rel="nofollow noreferrer"><code>AsyncSeq.initInfinite</code></a></p></li> </ul> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Threading.Tasks; public static class Enumerable { public static IEnumerable&lt;T&gt; InitInfinite&lt;T&gt;(Func&lt;T&gt; itemFactory) { while (true) { yield return itemFactory(); } // ReSharper disable once IteratorNeverReturns } public static IEnumerable&lt;T&gt; InitInfinite&lt;T&gt;(Func&lt;BigInteger, T&gt; itemFactory) { var index = BigInteger.Zero; while (true) { yield return itemFactory(index); index++; } // ReSharper disable once IteratorNeverReturns } } public static class AsyncEnumerable { #pragma warning disable 1998 public static async IAsyncEnumerable&lt;T&gt; InitInfinite&lt;T&gt;(Func&lt;T&gt; itemFactory) #pragma warning restore 1998 { while (true) { yield return itemFactory(); } // ReSharper disable once IteratorNeverReturns } #pragma warning disable 1998 public static async IAsyncEnumerable&lt;T&gt; InitInfinite&lt;T&gt;(Func&lt;BigInteger, T&gt; itemFactory) #pragma warning restore 1998 { var index = BigInteger.Zero; while (true) { yield return itemFactory(index); index++; } // ReSharper disable once IteratorNeverReturns } public static async IAsyncEnumerable&lt;T&gt; InitInfiniteAsync&lt;T&gt;(Func&lt;Task&lt;T&gt;&gt; asyncItemFactory) { while (true) { yield return await asyncItemFactory(); } // ReSharper disable once IteratorNeverReturns } public static async IAsyncEnumerable&lt;T&gt; InitInfiniteAsync&lt;T&gt;(Func&lt;BigInteger, Task&lt;T&gt;&gt; asyncItemFactory) { var index = BigInteger.Zero; while (true) { yield return await asyncItemFactory(index); index++; } // ReSharper disable once IteratorNeverReturns } } </code></pre> <p>My code is working as expected, like in the example below:</p> <pre><code>public static class Program { public static async Task Main() { var asyncResultWithIntegers = await AsyncEnumerable .InitInfiniteAsync(i =&gt; Task.FromResult(i)) .Take(4) .ToArrayAsync(); var asyncResultWithoutIntegers = await AsyncEnumerable .InitInfiniteAsync(() =&gt; Task.FromResult("Hi there!")) .Take(4) .ToArrayAsync(); var resultWithIntegers = await AsyncEnumerable .InitInfinite(i =&gt; i) .Take(4) .ToArrayAsync(); var resultWithoutIntegers = await AsyncEnumerable .InitInfinite(() =&gt; "Hi there!") .Take(4) .ToArrayAsync(); Console.ReadKey(); } } </code></pre> <p>I am wondering if there is a better way to implement those. In particular, is there a way to implement those methods without disabling the ReSharper warnings?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T15:24:00.063", "Id": "470809", "Score": "0", "body": "Hey, welcome to Code Review! It seems like someone voted to close this question because it does not work. Does your code currently work as intended? If yes, please state so in the question (to avoid confusion). You might also want to add an example of how this code is being used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T15:27:39.677", "Id": "470811", "Score": "0", "body": "@Graipher thanks your message\n\"It seems like someone voted to close this question because it does not work\" I kinda resent when people are doing that without giving any sort of guidance (I know it's not a requirement) but afaik no explicit reason was given when the downvote happened.\n\n\"Does your code currently work as intended?\"\nYes, it does" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T15:35:12.370", "Id": "470812", "Score": "0", "body": "Well, yeah, it kinda sucks sometimes. I agree that if voting to close because the code does not work this should be worth a comment. But I also have to admit that I don't do it everytime as well... But if it is because of a bug I try to always comment, because otherwise the other people in the queue have no guidance about what is wrong. Let alone the OP not knowing what they should fix, if anything, either, as you have experienced now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T15:36:31.883", "Id": "470813", "Score": "1", "body": "Agreed, I'm adding a few examples, and my code should be all good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T19:47:43.040", "Id": "470852", "Score": "0", "body": "What's with the magic numbers? The examples show your code in action, which is good, but for those of us not fluent in F#, what really prompted you to write this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T19:55:19.893", "Id": "470854", "Score": "0", "body": "If you're talking about the pragma number: https://stackoverflow.com/questions/13243975/suppress-warning-cs1998-this-async-method-lacks-await\n\nAh... don't tell me that =|" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T21:43:59.167", "Id": "470872", "Score": "1", "body": "Do you actually need infinity results? Or do you always expect to Take a certain amount? If it's the latter, you could just use [Enumerable.Repeat](https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.repeat?view=netframework-4.8) or [Enumerable.Range](https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.range?view=netframework-4.8)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T09:13:40.653", "Id": "470911", "Score": "0", "body": "@devNull I'll answer you tonight. But yes I possibly need an infinity of results (can depend on some parameters, say user input)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T12:27:14.150", "Id": "240044", "Score": "1", "Tags": [ "c#" ], "Title": "F# InitInfinite(Async) functions in C# without disabling ReSharper warnings" }
240044
<p>I wrote a program that saves the data from the first table of <a href="https://de.wikipedia.org/wiki/COVID-19-Pandemie_in_Deutschland" rel="nofollow noreferrer">this</a> Wikipedia article (in German) and then saves the column &quot;Gesamt&quot; (contains daily update of absolute numbers of COVID-19 infected people in Germany) together with the date in a CSV file. After that it draws a chart with logarithmical axis.</p> <p>For the parsing, I used JSoup and for saving the data in the CSV file, I used a <code>FileWriter</code>. For the chart, I used swing and JFree.</p> <pre><code>import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.time.LocalDate; import java.io.FileWriter; import java.time.format.DateTimeFormatter; import java.io.IOException; import org.jfree.chart.axis.LogAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import javax.swing.*; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; public class Corona { public static void main(String[] args) throws IOException { int[] array = getData(); saveData(array); visualizeData(array); } public static int[] getData() { //Saving data from wikipedia in a 2D-String-Array String url = &quot;https://de.wikipedia.org/wiki/COVID-19-Pandemie_in_Deutschland&quot;; String[][] a = new String[365][30]; try{ Document doc = Jsoup.connect(url).get(); Element table = doc.getElementsByClass(&quot;wikitable zebra toptextcells mw-collapsible&quot;).first(); Elements rows = table.getElementsByTag(&quot;tr&quot;); int i = 0; int j = 0; for (Element row : rows) { Elements cells = row.getElementsByTag(&quot;td&quot;); for (Element cell : cells) { a[j][i] = cell.text().concat(&quot;, &quot;); i++; } j++; i = 0; } } catch (IOException e){ e.printStackTrace(); } //Only taking column with absolute numbers for whole country int[] array = new int[365]; for(int k = 0; k &lt; array.length; k++) { if(a[k][17] != null) { a[k][17] = a[k][17].split(&quot;,&quot;)[0]; a[k][17] = a[k][17].replaceAll(&quot;[.]&quot;,&quot;&quot;); array[k] = Integer.parseInt(a[k][17]); } } return array; } public static void saveData(int[] array) throws IOException { //Writing date and data from array to csv-file LocalDate date = LocalDate.of(2020, 2, 24); FileWriter writer = new FileWriter(&quot;data.csv&quot;); writer.append(&quot;&quot;); writer.append(&quot;\n&quot;); for(int i = 0; i &lt; array.length - 1; i++) { writer.append(date.format(DateTimeFormatter.ofPattern(&quot;dd/MM/yyyy&quot;))); writer.append(&quot;,&quot;); writer.append(Integer.toString(array[i + 1])); writer.append(&quot;\n&quot;); date = date.plusDays(1); } writer.flush(); writer.close(); } public static void visualizeData(int[] array) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { //JFrame and JPanel JFrame frame = new JFrame(&quot;Corona-Statistics&quot;); frame.setSize(600,600); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); JPanel panel = new JPanel(new BorderLayout()); //Series gets filled up with data XYSeries series = new XYSeries(&quot;XYGraph&quot;); int i = 1; while(array[i] &gt; 0) { series.add(i - 1, array[i]); i++; } //Printing the chart NumberAxis xAxis = new NumberAxis(&quot;Days since 24-02-20&quot;); LogAxis yAxis = new LogAxis(&quot;People infected with Covid-19 in Germany&quot;); yAxis.setBase(10); XYPlot plot = new XYPlot(new XYSeriesCollection(series), xAxis, yAxis, new XYLineAndShapeRenderer(true, false)); JFreeChart chart = new JFreeChart( &quot;People infected with Covid-19 in Germany&quot;, JFreeChart.DEFAULT_TITLE_FONT, plot, false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ChartPanel chartpanel = new ChartPanel(chart); //Adding chartpanel to panel panel.add(chartpanel, BorderLayout.NORTH); //Button to open csv JButton button = new JButton(&quot;Open csv&quot;); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { Runtime run = Runtime.getRuntime(); try { Process pp = run.exec(&quot;libreoffice data.csv&quot;); } catch(Exception e) { e.printStackTrace(); } } }); //Button to update data JButton button2 = new JButton(&quot;Update data&quot;); button2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { try { frame.setVisible(false); frame.dispose(); final int[] a = getData(); saveData(a); visualizeData(a); } catch(IOException e) { } } }); //Adding buttons to subpanel JPanel subpanel = new JPanel(new GridLayout(1,2)); subpanel.add(button); subpanel.add(button2); panel.add(subpanel, BorderLayout.SOUTH); frame.add(panel); frame.setVisible(true); } }); } } </code></pre> <p>The program has no special purpose, it's for practice only.</p> <p>My question now is: How can I improve the code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T13:52:39.797", "Id": "471133", "Score": "2", "body": "Oh my, that's a lot of magic numbers." } ]
[ { "body": "<p>I have some suggestions for your code:</p>\n\n<blockquote>\n<pre><code>String[][] a = new String[365][30];\nint i = 0;\nint j = 0;\nfor (Element row : rows) {\n Elements cells = row.getElementsByTag(\"td\");\n for (Element cell : cells) {\n a[j][i] = cell.text().concat(\", \");\n i++;\n }\n j++;\n i = 0;\n}\n</code></pre>\n</blockquote>\n\n<p>You are storing a m * n matrix of values retrieved by jsoup in a 2d array, but this can be avoided? Here the second part of your code :</p>\n\n<blockquote>\n<pre><code>int[] array = new int[365];\nfor(int k = 0; k &lt; array.length; k++) {\n if(a[k][17] != null) {\n a[k][17] = a[k][17].split(\",\")[0];\n a[k][17] = a[k][17].replaceAll(\"[.]\",\"\");\n array[k] = Integer.parseInt(a[k][17]);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>The values you are interested are in the 17th column of the table, so instead of a 2d matrix, you can use directly an int array where to store elements. You are doing a lot of not necessary work parsing by yourself strings like \"1.234\" and convert them to integer without the point for thousands, use instead the class <a href=\"https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html\" rel=\"nofollow noreferrer\">NumberFormat</a>:</p>\n\n<pre><code>NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);\nint value = nf.parse(\"1.234\").intValue(); // it will contain the number 1234\n</code></pre>\n\n<p>You can extract the 17th column values from your table using the jsoup <code>Element</code> <code>get</code> method checking if the row you are examining has at least 18 elements:</p>\n\n<pre><code>for (int i = 0; i &lt; rows.size(); ++i) {\n Elements cells = rows.get(i).getElementsByTag(\"td\");\n if (cells.size() &gt; 17) {\n Element cell = cells.get(17);\n array[i] = nf.parse(cell.text()).intValue(); //&lt;-- nf.parse call\n }\n}\n</code></pre>\n\n<p>So your method <code>getData</code> can be rewritten like this:</p>\n\n<pre><code>public static int[] getData() throws IOException, ParseException {\n String url = \"https://de.wikipedia.org/wiki/COVID-19-Pandemie_in_Deutschland\";\n int[] array = new int[365];\n\n Document doc = Jsoup.connect(url).get();\n Element table = doc.getElementsByClass(\"wikitable zebra toptextcells mw-collapsible\").first();\n Elements rows = table.getElementsByTag(\"tr\");\n\n NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);\n\n for (int i = 0; i &lt; rows.size(); ++i) {\n Elements cells = rows.get(i).getElementsByTag(\"td\");\n if (cells.size() &gt; 17) {\n Element cell = cells.get(17);\n array[i] = nf.parse(cell.text()).intValue();\n }\n }\n\n return array;\n}\n</code></pre>\n\n<p>Some minor changes can be applied to your other method <code>saveData</code>, first is use of try with resources to avoid manual closing and flushing of the <code>FileWriter</code>:</p>\n\n<pre><code>try (FileWriter writer = new FileWriter(\"data.csv\")) { /*here your logic*/ }\n</code></pre>\n\n<p>Second, to avoid use of consecutive appends , you can use the <code>write</code> method of the <code>FileWriter</code> class rewriting the method in this way:</p>\n\n<pre><code>public static void saveData(int[] array) throws IOException {\n LocalDate date = LocalDate.of(2020, 2, 24);\n DateTimeFormatter df = DateTimeFormatter.ofPattern(\"dd/MM/yyyy\");\n\n try (FileWriter writer = new FileWriter(\"data.csv\")) {\n writer.write(\"\\n\");\n String template = \"%s,%d\\n\";\n for(int i = 0; i &lt; array.length - 1; i++) {\n String data = String.format(template, date.format(df), array[i + 1]);\n writer.write(data);\n date = date.plusDays(1);\n }\n }\n}\n</code></pre>\n\n<p>I defined a <code>template</code> variable so the format of the data is more readable and easier to modify.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T17:33:14.270", "Id": "240152", "ParentId": "240045", "Score": "4" } } ]
{ "AcceptedAnswerId": "240152", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T12:41:48.557", "Id": "240045", "Score": "3", "Tags": [ "java", "parsing", "covid-19", "jsoup" ], "Title": "Saving data from table of COVID-19 infections in Germany" }
240045
<p>I have (designed and) implemented this fancy sorting algorithm that combines natural runs in the input array with a heap data structure:</p> <pre><code>function ArrayRangeException(message) { this.message = message; this.getMessage = function() { return this.message; } } function RangeCheck(arrayLength, fromIndex, toIndex) { if (fromIndex &lt; 0) { throw new ArrayRangeException("'fromIndex' is negative: " + fromIndex); } if (toIndex &gt; arrayLength) { throw new ArrayRangeException( "'toIndex' is too large: " + toIndex + ", array length: " + arrayLength); } if (fromIndex &gt; toIndex) { throw new ArrayRangeException( "fromIndex(" + fromIndex + ") &gt; toIndex(" + toIndex + ")"); } } function RunHeap(array, cmp) { this.cmp = cmp; this.array = array; const auxArrayLength = (array.length &gt;&gt;&gt; 1) + 1; this.fromIndexArray = Array(auxArrayLength); this.toIndexArray = Array(auxArrayLength); this.size = 0; this.pushRun = function(fromIndex, toIndex) { const nodeIndex = this.size++; this.fromIndexArray[nodeIndex] = fromIndex; this.toIndexArray[nodeIndex] = toIndex; }, this.popElement = function() { const returnValue = this.array[this.fromIndexArray[0]]; this.fromIndexArray[0]++; if (this.fromIndexArray[0] === this.toIndexArray[0]) { const last1 = this.fromIndexArray[--this.size]; this.fromIndexArray[0] = last1; const last2 = this.toIndexArray[this.size]; this.toIndexArray[0] = last2; } this.siftDown(0); return returnValue; }, this.swap = function(array, index1, index2) { const tmp = array[index1]; array[index1] = array[index2]; array[index2] = tmp; }, this.isLessThan = function(runIndex1, runIndex2) { const element1 = this.array[this.fromIndexArray[runIndex1]]; const element2 = this.array[this.fromIndexArray[runIndex2]]; const cmp = this.cmp(element1, element2); if (cmp != 0) { return cmp &lt; 0; } return this.fromIndexArray[runIndex1] &lt; this.fromIndexArray[runIndex2]; }, this.siftDown = function(index) { let nodeIndex = index; let leftChildIndex = (index &lt;&lt; 1) + 1 let rightChildIndex = leftChildIndex + 1; let minIndex = index; while (true) { if (leftChildIndex &lt; this.size &amp;&amp; this.isLessThan(leftChildIndex, nodeIndex)) { minIndex = leftChildIndex; } if (rightChildIndex &lt; this.size &amp;&amp; this.isLessThan(rightChildIndex, minIndex)) { minIndex = rightChildIndex; } if (minIndex === nodeIndex) { return; } this.swap(this.fromIndexArray, minIndex, nodeIndex); this.swap(this.toIndexArray, minIndex, nodeIndex); nodeIndex = minIndex; leftChildIndex = (nodeIndex &lt;&lt; 1) + 1; rightChildIndex = leftChildIndex + 1; } }, this.buildHeap = function() { for (i = Math.floor(this.size / 2); i &gt;= 0; --i) { this.siftDown(i); } }, this.extendRun = function(length) { this.toIndexArray[this.size - 1] += length; }, this.appendRun = function(fromIndex, toIndex) { this.fromIndexArray[this.size] = fromIndex; this.toIndexArray[this.size] = toIndex; this.size++; } } function reverseRun(array, fromIndex, toIndex) { for (i1 = fromIndex, i2 = toIndex; i1 &lt; i2; i1++, i2--) { const savedArrayComponent = array[i1]; array[i1] = array[i2]; array[i2] = savedArrayComponent; } } function createRunHeap(array, cmp) { let runHeap = new RunHeap(array, cmp); let left = 0; let right = 1; let last = array.length - 1; let previousWasDescending = false; while (left &lt; last) { head = left; right = left + 1; if (cmp(array[left], array[right]) &lt;= 0) { while (left &lt; last &amp;&amp; cmp(array[left], array[right]) &lt;= 0) { ++left; ++right; } if (previousWasDescending) { if (cmp(array[head - 1], array[head]) &lt;= 0) { runHeap.extendRun(right - head); } else { runHeap.appendRun(head, right); } } else { runHeap.appendRun(head, right); } previousWasDescending = false; } else { // Scan a descending run: while (left &lt; last &amp;&amp; cmp(array[left], array[right]) &gt; 0) { ++left; ++right; } reverseRun(array, head, left); if (previousWasDescending) { if (cmp(array[head - 1], array[head]) &lt;= 0) { runHeap.extendRun(right - head); } else { runHeap.appendRun(head, right); } } else { runHeap.appendRun(head, right); } previousWasDescending = true; } ++left; ++right; } if (left === last) { if (cmp(array[last - 1], array[last]) &lt;= 0) { runHeap.extendRun(1); } else { runHeap.appendRun(last, last + 1); } } return runHeap; } Array.prototype.heapSelectionSort = function(cmp, fromIndex, toIndex) { if (!cmp) { cmp = (a, b) =&gt; a - b; } if (!fromIndex) { fromIndex = 0; } if (!toIndex) { toIndex = this.length; } RangeCheck(this.length, fromIndex, toIndex); if (toIndex - fromIndex &lt; 2) { return this; } const aux = this.slice(fromIndex, toIndex); const runHeap = createRunHeap(aux, cmp); runHeap.buildHeap(); let index = fromIndex; while (index &lt; toIndex) { this[index] = runHeap.popElement(); index++; } return this; }; </code></pre> <p>(The entire demo gist is here: <a href="https://gist.github.com/coderodde/47ae57983954c89ab7bef21b3fa7b232" rel="nofollow noreferrer">https://gist.github.com/coderodde/47ae57983954c89ab7bef21b3fa7b232</a>)</p> <p><strong>Critique request</strong></p> <p>Since I am not a professional Javascript developer, I would like to make my code above on par with idiomatic JS code.</p>
[]
[ { "body": "<p>Some possible improvements:</p>\n\n<p>Your <code>ArrayRangeException</code> has a <code>getMessage</code> property that is never referenced elsewhere (even if a consumer were to know about it, it would be much simpler for it to just use the <code>.message</code> property). But it's still basically just an object wrapper around a string. Since you're going to be throwing, you might consider using a built-in <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError\" rel=\"nofollow noreferrer\">RangeError</a> instead, eg:</p>\n\n<pre><code>if (toIndex &gt; arrayLength) {\n throw new RangeError(\n \"'toIndex' is too large: \" + toIndex + ', array length: ' +\n arrayLength);\n}\n</code></pre>\n\n<p>You can also consider using template literals, which some consider to be more readable than concatenation:</p>\n\n<pre><code>if (toIndex &gt; arrayLength) {\n throw new RangeError(`'toIndex' is too large: ${toIndex}, array length: ${arrayLength}`);\n}\n</code></pre>\n\n<p><code>RangeCheck</code> isn't a constructor, so it probably shouldn't be capitalized.</p>\n\n<p>Your <code>RunHeap</code> constructor assigns lots of function properties directly to the instance, and chains them with the comma operator:</p>\n\n<pre><code>this.pushRun = function(fromIndex, toIndex) {\n // ...\n},\nthis.popElement = function() {\n // ...\n},\nthis.swap = function(array, index1, index2) {\n // ...\n</code></pre>\n\n<p>The comma operator <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Comma_Operator\" rel=\"nofollow noreferrer\">evaluates each of its operands (from left to right) and returns the value of the last operand</a>. This can be <a href=\"https://stackoverflow.com/questions/3561043/what-does-a-comma-do-in-javascript-expressions\">somewhat</a> <a href=\"https://stackoverflow.com/questions/9579546/when-is-the-comma-operator-useful\">confusing</a>, and so is often forbidden by code style guides. Since each function assignment here can be standalone, have each be a separate statement instead, and separate them with semicolons:</p>\n\n<pre><code>this.pushRun = function(fromIndex, toIndex) {\n // ...\n};\nthis.popElement = function() {\n // ...\n};\nthis.swap = function(array, index1, index2) {\n // ...\n</code></pre>\n\n<p>But there's another issue - this creates those <code>pushRun</code>, <code>popElement</code>, <code>swap</code> methods anew <em>every time</em> the <code>RunHeap</code> constructor is run. This is inefficient; the functions are all the same. Put them on the prototype instead, so that they only have to be created once:</p>\n\n<pre><code>function RunHeap(array, cmp) {\n this.cmp = cmp;\n // ...\n}\nRunHeap.prototype.pushRun = function(fromIndex, toIndex) {\n // ...\n};\n\nRunHeap.prototype.popElement = function() {\n // ...\n</code></pre>\n\n<p>Since you're already using ES6+ syntax (which is great, you should), it'd probably be a good idea to use it everywhere - instead of a <code>function</code> that you call <code>new</code> on, you can use <code>class</code>, they're a bit more concise and readable, and are the preferred modern way of doing things:</p>\n\n<pre><code>class RunHeap {\n constructor(array, cmp) {\n this.cmp = cmp;\n // ...\n }\n pushRun(fromIndex, toIndex) {\n const nodeIndex = this.size++;\n // ...\n }\n popElement() {\n const returnValue = this.array[this.fromIndexArray[0]];\n // ...\n</code></pre>\n\n<p>Using <code>++</code> / <code>--</code> as a standalone statement is fine, but they can sometimes be confusing when they're used as an expression. (This is the same idea behind avoiding <a href=\"https://eslint.org/docs/rules/no-multi-assign\" rel=\"nofollow noreferrer\">chained assignments</a> and <a href=\"https://eslint.org/docs/rules/no-cond-assign\" rel=\"nofollow noreferrer\">conditional assignments</a>) You might consider putting the increments/decrements on their own line, eg replace</p>\n\n<pre><code>const last1 = this.fromIndexArray[--this.size];\n</code></pre>\n\n<p>with</p>\n\n<pre><code>this.size--;\nconst last1 = this.fromIndexArray[this.size];\n</code></pre>\n\n<p>Same for the other instances of pre/post increment-as-expression.</p>\n\n<p>(even if <em>you</em> find the first version readable at a glance, I wouldn't bet on most readers of the code seeing it the same way)</p>\n\n<p><code>if (cmp != 0) {</code> When comparing, best to use strict equality, <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">not loose equality</a>.</p>\n\n<p><code>for (i = Math.floor(this.size / 2); i &gt;= 0; --i) {</code> Best to always declare variables before using them - this will either implicitly create a global variable <code>i</code>, or throw an error if in strict mode. (change to <code>let i =</code>) (Same for <code>for (i1 = fromIndex, i2 = toIndex;</code> and <code>head = left</code>)</p>\n\n<p>The <code>swap</code> function does the same thing as is done in each iteration of the <code>reverseRun</code> loop. Maybe have <code>reverseRun</code> call <code>swap</code>?</p>\n\n<p>ES6 allows for default arguments in the case nothing is passed:</p>\n\n<pre><code>Array.prototype.heapSelectionSort = function (cmp, fromIndex, toIndex) {\n if (!cmp) {\n cmp = (a, b) =&gt; a - b;\n }\n\n if (!fromIndex) {\n fromIndex = 0;\n }\n\n if (!toIndex) {\n toIndex = this.length;\n }\n</code></pre>\n\n<p>can be:</p>\n\n<pre><code>Array.prototype.heapSelectionSort = function (\n cmp = (a, b) =&gt; a - b,\n fromIndex = 0,\n toIndex = this.length\n) {\n</code></pre>\n\n<p>It's <a href=\"https://stackoverflow.com/q/14034180\">usually a bad idea</a> to mutate the built-in objects, like <code>Array.prototype</code>. (Bad frameworks putting non-standard methods onto prototypes <a href=\"https://stackoverflow.com/a/55934491\">is why</a> we have <code>Array.prototype.flat</code> instead of <code>Array.prototype.flatten</code>, and <code>Array.prototype.includes</code> instead of <code>Array.prototype.contains</code>.) It can cause a few problems. You could have <code>heapSelectionSort</code> be a standalone function instead.</p>\n\n<p>In full:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const heapSelectionSort = (() =&gt; {\n 'use strict';\n function rangeCheck(arrayLength, fromIndex, toIndex) {\n if (fromIndex &lt; 0) {\n throw new RangeError(`'fromIndex' is negative: ${fromIndex}`);\n }\n if (toIndex &gt; arrayLength) {\n throw new RangeError(`'toIndex' is too large: ${toIndex}, array length: ${arrayLength}`);\n }\n if (fromIndex &gt; toIndex) {\n throw new RangeError(`fromIndex(${fromIndex}) &gt; toIndex(${toIndex})`);\n }\n }\n\n const swap = (array, index1, index2) =&gt; {\n const tmp = array[index1];\n array[index1] = array[index2];\n array[index2] = tmp;\n };\n\n class RunHeap {\n constructor(array, cmp) {\n this.cmp = cmp;\n this.array = array;\n const auxArrayLength = (array.length &gt;&gt;&gt; 1) + 1;\n this.fromIndexArray = Array(auxArrayLength);\n this.toIndexArray = Array(auxArrayLength);\n this.size = 0;\n }\n pushRun(fromIndex, toIndex) {\n this.fromIndexArray[this.size] = fromIndex;\n this.toIndexArray[this.size] = toIndex;\n this.size++;\n }\n popElement() {\n const returnValue = this.array[this.fromIndexArray[0]];\n this.fromIndexArray[0]++;\n\n if (this.fromIndexArray[0] === this.toIndexArray[0]) {\n this.size--;\n const last1 = this.fromIndexArray[this.size];\n this.fromIndexArray[0] = last1;\n\n const last2 = this.toIndexArray[this.size];\n this.toIndexArray[0] = last2;\n }\n\n this.siftDown(0);\n return returnValue;\n }\n isLessThan(runIndex1, runIndex2) {\n const element1 = this.array[this.fromIndexArray[runIndex1]];\n const element2 = this.array[this.fromIndexArray[runIndex2]];\n const cmp = this.cmp(element1, element2);\n\n if (cmp !== 0) {\n return cmp &lt; 0;\n }\n\n return this.fromIndexArray[runIndex1] &lt; this.fromIndexArray[runIndex2];\n }\n\n siftDown(index) {\n let nodeIndex = index;\n let leftChildIndex = (index &lt;&lt; 1) + 1;\n let rightChildIndex = leftChildIndex + 1;\n let minIndex = index;\n\n while (true) {\n if (leftChildIndex &lt; this.size &amp;&amp; this.isLessThan(leftChildIndex, nodeIndex)) {\n minIndex = leftChildIndex;\n }\n\n if (rightChildIndex &lt; this.size &amp;&amp; this.isLessThan(rightChildIndex, minIndex)) {\n minIndex = rightChildIndex;\n }\n\n if (minIndex === nodeIndex) {\n return;\n }\n\n swap(this.fromIndexArray, minIndex, nodeIndex);\n swap(this.toIndexArray, minIndex, nodeIndex);\n\n nodeIndex = minIndex;\n leftChildIndex = (nodeIndex &lt;&lt; 1) + 1;\n rightChildIndex = leftChildIndex + 1;\n }\n }\n\n buildHeap() {\n for (let i = Math.floor(this.size / 2); i &gt;= 0; i--) {\n this.siftDown(i);\n }\n }\n\n extendRun(length) {\n this.toIndexArray[this.size - 1] += length;\n }\n\n appendRun(fromIndex, toIndex) {\n this.fromIndexArray[this.size] = fromIndex;\n this.toIndexArray[this.size] = toIndex;\n this.size++;\n }\n }\n\n function reverseRun(array, fromIndex, toIndex) {\n for (let i1 = fromIndex, i2 = toIndex; i1 &lt; i2; i1++ , i2--) {\n swap(array, i1, i2);\n }\n }\n\n function createRunHeap(array, cmp) {\n const runHeap = new RunHeap(array, cmp);\n let left = 0;\n let right = 1;\n const last = array.length - 1;\n let previousWasDescending = false;\n\n while (left &lt; last) {\n const head = left;\n right = left + 1;\n\n if (cmp(array[left], array[right]) &lt;= 0) {\n while (left &lt; last &amp;&amp; cmp(array[left], array[right]) &lt;= 0) {\n left++;\n right++;\n }\n\n if (previousWasDescending) {\n if (cmp(array[head - 1], array[head]) &lt;= 0) {\n runHeap.extendRun(right - head);\n } else {\n runHeap.appendRun(head, right);\n }\n } else {\n runHeap.appendRun(head, right);\n }\n\n previousWasDescending = false;\n } else { // Scan a descending run:\n while (left &lt; last &amp;&amp; cmp(array[left], array[right]) &gt; 0) {\n left++;\n right++;\n }\n\n reverseRun(array, head, left);\n\n if (previousWasDescending) {\n if (cmp(array[head - 1], array[head]) &lt;= 0) {\n runHeap.extendRun(right - head);\n } else {\n runHeap.appendRun(head, right);\n }\n } else {\n runHeap.appendRun(head, right);\n }\n\n previousWasDescending = true;\n }\n\n left++;\n right++;\n }\n\n if (left === last) {\n if (cmp(array[last - 1], array[last]) &lt;= 0) {\n runHeap.extendRun(1);\n } else {\n runHeap.appendRun(last, last + 1);\n }\n }\n\n return runHeap;\n }\n\n return (\n arr,\n cmp = (a, b) =&gt; a - b,\n fromIndex = 0,\n toIndex = arr.length\n ) =&gt; {\n rangeCheck(arr.length, fromIndex, toIndex);\n\n if (toIndex - fromIndex &lt; 2) {\n return arr;\n }\n\n const aux = arr.slice(fromIndex, toIndex);\n const runHeap = createRunHeap(aux, cmp);\n runHeap.buildHeap();\n\n let index = fromIndex;\n\n while (index &lt; toIndex) {\n arr[index] = runHeap.popElement();\n index++;\n }\n\n return arr;\n };\n})();\n\nconsole.log(\n heapSelectionSort([4, 5, 0, 1, 7, 8])\n);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T00:03:05.267", "Id": "240077", "ParentId": "240046", "Score": "1" } } ]
{ "AcceptedAnswerId": "240077", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T12:45:02.000", "Id": "240046", "Score": "1", "Tags": [ "javascript", "array", "sorting", "heap", "heap-sort" ], "Title": "Heap selection sort in Javascript" }
240046
Jsoup is a Java library that is designed for parsing, extracting and manipulating data that is stored in HTML-documents. The library is open-source.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T13:44:08.570", "Id": "240050", "Score": "0", "Tags": null, "Title": null }
240050
<p>I have the following: </p> <ol> <li>A set of <code>K</code> time-series in a numpy array with dimensions <code>T x K</code>.</li> <li>A set of <code>P</code> permuted approximation of them in a numpy array with dimensions <code>P times T</code>. </li> </ol> <p>I need a dictionary that tells me which is the most probable permutation. For that I've created the following function, but I would like to know if can be done in a more efficient way and with less code to do this.</p> <pre><code>def find_permutation(true, permuted): """ Finds the most probable permutation of true time series in between permuted time series :param true: true ordered time series of shape T times X :param permuted: Permuted time series of shape P times T. P &gt; K :return: A dict containing {true idx: permuted idx} """ N = true.shape[1] max_comps = permuted.shape[0] permutation_dict = {} used_comps = [] corr_matrix = np.zeros((N, max_comps)) # Find correlations for i in range(N): for j in range(max_comps): corr_matrix[i, j] = np.corrcoef(true[:, i], permuted[j, :])[0, 1] # Find best order per_matrix = np.argsort(-np.abs(corr_matrix), axis=1) for i in range(N): for j in per_matrix[i, :]: if j in used_comps: continue else: permutation_dict[i] = j used_comps.append(j) break return permutation_dict if __name__ == "__main__": import numpy as np a = np.array([1, 2, 3, 4.]) b = np.array([4, 8, 9, 12.]) c = np.array([9, 5, 8, 9.]) true = np.vstack([a, b, c]).transpose() permuted = np.vstack([b*0.2, c*0.5, a*0.7]) print(find_permutation(true, permuted)) # {0: 2, 1: 0, 2: 1} </code></pre> <p>Here a Cython version</p> <pre><code># C imports first cimport numpy as np # other imports import numpy as np import cython # Type declarations DTYPE = np.float ctypedef np.float_t DTYPE_t @cython.boundscheck(False) # Deactivate bounds checking @cython.wraparound(False) # Deactivate negative indexing. def find_permutation(np.ndarray[DTYPE_t, ndim=2] true, np.ndarray[DTYPE_t, ndim=2] permuted): """ Finds the most probable permutation of true time series in between permuted time series :param true: true ordered time series of shape T times X :param permuted: Permuted time series of shape P times T. P &gt; K :return: A dict containing {true idx: permuted idx} """ cdef unsigned int N = true.shape[1] cdef unsigned int max_comps = permuted.shape[0] cdef dict permutation_dict = {} cdef list used_comps = [] cdef np.ndarray[DTYPE_t, ndim=2] corr_matrix corr_matrix = np.zeros((N, max_comps)) cdef Py_ssize_t i cdef Py_ssize_t j # Find correlations for i in range(N): for j in range(max_comps): corr_matrix[i, j] = np.corrcoef(true[:, i], permuted[j, :])[0, 1] # Find best order cdef np.ndarray[long, ndim=2] per_matrix per_matrix = np.argsort(-np.abs(corr_matrix), axis=1) for i in range(N): for j in per_matrix[i, :]: if j in used_comps: continue else: permutation_dict[i] = j used_comps.append(j) break return permutation_dict </code></pre> <p>Any suggestion is more than welcome. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T10:04:14.777", "Id": "470914", "Score": "0", "body": "do you have some (dummy) sample data with which you call this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T12:17:27.137", "Id": "470936", "Score": "0", "body": "Added in the python code part :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T13:08:00.420", "Id": "470945", "Score": "0", "body": "The cython code as is will not work for me. There are some imports and typedefs missing. Can you include thos?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T13:14:14.620", "Id": "470946", "Score": "0", "body": "In your docstring you mention `P >K`, but in your example `P == K` and is every time series represented at least once? or better, is there a 1 in each row of `corr_matrix`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T14:44:39.667", "Id": "470952", "Score": "0", "body": "Added type definitions, and imports. I hope I didn't miss anything. The objective of the function is to find among `P` times series those that are more correlated with `K`. That is way only `K` are returned. In the ideal case, would be at least one 1 for each row, but can happen that two series in `permuted` are more similar to only one in `true`, that's prevented by tracking them using `used_comps`." } ]
[ { "body": "<h1>Pythonic</h1>\n\n<p>I rewrote a few of the loops to prevent looping over the index. I also changed <code>used_comps</code> to a <code>set</code> which has <code>O(1)</code> containment checks. For smaller arrays this will not matter a lot, for larger ones this can make a difference.</p>\n\n<p>I also moved the <code>permutation_dict</code> and <code>used_comps</code> definitions closer to the place they are used.</p>\n\n<pre><code>def find_permutation2(true, permuted):\n \"\"\"\n Finds the most probable permutation of true time series in between permuted time series\n :param true: true ordered time series of shape T times X\n :param permuted: Permuted time series of shape P times T. P &gt; K\n :return: A dict containing {true idx: permuted idx}\n \"\"\"\n\n corr_matrix = np.zeros((true.shape[1], permuted.shape[0]))\n\n # Find correlations\n for i, column in enumerate(true.T):\n for j, row in enumerate(permuted):\n corr_matrix[i, j] = np.corrcoef(column, row)[0, 1]\n\n # Find best order\n per_matrix = np.argsort(-np.abs(corr_matrix), axis=1)\n\n permutation_dict = {}\n used_comps = set()\n for i, row in enumerate(per_matrix):\n for j in row:\n if j in used_comps:\n continue\n permutation_dict[i] = j\n used_comps.add(j)\n break\n\n return permutation_dict\n</code></pre>\n\n<h1>numba</h1>\n\n<p>You can use <code>numba</code>, which compiles the python to llvm. I'm no expert, but I got it to work with these settings.</p>\n\n<pre><code>m_jith = numba.jit(find_permutation2, looplift=False, forceobj=True)\nm_jith(true, permuted)\n</code></pre>\n\n<h1><code>np.setdiff1d</code></h1>\n\n<p>You can use <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.setdiff1d.html\" rel=\"nofollow noreferrer\"><code>np.setdiff1d</code></a>. This will be slower for smaller arrays, but might be faster for larger arrays.</p>\n\n<pre><code>def find_permutation3(true, permuted):\n \"\"\"\n Finds the most probable permutation of true time series in between permuted time series\n :param true: true ordered time series of shape T times X\n :param permuted: Permuted time series of shape P times T. P &gt; K\n :return: A dict containing {true idx: permuted idx}\n \"\"\"\n\n corr_matrix = np.zeros((true.shape[1], permuted.shape[0]))\n\n # Find correlations\n for i, column in enumerate(true.T):\n for j, row in enumerate(permuted):\n corr_matrix[i, j] = np.corrcoef(column, row)[0, 1]\n\n # Find best order\n per_matrix = np.argsort(-np.abs(corr_matrix))\n\n permutation_dict = {}\n used_comps = set()\n for i, row in enumerate(per_matrix):\n j = np.setdiff1d(row, used_comps, assume_unique=True)[0]\n permutation_dict[i] = j\n used_comps.add(j)\n\n return permutation_dict\n</code></pre>\n\n<h1>timings</h1>\n\n<p>All these things have very little effect on the speed of the algorithm</p>\n\n<pre><code>%timeit find_permutation(true, permuted)\n</code></pre>\n\n<blockquote>\n<pre><code>950 µs ± 23.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n</code></pre>\n</blockquote>\n\n<pre><code>%timeit find_permutation2(true, permuted)\n</code></pre>\n\n<blockquote>\n<pre><code>978 µs ± 55.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n</code></pre>\n</blockquote>\n\n<pre><code>%timeit find_permutation3(true, permuted)\n</code></pre>\n\n<blockquote>\n<pre><code>1.05 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n</code></pre>\n</blockquote>\n\n<pre><code>%timeit find_permutation_jit(true, permuted)\n</code></pre>\n\n<blockquote>\n<pre><code>1.08 ms ± 139 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n</code></pre>\n</blockquote>\n\n<pre><code>%timeit find_permutation_cython(true, permuted)\n</code></pre>\n\n<blockquote>\n<pre><code>1.06 ms ± 135 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n</code></pre>\n</blockquote>\n\n<p>But this can change with a larger dataset.</p>\n\n<p>This close timing is probably because the python is not the bottleneck, but the <code>numpy</code> operations, most likely the <code>corrcoef</code>, but you'll need to do some profiling to see whether this is true.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T07:21:35.937", "Id": "471029", "Score": "0", "body": "Thanks, that was nice!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T16:04:38.660", "Id": "240107", "ParentId": "240051", "Score": "1" } } ]
{ "AcceptedAnswerId": "240107", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T14:37:19.327", "Id": "240051", "Score": "3", "Tags": [ "python", "combinatorics" ], "Title": "Finding permutations efficiently" }
240051
<p>Here's my code for this' weeks homework I had. The code should take an expression , preferably in prefix notation ( otherwise throws exception ), that evaluate prefix expression. I've given three example in the main function. The expression gets saved in the object at the mText variable type of string and then the function 'evaluate' evaluates the expression. </p> <p>The code works fine as said by my professor, but he highly criticized my poor style of writing.</p> <p>I'm interested in your opinion and what exactly should I be working on in the future ? I'm pretty sure my biggest mistake is writing bunch of code in one line instead of separating it in a several lines.</p> <p>The code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;stdexcept&gt; #include &lt;cctype&gt; #include &lt;sstream&gt; #include &lt;limits&gt; #include &lt;cmath&gt; using namespace std; class Expression{ public: using Value=int; enum TokenType {operand,unaryOp,binaryOp}; struct Token{ TokenType tokentype; char sym; Value val; bool start; TokenType type() const { return tokentype; } char symbol() const { return sym; } Value value() const { return val; } }; Expression(){} Expression(string text); Value evaluate(); string getText() { return mText; } private: static string valid,whites; string mText; size_t processed_size=0; Token mnextToken; Token getToken(); }; Expression::Expression(string text) : mText{text} {} string Expression::valid="+*/-^~0123456789"; string Expression::whites=" \t\v\n"; Expression::Value solve(Expression::Value a, Expression::Value b,char symbol){ long long num1=a,num2=b; switch (symbol){ case '+': return !(abs(num1+num2) &gt; numeric_limits&lt;int&gt;::max()) ? a+b : throw runtime_error("Wrong expression [Two big(or low) numbers generated for the type int]."); case '-': return !(abs(num1-num2) &gt; numeric_limits&lt;int&gt;::max()) ? a-b : throw runtime_error("Wrong expression [Two big(or low) numbers generated for the type int]."); case '*': return !(abs(num1*num2) &gt; numeric_limits&lt;int&gt;::max()) ? a*b : throw runtime_error("Wrong expression [Two big(or low) numbers generated for the type int]."); case '/': return !b ? a/b : throw runtime_error("Wrong expression [dividing with 0]."); case '^': { auto b_th_power_of = [num2] (long long x) mutable { if (!num2) return static_cast&lt;long long&gt;(1); if (num2&lt;0) return static_cast&lt;long long&gt;(0); long long temp=1; while (num2--&gt;0) temp*=x; return temp; }; num2=b_th_power_of(num1); return !(abs(num2) &gt; numeric_limits&lt;int&gt;::max()) ? num2 : throw runtime_error("Wrong expression [Two big(or low) numbers generated for the type int]."); } default: throw runtime_error("Undefined error occured."); //Za svaki slucaj } } Expression::Value Expression::evaluate(){ Token t=getToken(); if (t.type()==unaryOp){ Value a=evaluate(); if (t.start &amp;&amp; mText.find_first_not_of(Expression::whites,processed_size)!=string::npos) throw runtime_error("Wrong expression [Too many characters on the right side]"); return a-(2*a); } else if(t.type() == binaryOp){ Value a=evaluate(); Value b=evaluate(); if (t.start &amp;&amp; mText.find_first_not_of(Expression::whites,processed_size)!=string::npos) throw runtime_error("Wrong expression [Too many characters on the right side]."); return solve(a,b,t.symbol()); } else{ return t.value(); } } Expression::Token Expression::getToken(){ processed_size ? mnextToken.start=false : mnextToken.start=true; if (static_cast&lt;int&gt;(processed_size) &gt; static_cast&lt;int&gt;(mText.length())-1 ) throw runtime_error("Wrong expression [Too many operators on the left side or empty expression]."); // Fali mi u dz while (Expression::whites.find( mText.at(processed_size) ) != string::npos){ ++processed_size; if (processed_size &gt; mText.length()-1) throw runtime_error("Wrong expression [Too many operators on the left side]."); } size_t found=Expression::valid.find(mText[processed_size]); if (found &lt; 5){ mnextToken.sym=mText[processed_size++]; mnextToken.tokentype=binaryOp; } else if (found == 5){ ++processed_size; mnextToken.tokentype=unaryOp; } else if (found &lt; 16 &amp;&amp; found &gt; 5){ if (mnextToken.start) throw runtime_error("Wrong expression [Expression shouldn't start with a number]."); Expression::Value number; stringstream buffer; while (isdigit( mText[processed_size] )){ buffer &lt;&lt; mText[processed_size]; processed_size++; } if ( !(buffer &gt;&gt; number) ) throw runtime_error("Wrong expression [Too large number(s) in the expression]."); mnextToken.val=number; mnextToken.tokentype=operand; } else throw runtime_error("Wrong expression [Invalid symbol inside the expression]."); return mnextToken; } int main() { try{ Expression a1("+ 2 3"); cout &lt;&lt; a1.getText() &lt;&lt; " = " &lt;&lt; a1.evaluate() &lt;&lt; " [Correct result: 5]" &lt;&lt; endl; Expression a2(" * 4 ^ 2++2 3 1 "); cout &lt;&lt; a2.getText() &lt;&lt; " = " &lt;&lt; a2.evaluate() &lt;&lt; " [Correct result: 256]" &lt;&lt; endl; Expression a3("-+*2 3 *5 4 9"); cout &lt;&lt; a3.getText() &lt;&lt; " = " &lt;&lt; a3.evaluate() &lt;&lt; " [Correct result: 17]" &lt;&lt; endl; } catch (const exception&amp; ex){ cout &lt;&lt; "Exception: " &lt;&lt; ex.what() &lt;&lt; endl; } return 0; } </code></pre> <p>Just to mention that I was supposed to work with runtime_error exception as that was the part of the homework.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T16:41:29.990", "Id": "470827", "Score": "2", "body": "Welcome to code review, the title does not indicate what the code does, and neither does the text below the title. This makes the question off-topic for code review and it can be closed. If this is a calculator then please explain that in the title and in the block of text below that. Your concerns about the code should be in the block of text after the title. Someone has already voted to close this question without leaving a comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T16:42:21.017", "Id": "470828", "Score": "0", "body": "@pacmaninbw The text below indicates what the code is about. It is evaluating prefix expressions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T16:43:28.817", "Id": "470829", "Score": "0", "body": "@pacmaninbw The question is mainly about the style of coding, so any further details about what the code does would be irrelevant imho." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T16:47:05.107", "Id": "470831", "Score": "1", "body": "Please take the tour at https://codereview.stackexchange.com/tour and read about how to ask a good question at https://codereview.stackexchange.com/help/how-to-ask. Our guidelines are not the same as stack overflow. Please realize that I am trying to help you make the question better so that it doesn't get closed by the members of the code review community." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T17:05:57.603", "Id": "470836", "Score": "0", "body": "Your proffessor probably does not like the wide lines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T18:01:08.307", "Id": "470838", "Score": "0", "body": "@slepic Yeah I guess. Is that generally a bad way of writing codes or it depends on the individual ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T19:56:54.023", "Id": "470855", "Score": "4", "body": "\"so any further details about what the code does would be irrelevant imho\" On Code Review? Where we review the actual code as you post it? I really want to say this in a friendly manner, but, that doesn't make much sense to us. Next time, please read our [help/on-topic] and [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915). Code Review does things a bit different." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T20:58:22.763", "Id": "470868", "Score": "1", "body": "`I guess [somebody does not like wide lines] Is that generally a bad way of writing` Try to visualise a newspaper. Competent presentation of information is making it easy to grasp. Competent presentation of text is making it easy to read. If darting back from the end of any given line the eye doesn't \"automatically\" continue with the next line, the line has been too long." } ]
[ { "body": "<p>Your professor is correct. This is really hard to read, and is structured somewhat oddly.</p>\n\n<p>Here is an assortment of comments, left mostly in the order from top to bottom as I found them.</p>\n\n<ol>\n<li>Don't <code>using namespace std;</code>. This has been discussed at length on this site and elsewhere, so I'm not going to leave any additional context here.</li>\n<li><code>Expression::Value</code> is a bit weird; if this is important you should make <code>Expression&lt;T&gt;</code>. The name <code>ValueType</code> is probably better too.</li>\n<li>You should take strings by reference when they're parameters.</li>\n<li>Your list of whitespace seems incomplete</li>\n<li>I don't love declaring multiple variables per line</li>\n<li>The general idea <code>!(abs(expr) &gt; numeric_limits&lt;int&gt;::max()) ? expr : throw runtime_error</code> should be encapsulated in a helper function, and not done in a ternary expression</li>\n<li>I don't see a good reason why exponentiation needs an anonymous function</li>\n<li>All your magic numbers (I think they're string indices?) should be well named constants so it can be understood</li>\n<li>A few of your while loops could probably be for loops</li>\n<li>It might be nice to implement <code>operator&lt;&lt;</code> </li>\n<li>Most of your member functions should be <code>const</code></li>\n<li>The getter methods on <code>Token</code> are pointless and should be removed</li>\n<li><code>Token</code> and <code>TokenType</code> don't seem like they should be public.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T18:53:27.883", "Id": "470841", "Score": "0", "body": "I agree with you about declaring declaring multiple variables in a single declaration and several other points." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T18:32:30.290", "Id": "240067", "ParentId": "240063", "Score": "4" } }, { "body": "<h2>The Good</h2>\n<p>In the class Expression you put the public interfaces first and then the private variables even though when C++ defaults the section immediately following <code>class CLASSNAME {</code> to private. This is very helpful for programmers that may have to maintain your code and can be considered a best practice.</p>\n<p>You use an enum to indicate the token type.</p>\n<h2>Avoid <code>using namespace std;</code></h2>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>, std::string). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code>&lt;&lt;</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n<h2>Symbolic Constants</h2>\n<p>You have 2 static variables <code>static string valid,whites;</code> in the class <code>Expression</code>, it might be better to create these as <code>const</code> and initialize them in the class rather than initializing them almost as globals.</p>\n<pre><code>class Expression{\n ...\nprivate:\n const std::string valid = &quot;+*/-^~0123456789&quot;;\n const std::string whites = &quot; \\t\\v\\n&quot;;\n ...\n};\n</code></pre>\n<p>There are Magic Numbers in the <code>Expression::Token Expression::getToken()</code> function (5), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintainence easier.</p>\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n<h2>Horizontal and Vertical Spacing</h2>\n<p>It is common to put spaces between operands and operators in expressions. This makes the code more readable and easier to maintain by yourself or others.</p>\n<pre><code> while (num2-- &gt; 0)\n</code></pre>\n<p>This includes the <code>comma</code> operator in function definitions and function calls.</p>\n<pre><code>Expression::Value solve(Expression::Value a, Expression::Value b, char symbol){\n</code></pre>\n<p>As @slepic noted, long lines may make the code less readable.</p>\n<p>Here is a more readable version of the function <code>solve()</code>:</p>\n<pre><code>Expression::Value solve(Expression::Value a, Expression::Value b, char symbol){\n long long num1=a,num2=b;\n switch (symbol){\n case '+':\n return !(abs(num1+num2) &gt; std::numeric_limits&lt;int&gt;::max()) ?\n a + b :\n throw std::runtime_error(&quot;Wrong expression [Two big(or low) numbers generated for the type int].&quot;);\n\n case '-':\n return !(abs(num1-num2) &gt; std::numeric_limits&lt;int&gt;::max()) ?\n a - b :\n throw std::runtime_error(&quot;Wrong expression [Two big(or low) numbers generated for the type int].&quot;);\n\n case '*':\n return !(abs(num1*num2) &gt; std::numeric_limits&lt;int&gt;::max()) ?\n a * b :\n throw std::runtime_error(&quot;Wrong expression [Two big(or low) numbers generated for the type int].&quot;);\n\n case '/':\n return !b ?\n a / b :\n throw std::runtime_error(&quot;Wrong expression [dividing with 0].&quot;);\n\n case '^':\n {\n auto b_th_power_of = [num2] (long long x) mutable\n {\n if (!num2) return static_cast&lt;long long&gt;(1);\n if (num2 &lt; 0) return static_cast&lt;long long&gt;(0); long long temp=1;\n while (num2-- &gt; 0)\n {\n temp *= x;\n }\n return temp;\n };\n num2 = b_th_power_of(num1);\n return !(abs(num2) &gt; std::numeric_limits&lt;int&gt;::max()) ?\n num2 :\n throw std::runtime_error(&quot;Wrong expression [Two big(or low) numbers generated for the type int].&quot;);\n }\n default: throw std::runtime_error(&quot;Undefined error occured.&quot;); //Za svaki slucaj\n }\n}\n</code></pre>\n<p>*Note: It is common to put the opening brace <code>{</code> of a function on the next line so that it lines up with the closing brace <code>}</code>. This makes it easier to read and follow the logic. *</p>\n<h2>Testing the Code</h2>\n<p>A good practice in testing is to include failures to make sure the failure handling code executes as well as the other code. Has the exception handling been tested?</p>\n<h2>Separate Classes From Other Code</h2>\n<p>If this was a more complicated problem with multiple classes this would be more noticeable, but classes should be define in other files from main. Amoung other things this allows the classes to be reused. The class <code>Expression</code> should have a header file <code>Expression.h</code> and an implementation file <code>Expression.cpp</code>. Most modern editors will do this for you if you indicate you want to create a new class. This also decreases the amount of code in any single file, and allows classes to be mainted separately from other code. As long as the class header file is not touched, bugs can be fixed in the class implementation file. This also reduces the number of include files any single implementation file needs to include (improves build times).</p>\n<h2>Extend Ability</h2>\n<p>The function <code>Expression::Value Expression::evaluate()</code> is not as extendable as it could be, the <code>if then else if</code> logic could be replaced by a <code>switch / case</code> statement. This would allow the <code>TokenType</code> enum to be extended if necessary. An alternate implementation would be to use <code>std::map</code> and a function for each `TokenType. The map would be identified by the enum and then execute the function.</p>\n<pre><code>Expression::Value Expression::evaluate(){\n Token t=getToken();\n switch (t.type())\n {\n case unaryOp:\n {\n Value a=evaluate();\n if (t.start &amp;&amp; mText.find_first_not_of(whites, processed_size) != std::string::npos)\n {\n throw std::runtime_error(&quot;Wrong expression [Too many characters on the right side]&quot;);\n }\n return a - (2 * a);\n }\n case binaryOp :\n {\n Value a=evaluate();\n Value b=evaluate();\n if (t.start &amp;&amp; mText.find_first_not_of(whites, processed_size) != std::string::npos)\n {\n throw std::runtime_error(&quot;Wrong expression [Too many characters on the right side].&quot;);\n }\n return solve(a,b, t.symbol());\n }\n case operand :\n return t.value();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T18:48:08.613", "Id": "240068", "ParentId": "240063", "Score": "4" } } ]
{ "AcceptedAnswerId": "240068", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T16:26:21.913", "Id": "240063", "Score": "2", "Tags": [ "c++", "beginner", "homework" ], "Title": "Prefix expression evaluator [C++]" }
240063
<p>Legend says phones used to have keys<sup><a href="https://xkcd.com/285/" rel="nofollow noreferrer">citation needed</a></sup> and in those times, a person could "encode" a phone number by creating a word from the letters in the keys with the given numbers.</p> <p>Below is the usual layout of the keys (that matter for my question) of a phone:</p> <pre><code> | abc | def | 1 | 2 | 3 | ------------------ ghi | jkl | mno | 4 | 5 | 6 | ------------------ pqrs | tuv | wxyz| 7 | 8 | 9 | ------------------ </code></pre> <p>I have to write a function that, given a vector of characters with uppercase letters/digits, recovers the original phone number.</p> <p>For example,</p> <pre><code>'HELLO' -&gt; 4 3 5 5 6 'IAMYY4U' -&gt; 4 2 6 9 9 4 8 '' -&gt; ⍬ </code></pre> <p>This is the code I have written:</p> <pre><code>Telephone ← { ⍝ Monadic function taking an uppercase string as input. ⍝ Decodes the number expressed with uppercase letters, ⍝ e.g. '1ABCZ' gives '12229' ⍝ Split letters and digits according to their keys (each digit goes to itself) keyStarts ← 'ADGJMPTW' splits ← ⎕D, keyStarts classes ← (1 -⍨ ⍳10), 1 + ⍳8 classes[splits ⍸ ⍵] } </code></pre> <p>I am particularly interested in a better way to create the <code>classes</code> variable, that looks like this <code>0 1 2 3 4 5 6 7 8 9 2 3 4 5 6 7 8 9</code> and this ordering depends obviously on the order of <code>splits</code>.</p> <p>This comes from <a href="https://www.dyalogaplcompetition.com/?goto=P16" rel="nofollow noreferrer">a problem from an APL competition</a>.</p>
[]
[ { "body": "<blockquote>\n <p>I am particularly interested in a better way to create the <code>classes</code> variable, [...] this ordering depends obviously on the order of <code>splits</code>.</p>\n</blockquote>\n\n<p>Because ASCII codes of <code>A..Z</code> come later than those of <code>0..9</code>, we can't shorten the <code>classes</code> array itself. Instead, we can <em>lengthen</em> it, so that <code>classes</code> becomes simply two copies of <code>0..9</code>. You can create unused intervals by copying the boundary item that comes <em>after</em> them:</p>\n\n<pre><code> 'BBB' ⍸ 'ABCD'\n0 3 3 3\n</code></pre>\n\n<p>Incorporating it in <code>Telephone</code>:</p>\n\n<pre><code> splits ← ⎕D, 'AAADGJMPTW'\n classes ← ,⍨ 1 -⍨ ⍳10\n</code></pre>\n\n<hr>\n\n<p><strong>Nitpicking:</strong> When I need to subtract 1 from an expression, I use <code>¯1+expr</code> instead of <code>1-⍨expr</code> because the former reads better to me. This is a personal choice though. Or, if the \"subtract 1\" appears only for generating <code>0..n-1</code> instead of <code>1..n</code> with <code>⍳</code>, consider using <code>⎕IO←0</code>.</p>\n\n<hr>\n\n<p>Now, <code>splits</code> is creating the interval indices <code>0..20</code>, and except the first 0, each index is mapped to <code>0..9,0..9</code>.</p>\n\n<pre><code>interval index: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\nclass : 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9\n</code></pre>\n\n<p>Do you see the pattern? If you discard the unused interval and take modulo 10, you get the right class! Then you can entirely discard the variable <code>classes</code> and extra indexing:</p>\n\n<pre><code>Telephone ← {\n splits ← 1↓ ⎕D, 'AAADGJMPTW'\n 10| splits ⍸ ⍵\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:41:10.153", "Id": "471514", "Score": "0", "body": "I like your \"nitpicking\" here about the `¯1 + ...`. I have adopted it in my code already. Also, really nice simplification of the code with the extended `splits`, thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T23:44:20.227", "Id": "240075", "ParentId": "240065", "Score": "3" } } ]
{ "AcceptedAnswerId": "240075", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T18:05:01.957", "Id": "240065", "Score": "2", "Tags": [ "apl" ], "Title": "Decoding a telephone number that was masked with letters from the respective keys with APL" }
240065
<p>Below is my permutation function and I'm looking to make it more elegant and efficient if possible.</p> <p>The function should return a string which includes all the permutations of the given string (separated by comma).</p> <pre><code>private static String permutation(String prefix, String str) { int n = str.length(); String toReturn = ""; if (n == 0) { return prefix + ","; } else { for (int i = 0; i &lt; n; i++) { toReturn += permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n)); } } return toReturn; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T19:05:52.830", "Id": "470843", "Score": "3", "body": "What are the restrictions on the input? Can it contain duplicate letters? `\"BEE\"` would produce `\"EEB\"` (last E first), and `\"EEB\"` (first E first), which are normally not both counted as valid permutations. Can you input string contain a comma? What is the driving function, which takes only 1 input string, instead of a string & a prefix?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T11:35:40.507", "Id": "470921", "Score": "0", "body": "I have another function which clears the input but there can be duplicate characters and commas are added to seperate each permutations in the return string. But currently an extra comma is always added, which is an issue." } ]
[ { "body": "<p>I think you should divide this problem to 3:</p>\n\n<ol>\n<li>Create a list of all permutations</li>\n<li>Add the prefix to each item in the list</li>\n<li>Convert the list to comma separated string</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T18:42:44.583", "Id": "240297", "ParentId": "240066", "Score": "2" } } ]
{ "AcceptedAnswerId": "240297", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T18:12:19.417", "Id": "240066", "Score": "2", "Tags": [ "java", "strings" ], "Title": "String Permutation" }
240066
<p>This is my first proper Go program, after completing <a href="https://gobyexample.com/" rel="nofollow noreferrer">Go by Example</a> and <a href="https://tour.golang.org" rel="nofollow noreferrer">https://tour.golang.org</a>. I have a background in Python.</p> <p>This program scrapes definitions from <a href="https://www.wordnik.com" rel="nofollow noreferrer">Wordnik</a>, then prints them nicely in the commandline. It's made for looking up a word quickly in the commandline.</p> <p>I'm hoping that someone can review this code and make suggestions on inefficiencies, but especially on any parts of the code that are not idiomatic, that aren't good examples of Go code. To highlight one part, at the end of the code I use a slice of channels to keep track of multiple workers. I would be happy to hear opinions on that approach.</p> <pre class="lang-golang prettyprint-override"><code>package main import ( "errors" "fmt" "github.com/PuerkitoBio/goquery" "gopkg.in/gookit/color.v1" "net/http" "os" "sort" "strings" "text/tabwriter" ) // definition is a struct for storing simple word definitions. type definition struct { wordType string // noun, verb, interjection, intransitive verb, etc text string // The actual definition itself } // ctxDefinition includes additional info about a definition. type ctxDefinition struct { dict string // The dictionary the definition comes from rank uint8 // Where this definition is compared to the others def definition } // byDictionary sorts ctxDefintions by rank and dictionary. // Returns a map with dictionary names as keys, and definition slices as values func byDictionary(cDs []ctxDefinition) map[string][]definition { pre := make(map[string][]ctxDefinition) // Used for ranking, not returned // Add all the defintions to the map for _, cD := range cDs { pre[cD.dict] = append(pre[cD.dict], cD) } // Sort by rank for k := range pre { sort.Slice(pre[k], func(i, j int) bool { return pre[k][i].rank &lt; pre[k][j].rank }) } // Convert to hold definitions only, not context m := make(map[string][]definition) for dict, cDs := range pre { for _, cD := range cDs { m[dict] = append(m[dict], cD.def) } } return m } // render returns a formatted definition, optionally with color. // This contains some opinionted color defaults, as opposed to renderOps func (d *definition) render(c bool) string { if c { return color.New(color.OpItalic).Render(d.wordType) + "\t" + d.text } return d.wordType + "\t" + d.text } // renderOps returns a formatted color definition, according to the provided styles. func (d *definition) renderOps(wordType, text color.Style) string { return wordType.Render(d.wordType) + "\t\t" + text.Render(d.text) } // pprintCtxDefs pretty prints multiple context definitions, optionally with color. func pprintCtxDefs(cDs []ctxDefinition, c bool) { m := byDictionary(cDs) w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) //esc := string(tabwriter.Escape) for dict, defs := range m { if c { // Bracket dict name with escape characters so it's not part of the tabbing fmt.Fprintln(w, color.New(color.BgGray).Render(dict)) // Print first definition differently fmt.Fprintf(w, "%s\n", defs[0].renderOps(color.New(color.OpItalic, color.OpBold), color.New(color.Cyan))) for _, def := range defs[1:] { fmt.Fprintf(w, "%s\n", def.render(true)) } } else { fmt.Fprintf(w, dict+"\n") for _, def := range defs { fmt.Fprintf(w, "%s\n", def.render(false)) } } fmt.Fprintln(w) } w.Flush() } // wordnikLookup returns a slice of ctxDefinitions for the provided word. // Looks up words using wordnik.com func wordnikLookup(w string, client *http.Client) ([]ctxDefinition, error) { req, err := http.NewRequest("GET", "https://www.wordnik.com/words/"+w, nil) if err != nil { panic(err) } req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36") resp, err := client.Do(req) if err != nil { return nil, errors.New("couldn't connect to wordnik") } defer resp.Body.Close() if resp.StatusCode != 200 { return nil, errors.New("200 not returned, likely a non-word like '../test' was passed") } doc, err := goquery.NewDocumentFromReader(resp.Body) if err != nil { return nil, errors.New("malformed HTML from wordnik") } ret := make([]ctxDefinition, 0) s := doc.Find(".word-module.module-definitions#define .guts.active").First() dicts := s.Find("h3") lists := s.Find("ul") // Go through each list of defs., then each def., and add them lists.Each(func(i int, list *goquery.Selection) { list.Find("li").Each(func(j int, def *goquery.Selection) { // wordType wT := def.Find("abbr").First().Text() + " " + def.Find("i").First().Text() wT = strings.TrimSpace(wT) // dictionary d := dicts.Get(i).FirstChild.Data[5:] // strip the "from " prefix d = strings.ToUpper(string(d[0])) + string(d[1:]) // Capitalize first letter if string(d[len(d)-1]) == "." { // Remove ending period d = string(d[:len(d)-1]) } // definition text - remove the wordType at the beginning of the definition t := strings.TrimSpace(def.Text()[len(wT):]) t = strings.ToUpper(string(t[0])) + string(t[1:]) // Capitalize first letter ret = append(ret, ctxDefinition{ dict: d, rank: uint8(j), def: definition{ wordType: wT, text: t, }, }) }) }) return ret, nil } func main() { if len(os.Args) &lt;= 1 { fmt.Println("Provide a word to lookup.") return } // TODO: Support multiple words concurrently client := &amp;http.Client{} words := os.Args[1:] // Lookup each word concurrently and store results results := make([]chan []ctxDefinition, 0) for i, word := range words { results = append(results, make(chan []ctxDefinition)) go func(ind int, w string) { defs, err := wordnikLookup(w, client) if err != nil { panic(err) } results[ind] &lt;- defs }(i, word) } // Print the answer of each word for i, result := range results { // TODO: Write to buffer, then flush after result comes in color.New(color.BgRed, color.White).Println(words[i]) pprintCtxDefs(&lt;-result, true) } } </code></pre> <p>This code is licensed under the <a href="https://www.gnu.org/licenses/gpl-3.0.en.html" rel="nofollow noreferrer">GPL version 3</a>. It will be uploaded to Github. Anyone who wants to reuse or modify this code must adhere to that license.</p>
[]
[ { "body": "<p>the two loops of the main function are problematic. </p>\n\n<p>It is uselessly complicated to use indices over the two slices assuming they are same length etc. </p>\n\n<p>The first loop is unbounded, meaning that if i pass a large amount of words it will start that many routines, requests and so on. Which will definitely creates troubles for some users.</p>\n\n<p>Also, the second loop is sub-optimal because it does not wait for the fastest result to begin output the results, it wait for the fist item of its slice. Which means that if the first request is, for whatever reason, slow, all other results that could come faster will not appear until that first item finished. This is definitely undesired behavior in concurrent programming.</p>\n\n<p>The rest of the code is okish, I have not dug it that much.</p>\n\n<p>Here is an updated version of your main function with a more idiomatic way to transport the data (input word, output results including possible error) in and out the routines with more casual synchronizations mechanisms. It also limit the number of concurrent requests to 4, for the purposes of demonstration.</p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>package main\n\nimport (\n \"errors\"\n \"fmt\"\n \"net/http\"\n \"os\"\n \"sort\"\n \"strings\"\n \"sync\"\n \"text/tabwriter\"\n\n \"github.com/PuerkitoBio/goquery\"\n \"github.com/gookit/color\"\n)\n\n// definition is a struct for storing simple word definitions.\ntype definition struct {\n wordType string // noun, verb, interjection, intransitive verb, etc\n text string // The actual definition itself\n}\n\n// ctxDefinition includes additional info about a definition.\ntype ctxDefinition struct {\n dict string // The dictionary the definition comes from\n rank uint8 // Where this definition is compared to the others\n def definition\n}\n\n// byDictionary sorts ctxDefintions by rank and dictionary.\n// Returns a map with dictionary names as keys, and definition slices as values\nfunc byDictionary(cDs []ctxDefinition) map[string][]definition {\n pre := make(map[string][]ctxDefinition) // Used for ranking, not returned\n // Add all the defintions to the map\n for _, cD := range cDs {\n pre[cD.dict] = append(pre[cD.dict], cD)\n }\n // Sort by rank\n for k := range pre {\n sort.Slice(pre[k], func(i, j int) bool {\n return pre[k][i].rank &lt; pre[k][j].rank\n })\n }\n // Convert to hold definitions only, not context\n m := make(map[string][]definition)\n for dict, cDs := range pre {\n for _, cD := range cDs {\n m[dict] = append(m[dict], cD.def)\n }\n }\n return m\n}\n\n// render returns a formatted definition, optionally with color.\n// This contains some opinionted color defaults, as opposed to renderOps\nfunc (d *definition) render(c bool) string {\n if c {\n return color.New(color.OpItalic).Render(d.wordType) + \"\\t\" + d.text\n }\n return d.wordType + \"\\t\" + d.text\n}\n\n// renderOps returns a formatted color definition, according to the provided styles.\nfunc (d *definition) renderOps(wordType, text color.Style) string {\n return wordType.Render(d.wordType) + \"\\t\\t\" + text.Render(d.text)\n}\n\n// pprintCtxDefs pretty prints multiple context definitions, optionally with color.\nfunc pprintCtxDefs(cDs []ctxDefinition, c bool) {\n m := byDictionary(cDs)\n w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n //esc := string(tabwriter.Escape)\n for dict, defs := range m {\n if c {\n // Bracket dict name with escape characters so it's not part of the tabbing\n fmt.Fprintln(w, color.New(color.BgGray).Render(dict))\n // Print first definition differently\n fmt.Fprintf(w, \"%s\\n\", defs[0].renderOps(color.New(color.OpItalic, color.OpBold), color.New(color.Cyan)))\n for _, def := range defs[1:] {\n fmt.Fprintf(w, \"%s\\n\", def.render(true))\n }\n } else {\n fmt.Fprintf(w, dict+\"\\n\")\n for _, def := range defs {\n fmt.Fprintf(w, \"%s\\n\", def.render(false))\n }\n }\n fmt.Fprintln(w)\n }\n w.Flush()\n}\n\n// wordnikLookup returns a slice of ctxDefinitions for the provided word.\n// Looks up words using wordnik.com\nfunc wordnikLookup(w string, client *http.Client) ([]ctxDefinition, error) {\n req, err := http.NewRequest(\"GET\", \"https://www.wordnik.com/words/\"+w, nil)\n if err != nil {\n return nil, errors.New(\"couldn't connect to wordnik\")\n }\n req.Header.Set(\"User-Agent\", \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\")\n resp, err := client.Do(req)\n if err != nil {\n return nil, errors.New(\"couldn't connect to wordnik\")\n }\n defer resp.Body.Close()\n if resp.StatusCode != 200 {\n return nil, errors.New(\"200 not returned, likely a non-word like '../test' was passed\")\n }\n doc, err := goquery.NewDocumentFromReader(resp.Body)\n if err != nil {\n return nil, errors.New(\"malformed HTML from wordnik\")\n }\n ret := make([]ctxDefinition, 0)\n s := doc.Find(\".word-module.module-definitions#define .guts.active\").First()\n dicts := s.Find(\"h3\")\n lists := s.Find(\"ul\")\n // Go through each list of defs., then each def., and add them\n lists.Each(func(i int, list *goquery.Selection) {\n list.Find(\"li\").Each(func(j int, def *goquery.Selection) {\n // wordType\n wT := def.Find(\"abbr\").First().Text() + \" \" + def.Find(\"i\").First().Text()\n wT = strings.TrimSpace(wT)\n // dictionary\n d := dicts.Get(i).FirstChild.Data[5:] // strip the \"from \" prefix\n d = strings.ToUpper(string(d[0])) + string(d[1:]) // Capitalize first letter\n if string(d[len(d)-1]) == \".\" { // Remove ending period\n d = string(d[:len(d)-1])\n }\n // definition text - remove the wordType at the beginning of the definition\n t := strings.TrimSpace(def.Text()[len(wT):])\n t = strings.ToUpper(string(t[0])) + string(t[1:]) // Capitalize first letter\n ret = append(ret, ctxDefinition{\n dict: d,\n rank: uint8(j),\n def: definition{\n wordType: wT,\n text: t,\n },\n })\n })\n })\n return ret, nil\n\n}\n\ntype scrapRes struct {\n word string\n defs []ctxDefinition\n err error\n}\n\nfunc scrapWordnik(client *http.Client, input chan string, output chan scrapRes) {\n for w := range input {\n defs, err := wordnikLookup(w, client)\n output &lt;- scrapRes{\n word: w,\n defs: defs,\n err: err,\n }\n }\n}\n\nfunc main() {\n if len(os.Args) &lt;= 1 {\n fmt.Println(\"Provide a word to lookup.\")\n return\n }\n\n words := os.Args[1:]\n\n // TODO: Support multiple words concurrently\n client := http.DefaultClient // prefer default http client if you are not configuring it.\n\n // prepare async communication pipes\n input := make(chan string)\n output := make(chan scrapRes)\n\n // start async workers\n var wg sync.WaitGroup\n for i := 0; i &lt; 4; i++ {\n wg.Add(1)\n go func() {\n defer wg.Done()\n scrapWordnik(client, input, output)\n }()\n }\n go func() {\n wg.Wait()\n close(output)\n }()\n\n //feed input communication pipe\n for _, word := range words {\n input &lt;- word\n }\n close(input)\n\n //read output to get results\n for r := range output {\n color.New(color.BgRed, color.White).Println(r.word)\n pprintCtxDefs(r.defs, true)\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T17:22:49.950", "Id": "470969", "Score": "0", "body": "Thanks for the review! I will fix the unbounded first loop. However, the behaviour of the second loop is on purpose, as I want the definitions to come back out in the same order, even if the first one is slow like you said. I will look into improving it with channels like you demonstrated though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T20:44:25.427", "Id": "470992", "Score": "0", "body": "in that case you might attach an output chan to the scrapRes type def. Keep track of all scrapRes instances, iterate them in order and query their output channel. As you know you are reading only once on each channels, it is not necessary to close them. I believe the waitgroup would be useless in that version." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T12:03:59.113", "Id": "240096", "ParentId": "240071", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T19:13:33.193", "Id": "240071", "Score": "3", "Tags": [ "console", "web-scraping", "go", "concurrency" ], "Title": "Command line dictionary tool, using webscraping" }
240071
<p>I'm creating a trip calculator that has some basic arithmetic and I'm just not grasping how to handle calculations. I feel like I'm doing a bunch of stuff wrong here. What initial values should I have in state? Am I putting too much in state? Is state saving these as numbers or strings? I included some commented out code that was using more vanilla JavaScript in the render but I that was causing problems with state of course and I'm not sure where functions like my <code>mealCalculator</code>, <code>vanTotal</code>, <code>truckTotal</code> and such would even live in the React component. Do I really need to duplicate so much stuff in the <code>onChange</code> methods? I'm not even sure where to start. I just want to have three input elements that I can change values and it present all the math on the fly as these variables change. </p> <pre><code> import React from "react"; class TripCalc extends React.Component { constructor(props) { super(props); this.state = { totalMiles: 33, hotelCost: 125, hotelDays: 0, hotelTotal: 125, drivingDays: 0.553, drivers: 1, hotelNights: 0, hours: 0, meals: 0, hourlyFee: 20, laborCost: 0, vanMPG: 16, fuelCost: 1, dieselCost: 2, vanFuelCost: 0, truckMPG: 10, truckRoadside: 5.99, truckDailyFee: 7, truckMileFee: .17, truckFuel: 0, roadsideDailyCharge: 0, enterpriseDailyCharge: 0, truckTotal: 0, vanTotal: 0, vanFuelCost: 0 }; this.onTotalMileChange.bind(this); this.onDriversChange.bind(this); this.onHotelCostChange.bind(this); } onTotalMileChange = (event) =&gt; { this.setState({totalMiles: parseInt(event.target.value)}) this.setState({drivingDays: this.state.totalMiles / 600}) this.setState({hotelNights: Math.floor(this.state.drivingDays)}) this.setState({hotelTotal: event.target.value * this.state.hotelDays}) this.setState({hours: Math.round(this.state.totalMiles /75)}) this.setState({meals: mealCalculator(this.state.hours)}) this.setState({laborCost: (this.state.hours * wages) * this.state.drivers}) this.setState({vanFuelCost: (this.setState.totalMiles / vanMPG) * fuelCost}) console.log(this.state) } onDriversChange = (event) =&gt; { this.setState({drivers: parseInt(event.target.value)}) this.setState({drivingDays: totalMiles / 600}) this.setState({hotelNights: Math.floor(this.state.drivingDays)}) this.setState({hotelTotal: event.target.value * this.state.hotelDays}) this.setState({hours: Math.round(this.state.totalMiles /75)}) this.setState({meals: mealCalculator(this.state.hours)}) this.setState({laborCost: (this.state.hours * wages) * this.state.drivers}) this.setState({vanFuelCost: (this.setState.totalMiles / vanMPG) * fuelCost}) console.log(this.state) } onHotelCostChange = (event) =&gt; { this.setState({hotelCost: parseInt(event.target.value)}) this.setState({drivingDays: totalMiles / 600}) this.setState({hotelNights: Math.floor(this.state.drivingDays)}) this.setState({hotelTotal: event.target.value * this.state.hotelDays}) this.setState({hours: Math.round(this.state.totalMiles /75)}) this.setState({meals: mealCalculator(this.state.hours)}) this.setState({laborCost: (this.state.hours * wages) * this.state.drivers}) this.setState({vanFuelCost: (this.setState.totalMiles / vanMPG) * fuelCost}) console.log(this.state); } render(){ // var hotelNights = Math.floor(this.state.drivingDays); // var hours = Math.round(this.state.totalMiles /75); // if(hours &gt;= 4){ // var meals = (Math.floor((hours / 4)) * 10) * this.state.drivers} // else{ // var meals = 0; // }; // //stops calculator to factor into hours // var laborCost = (hours * 20) * this.state.drivers; // var vanMPG = 16; // var fuelCost = 2; // var vanFuelCost = (this.state.totalMiles / vanMPG) * fuelCost; // var truckRoadside = 5.99; // var truckDailyFee = 7; // var truckMileFee = parseFloat(.17); // var dieselCost = 2; // var truckMPG = 10; // var truckByTheMile = ((this.state.totalMiles + 28) * .17); // var truckFuel = (((this.state.totalMiles + 28) / truckMPG)* dieselCost); // var roadsideDailyCharge = (Math.floor(this.state.drivingDays) * truckRoadside); // var enterpriseDailyCharge = ((Math.floor(this.state.drivingDays) * truckDailyFee)); // var truckTotal = truckByTheMile + truckFuel + roadsideDailyCharge + enterpriseDailyCharge; // console.log("truckbythemile = " + this.state.totalMiles + "roadsidedailycharge =" + roadsideDailyCharge + " enterprisedailycharge = " + enterpriseDailyCharge + " truck total = " + truckTotal); // pad truck trip miles by round trip total for picking up and returning truck return ( &lt;div&gt; &lt;form&gt; Total Miles of Trip &lt;input type="number" name="totalMiles" defaultValue="33" onChange={this.onTotalMileChange}/&gt; &lt;br/&gt; Total Drivers &lt;input type="number" name="drivers" defaultValue="1" onChange={this.onDriversChange} /&gt; &lt;br/&gt; Driving days &lt;p&gt;{this.state.drivingDays}&lt;/p&gt; &lt;br/&gt; Hotel cost &lt;input type="number" name="hotelCost" defaultValue="125" onChange={this.onHotelCostChange}/&gt; &lt;br/&gt; Nights in Hotel &lt;p&gt;{}&lt;/p&gt; &lt;br/&gt; Meals {mealCalculator(this.state.hours)} &lt;br/&gt; hours {} &lt;br/&gt; Labor cost {} &lt;br/&gt; Van Fuel cost {} &lt;br/&gt; Van Trip Total &lt;p&gt; ${} &lt;/p&gt; Truck Trip Total {/* add radio button for 2 day and 1 day truck return period */} &lt;p&gt; ${} &lt;/p&gt; &lt;/form&gt; &lt;/div&gt; ) } } export default TripCalc; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T05:34:39.340", "Id": "470890", "Score": "2", "body": "It's not clear whether the current code works the way it should from your description. Please clarify, after reading our [help/on-topic]." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T21:33:00.247", "Id": "240072", "Score": "1", "Tags": [ "react.js" ], "Title": "State and performing calculations in React" }
240072
<p>The game Space Station 13 (on the Paradise Station codebase) contains a DNA mechanic. Every carbon-based lifeform with DNA has 55 "blocks" that can be altered in a DNA Modifier, giving the mob disabilities or superpowers once they reach a certain threshold. </p> <p>DNA blocks are 3-digit base-16 numbers from <code>000</code> to <code>FFF</code>. The activation thresholds are different for each kind of mutation (disabilities and minor powers have lower thresholds), but if a block is set to a value of hexadecimal <code>DAC</code> or above, all of the mutations on that block are guaranteed to be active.</p> <p>Here is an example of the DNA modification process: </p> <ol> <li>A creature enters the DNA modifier.</li> <li>The Geneticist looks at the creature's first DNA block. It is set to <code>357</code>.</li> <li>The Geneticist selects the first digit of the block, <code>3</code>, and irradiates it.</li> <li>The digit <code>3</code> is replaced with the digit <code>9</code>.</li> <li><code>957</code> is below the threshold of <code>DAC</code>. The Geneticist irradiates the first digit again, until it is at least <code>D</code>.</li> <li>If the first digit is above <code>D</code>, the process ends. If it is at <code>D</code>, the geneticist irradiates that block until it is at <code>A</code> or higher. Then, the third block, until it is at <code>C</code> or higher.</li> <li>The process continues to until a value of <code>DAC</code> or above is reached. (If the first irradiation had resulted in <code>E57</code>, that would have ended it early.)</li> </ol> <p>I would like to find out how many attempts, on average, it takes to irradiate a block to <code>DAC</code>. Not every digit can turn into every other digit, and the probability table is not uniform. Fortunately, I have access to the source code of Paradise Station, and thus I can accurately simulate the process.</p> <p>The game is written in a rather clunky language called DreamMaker - I don't really know how to work with it. The function responsible for irradiating a single is called <code>miniscramble</code>, its source code is below: (modified slightly to be more readable, the defines were not originally there)</p> <pre><code>#define HIGH_SCRAMBLE prob((rs*10)) #define MED_SCRAMBLE prob((rs*10)-(rd)) #define LOW_SCRAMBLE prob((rs*5)+(rd))) /proc/miniscramble(input,rs,rd) var/output output = null if(input == "C" || input == "D" || input == "E" || input == "F") output = pick(HIGH_SCRAMBLE;"4",HIGH_SCRAMBLE;"5",HIGH_SCRAMBLE;"6",HIGH_SCRAMBLE;"7",LOW_SCRAMBLE;"0",LOW_SCRAMBLE;"1",MED_SCRAMBLE;"2",MED_SCRAMBLE;"3") if(input == "8" || input == "9" || input == "A" || input == "B") output = pick(HIGH_SCRAMBLE;"4",HIGH_SCRAMBLE;"5",HIGH_SCRAMBLE;"A",HIGH_SCRAMBLE;"B",LOW_SCRAMBLE;"C",LOW_SCRAMBLE;"D",LOW_SCRAMBLE;"2",LOW_SCRAMBLE;"3") if(input == "4" || input == "5" || input == "6" || input == "7") output = pick(HIGH_SCRAMBLE;"4",HIGH_SCRAMBLE;"5",HIGH_SCRAMBLE;"A",HIGH_SCRAMBLE;"B",LOW_SCRAMBLE;"C",LOW_SCRAMBLE;"D",LOW_SCRAMBLE;"2",LOW_SCRAMBLE;"3") if(input == "0" || input == "1" || input == "2" || input == "3") output = pick(HIGH_SCRAMBLE;"8",HIGH_SCRAMBLE;"9",HIGH_SCRAMBLE;"A",HIGH_SCRAMBLE;"B",MED_SCRAMBLE;"C",MED_SCRAMBLE;"D",LOW_SCRAMBLE;"E",LOW_SCRAMBLE;"F") if(!output) output = "5" return output </code></pre> <p>My program simulates trying to get each block from <code>000</code>-<code>800</code> (values above <code>800</code> do not occur in creatures at the start of a round) to at least <code>DAC</code>, by using the strategy outlined above. It is written in Python 3 and outputs a CSV file with two columns: the block being worked on, and how long it takes to get it to DAC, averaging 4096 attempts. The <code>miniscramble_table</code> function is my direct translation of the DreamMaker code above.</p> <pre class="lang-py prettyprint-override"><code>from random import random from functools import reduce import itertools print("This program will calculate how many attempts it takes to get to DAC from every block 000-800, on average.") block_attempts = input("How many attempts should be made per block? (default 4096, more is more accurate)") if not block_attempts: block_attempts = 4096 else: try: block_attempts = int(block_attempts) except ValueError: print("ERR: Could not parse that number. Using 4096.") user_bound = input("What should be the upper bound on the dataset? (default 800, lower is faster but less comprehensive)") if not user_bound: user_bound = '800' else: try: user_bound = [char for char in user_bound] assert(len(user_bound) == 3) except: print("ERR: Could not parse that bound. Using 800.") user_target = input("What should be the target value for a block? (default DAC)") if not user_target: user_target = ['D','A','C'] else: try: user_target = [char for char in user_target] assert(len(user_target) == 3) except: # bad, but like, c'mon print("ERR: Could not parse that bound. Using 800.") # Generate a probability table. This is ugly because it's based off BYOND code. def miniscramble_table(letter, rad_strength, rad_duration): HIGH_SCRAMBLE = rad_strength*10 MED_SCRAMBLE = rad_strength*10 - rad_duration LOW_SCRAMBLE = rad_strength*5 + rad_duration picks = (("5"),(1.0)) # default, I guess. if (letter in ["C", "D", "E", "F"]): picks = ("4", "5", "6", "7", "0", "1", "2", "3") probs = (*[HIGH_SCRAMBLE] * 4, *[LOW_SCRAMBLE] * 2, *[MED_SCRAMBLE] * 2) if (letter in ["8", "9", "A", "B", "4", "5", "6", "7"]): picks = ("4", "5", "A", "B", "C", "D", "2", "3") probs = (*[HIGH_SCRAMBLE] * 4, *[LOW_SCRAMBLE] * 4) if (letter in ["0", "1", "2", "3"]): picks = ("8", "9", "A", "B", "C", "D", "E", "F") probs = (*[HIGH_SCRAMBLE] * 4, *[MED_SCRAMBLE] * 2, *[LOW_SCRAMBLE] * 2) total = sum(probs) probs = map(lambda n: n/total, probs) # sums to 1 # make the output nicer to work with... out = [] prev = 0 for pick, prob in zip(picks, probs): out.append((pick, prob+prev)) prev += prob return out def miniscramble(letter, rad_strength, rad_duration): r = random() table = miniscramble_table(letter, rad_strength, rad_duration) output = filter(lambda entry: entry[1] &gt;= r, table) # print(r) return list(output)[0][0] # tries to get from `initial` to at least `letters` with specified settings # returns # of attempts to get there. def scramble_to(initial=('3','5','7'), target=user_target, settings=(10,2), log=False): current = list(initial) # what are we looking at # letter-iterable to base10 number def concat_letters(letters): return int(reduce(lambda x,y: x+y, letters, ''), 16) for attempts in enumerate(itertools.repeat(0)): if log: print(f'Miniscramble #{attempts[0]}:', ''.join(current)) if concat_letters(current) &gt;= concat_letters(target): if log: print(f'Done with {attempts[0]} miniscrambles!') return attempts[0] # done, since we're above/at the target! for i in range(3): if int(current[i], 16) &lt; int(target[i], 16): current[i] = miniscramble(current[i], *settings) break # 1 `enumerate` per attempt results = {} def unactivated(seq): return int(''.join(seq), 16) &lt; int(user_bound, 16) # blocks never start activated, so default is 800 dataset = filter(unactivated, (seq for seq in itertools.product([_ for _ in '0123456789ABCDEF'], repeat=3))) for block in dataset: # go through a sample set of blocks, 54 in all # Give each block lots of attempts for bigger sample size. default=4096 intermediate = [] for _ in range(block_attempts): intermediate.append(scramble_to(initial=block, target=('D','A','C'), settings=(1,2))) results[block] = (sum(intermediate)/len(intermediate)) # average it out # Convert results to CSV out = [] for k,v in results.items(): out.append(f'{"".join(k)},{v}\n') filename = input('\nDone. Where should the results be saved? (leave blank to not save) ') if filename: with open(filename, 'w') as outfile: [outfile.write(line) for line in out] else: print("Not saving.") </code></pre> <p>I made this plot of the results using Excel: <a href="https://i.stack.imgur.com/yqlHY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yqlHY.png" alt="The generated plot. Title: How many times do you have to press the &quot;Irradiate Block&quot; button to get a block to DAC? X axis: Block #, Y axis: # of attempts DAC"></a></p> <h3>Questions:</h3> <ul> <li>What could I do better?</li> <li>Are there libraries that make this kind of simulation easier to write, or faster?</li> <li>Generating the output takes a pretty long time right now: are there any obvious optimizations to be made? Would it be beneficial to make this asynchronous, spawn worker threads somehow, compile in Cython?</li> <li>How could I generate a similar graph using a library like <code>matplotlib</code>?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T03:22:10.533", "Id": "470883", "Score": "1", "body": "What's your question? What do you want from the review?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T18:32:06.983", "Id": "470977", "Score": "0", "body": "@RootTwo Oh yeah, the question part of asking questions... whoops. Added a section. Thanks!" } ]
[ { "body": "<p>The table of probabilities is set as soon as your rad strength and duration are known. You only need to generate it once, for all letters, and then use it as a lookup table.</p>\n\n<pre><code>from collections import defaultdict\n\ndef get_probabilities(rad_strength, rad_duration):\n high = rad_strength*10\n medium = rad_strength*10 - rad_duration\n low = rad_strength*5 + rad_duration\n picks = defaultdict(lambda: \"5\")\n probs = defaultdict(lambda: 1.)\n for letter in [\"C\", \"D\", \"E\", \"F\"]:\n # picks[letter] = (\"4\", \"5\", \"6\", \"7\", \"0\", \"1\", \"2\", \"3\")\n # probs[letter] = (*[high] * 4, *[low] * 2, *[medium] * 2)\n picks[letter] = (\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\")\n probs[letter] = (low, low, medium, medium, high, high, high, high)\n for letter in [\"8\", \"9\", \"A\", \"B\", \"4\", \"5\", \"6\", \"7\"]:\n # picks[letter] = (\"4\", \"5\", \"A\", \"B\", \"C\", \"D\", \"2\", \"3\")\n # probs[letter] = (*[high] * 4, *[low] * 4)\n picks[letter] = (\"2\", \"3\", \"4\", \"5\", \"A\", \"B\", \"C\", \"D\")\n probs[letter] = (low, low, high, high, high, high, low, low)\n for letter in [\"0\", \"1\", \"2\", \"3\"]:\n picks[letter] = (\"8\", \"9\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\")\n # probs[letter] = (*[high] * 4, *[medium] * 2, *[low] * 2)\n probs[letter] = (high, high, high, high, medium, medium, low, low)\n return picks, probs\n</code></pre>\n\n<p>Note that I did not normalize the weights. This is because you can use <a href=\"https://docs.python.org/3/library/random.html#random.choices\" rel=\"nofollow noreferrer\"><code>random.choices</code></a>, which takes a weight argument and normalizes it for you if necessary:</p>\n\n<pre><code>from random import choices\n\ndef scramble(letter, picks, probs):\n return choices(picks[letter], probs[letter])[0]\n</code></pre>\n\n<p>And if that seems like not enough for a function anymore, you might be right. You also don't need your <code>concat_letters</code> function. Lists are directly comparable and so are strings (which are larger than the strings of the numbers and sorted lexicographically): <code>[\"D\", \"A\", \"C\"] &gt; [\"9\", \"A\", \"3\"] -&gt; True</code>. Instead I made the <code>scramble</code> function an inner function, so you don't have to pass the picks and probabilities every time:</p>\n\n<pre><code>from itertools import count\nfrom random import choices\n\ndef scramble_to(initial, target, picks, probs, log=False): \n def scramble(letter):\n return choices(picks[letter], probs[letter])[0]\n\n current = initial.copy()\n for attempt in count():\n if log:\n print(f'Miniscramble #{attempt}:', ''.join(current))\n if current &gt;= target:\n if log:\n print(f'Done with {attempt} miniscrambles!')\n return attempt\n for i in range(3):\n if current[i] &lt; target[i]:\n current[i] = scramble(current[i])\n break # only scramble one letter per attempt\n</code></pre>\n\n<p>The ouput of <code>itertools.product</code> is directly iterable, and so are strings. No need to iterate over them in a needless list/generator comprehension, respectively. You can also use <a href=\"https://docs.python.org/3/library/statistics.html#statistics.mean\" rel=\"nofollow noreferrer\"><code>statistics.mean</code></a> instead of doing it yourself.</p>\n\n<pre><code>from statistics import mean\nfrom itertools import product\n\ndef inactive(seq):\n return seq &lt; (\"8\", \"0\", \"0\") # blocks never start activated, so default is 800\n\nif __name__ == \"__main__\":\n picks, probs = get_probabilities(1, 2)\n block_attempts = 4096\n target = [\"D\", \"A\", \"C\"]\n results = {}\n dataset = filter(inactive, product('0123456789ABCDEF', repeat=3))\n results = {block: mean(scramble_to(list(block), target, picks, probs)\n for _ in range(block_attempts))\n for block in dataset}\n</code></pre>\n\n<p>(Untested for now)</p>\n\n<p>Note that I used a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to ensure this code is not being run when importing from this script and followed Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, throughout this answer. PEP8 recommends using 4 spaces as indentation and always using a newline after e.g. an <code>if log:</code>.</p>\n\n<p>As for visualization, here is a quick attempt at replicating your graph:</p>\n\n<pre><code>import matplotlib.pyplot as plt\n\nplt.style.use(\"dark_background\")\nplt.figure(figsize=(12, 6))\nplt.plot(list(results.values()), 'o-', c=\"orange\")\nplt.grid()\nplt.title(\"How many times do you have to press the \\\"Irradiate Block\\\" button to get a block to DAC?\")\nplt.xlabel(\"Block #\")\nplt.ylabel(\"# of attempts\")\nplt.show()\n</code></pre>\n\n<p>which results in</p>\n\n<p><a href=\"https://i.stack.imgur.com/9TYcn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9TYcn.png\" alt=\"enter image description here\"></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T07:41:13.480", "Id": "240129", "ParentId": "240073", "Score": "2" } }, { "body": "<p>This problem is an <a href=\"https://en.wikipedia.org/wiki/Absorbing_Markov_chain\" rel=\"nofollow noreferrer\">\"absorbing Markov chain\"</a>, and the expected number of steps can be solved analytically.</p>\n\n<p>The Markov chain has a node or state corresponding to each of the DNA blocks. The <code>miniscramble</code> routine, along with the steps of the DNA modification process, can be used to define the transition probablities between states. For example, 0x000 can transistion to 0x100, 0x200, 0x300, ... (only the first digit changes). Similarly 0xD05 can go to 0xD15 ...0xDF5 (only the second digit changes) and so on. Any node >= 0xDAC is an absorbing node.</p>\n\n<p>The code could be cleaner, but it demonstrates the point.</p>\n\n<pre><code>import numpy as np\nimport matplotlib.pyplot as plt\n\ndef make_transition_table(rad_strength, rad_duration):\n # Hi, Med, Lo transition weights\n H = rad_strength*10\n M = rad_strength*10 - rad_duration\n L = rad_strength*5 + rad_duration\n\n transition_probability = []\n\n # for digits 0, 1, 2, 3\n # picks 0 1 2 3 4 5 6 7 8 9 A B C D E F\n weights = [0, 0, 0, 0, 0, 0, 0, 0, H, H, H, H, M, M, L, L]\n total = sum(weights)\n probabilities = [w/total for w in weights]\n transition_probability.extend(probabilities for _ in '0123')\n\n # for digits 4, 5, 6, 7, 8, 9, A, B\n # picks 0 1 2 3 4 5 6 7 8 9 A B C D E F\n weights = [0, 0, L, L, H, H, 0, 0, 0, 0, H, H, L, L, 0, 0]\n total = sum(weights)\n probabilities = [w/total for w in weights]\n transition_probability.extend(probabilities for _ in '456789AB')\n\n # for digits C, D, E, F:\n #picks 0 1 2 3 4 5 6 7 8 9 A B C D E F\n weights = [L, L, M, M, H, H, H, H, 0, 0, 0, 0, 0, 0, 0, 0]\n total = sum(weights)\n probabilities = [w/total for w in weights]\n transition_probability.extend(probabilities for _ in 'CDEF')\n\n return transition_probability\n\n\nrad_strength = 1\nrad_duration = 2\ntransition = make_transition_table(rad_strength, rad_duration)\n\n# build table of all transitions\n# P[i][j] = prob to go from i to j\nP = []\n\nfor i in range(0xFFF + 1):\n d0, rem = divmod(i, 0xFF)\n d1, d2 = divmod(rem, 0xF)\n\n row = [0]*4096\n\n if d0 &lt; 0xD:\n start = d1*0xF + d2\n for c, j in enumerate(range(start, start + 0xF00 + 1, 0x100)):\n row[j] = transition[d0][c]\n\n elif d0 == 0xD:\n if d1 &lt; 0xA:\n start = d0 * 0xFF + d2\n for c, j in enumerate(range(start, start + 0xF0 + 1, 0x10)):\n row[j] = transition[d1][c]\n\n elif d1 == 0xA:\n if d2 &lt; 0xC:\n start = d0 * 0xFF + d1 * 0xF\n for c, j in enumerate(range(start, start + 0xF + 1, 0x1)):\n row[j] = transition[d2][c]\n\n P.append(row)\n\n# convert to numpy array to do to more easily \n# select Q and do the matrix math\nP = np.array(P)\n\nQ = P[:0xDAB,:0xDAB]\n\nI = np.identity(Q.shape[0])\n\nN = np.linalg.inv(I - Q)\n\n# this is the same a N*1 as shown in the Wikipedia article\navg_steps = np.sum(N, axis=1)\n\n# change indices for avg_steps to view different\n# ranges of starting points\nplt.plot(avg_steps[:0x801])\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/1Qj5N.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1Qj5N.png\" alt=\"Expected number of steps to reach DNA &#39;DAC&#39;\"></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T23:44:59.297", "Id": "240236", "ParentId": "240073", "Score": "2" } } ]
{ "AcceptedAnswerId": "240236", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-06T21:43:21.753", "Id": "240073", "Score": "1", "Tags": [ "python", "game", "random", "simulation" ], "Title": "Monte Carlo Simulation of \"DNA Mutation\" Game Mechanic" }
240073
<p>Logical processors available on my machine: </p> <pre><code>CPU(s): 4 Thread(s) per core: 2 </code></pre> <p>So, 2x4 = 8 logical processors. But am currently using only 4 go-routines that should map to 4 OS threads.</p> <pre><code>$ lscpu Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian CPU(s): 4 On-line CPU(s) list: 0-3 Thread(s) per core: 2 </code></pre> <hr> <p>Each go routine is given 2K stack. GoLang by design does not have stackoverflow issues for medium size data, because it grows the stack size, until a limit</p> <p>So, am using recursive approach instead of an efficient iterative approach</p> <p>Divided the input into 4 parts instead of 8 parts.</p> <pre><code>package expressions import ( "fmt" "sync" ) func FindMax(list []int, length int) int { var wg sync.WaitGroup wg.Add(1) var max1 int go func() { max1 = max(list[0 : length/4]) wg.Done() }() wg.Add(1) var max2 int go func() { max2 = max(list[length/4 : length/2]) wg.Done() }() wg.Add(1) var max3 int go func() { max3 = max(list[length/2 : 3*length/4]) wg.Done() }() wg.Add(1) var max4 int go func() { max4 = max(list[3*length/4 : length]) wg.Done() }() wg.Wait() fmt.Println(max1, max2, max3, max4) var resultList = make([]int, 4) resultList[0] = max1 resultList[1] = max2 resultList[2] = max3 resultList[3] = max4 return max(resultList) } func max(list []int) int { length := len(list) if length &gt; 1 { if list[0] &gt; list[length-1] { return max(list[:length-1]) } else { return max(list[1:length]) } } return list[0] } </code></pre> <hr> <pre><code>package main import ( "fmt" "github.com/myhub/cs61a/expressions" ) var list = []int{4, 4, 4, 4, 6, 7, 8} func main() { var value = expressions.FindMax(list, len(list)) fmt.Println(value) } </code></pre> <hr> <p>Benchmark testing for <code>1e6</code> elements. With <code>length</code> value <code>1e8</code>, stackoverflow occurs.</p> <pre><code>$ go test -run none -bench . 1000000 750000 500000 250000 Max element is: 1000000 goos: linux goarch: amd64 pkg: github.com/myhub/cs61a/expressions BenchmarkMax-4 1000000 750000 500000 250000 Max element is: 1000000 1000000 750000 500000 250000 Max element is: 1000000 1000000 750000 500000 250000 Max element is: 1000000 1000000 750000 500000 250000 Max element is: 1000000 1000000 750000 500000 250000 Max element is: 1000000 1000000 750000 500000 250000 Max element is: 1000000 1000000 750000 500000 250000 Max element is: 1000000 1000000 750000 500000 250000 Max element is: 1000000 1000000000 0.0795 ns/op PASS ok github.com/myhub/cs61a/expressions 0.737s </code></pre> <hr> <p>1) Can function <code>max()</code> be improved in terms of condition check?</p> <p>2) Is <code>expressions</code> package providing good abstraction(<code>FindMax</code>) and encapsulation, as API interface? <code>FindMax</code> api is hard coded for 4 thread logic</p> <p>3) <code>sync.waitGroup</code> is not allowing parallel operations on 4 threads. How to achieve parallelism?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T04:19:39.590", "Id": "470885", "Score": "0", "body": "Does this work as intended? Did you try any input sequence with a descending subsequence?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T04:34:10.570", "Id": "470887", "Score": "0", "body": "@slepic Query edited. Now... it is working for `5,4,3,2,1`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T05:11:24.553", "Id": "470888", "Score": "0", "body": "Looks good now. Learn to test all your ifs as well as elses :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T11:44:24.597", "Id": "470928", "Score": "0", "body": "Avoid systematic recursion anyways, go does not provide tco support. If sorted input data is required for that function, take the last element. A good algorithm should check length of the input data and decide if it takes upper-half of the slices when it is large before iterating over resting elements, assuming it is sorted upfront. If it is not sorted upfront, and you are dealing with very large slice, i guess, some smarter algorithm splits the load across multiple routines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T12:20:53.240", "Id": "470937", "Score": "0", "body": "@mh-cbon What is tco support?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T12:26:19.473", "Id": "470938", "Score": "0", "body": "tail call optimization. It is an optimization to improve performance of recursion. add benchmarks to your code, with and without recursion, with small slices, you will see that recursion is much slower. On the other hand, when there is a large slice, it is smart to skip half of the items when possible, using recursion, or not! when the slice is veeeerrryyy large, and unsorted, you might want split the slice in that many routines, take each parts, sort it, max it, then gather each results, sort them, max them to get the final result. i guess with current confinement i might take time to demo it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T12:55:01.793", "Id": "470943", "Score": "1", "body": "@mh-cbon here is the issue: https://stackoverflow.com/q/61080157/3317808" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T04:38:08.843", "Id": "471024", "Score": "0", "body": "@mh-cbon do you think the sorting is necesary? The best sort i know of is O(n*log n), but naievely going through the array is just O(n). Multiple threads or not. But i agree that using recursion Is not the best way to go..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T07:05:01.320", "Id": "471026", "Score": "0", "body": "@slepic the answer is definitely within your question. You kind of spoiled the discovery." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T07:07:54.727", "Id": "471027", "Score": "0", "body": "@slepic but going down the obvious, as the demo code assumes sorted data, you can just pick the last element, compare it with the first element, return the biggest. no iteration. and it works with both descending and ascending sorted slice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T16:36:26.013", "Id": "471068", "Score": "0", "body": "@mh-cbon Am using recursive approach, because am weak in recursion, otherise it is a simple iterative loop. Query edited with enhanced code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T13:14:47.323", "Id": "471620", "Score": "0", "body": "Just a point of general pedantry: you're *not* using 4 routines. The `main` function runs in a go-routine on the go runtime, and the garbage collector runs in a routine. You're running at the very least in 6 routines. Golang doesn't cleanly map onto actual threads. That's why they say that _\"concurrency is not parallelism\"_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T13:19:40.537", "Id": "471623", "Score": "0", "body": "@EliasVanOotegem Actually I can set to 8 logical processors(2 X 4 core). 2 Logical processors per core. Can I `runtime.GOMAXPROCS(8)` and make 6 go routines run in 8 OS threads in parallel?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T13:45:22.600", "Id": "471631", "Score": "0", "body": "@overexchange: No, there's no guarantee a go binary will use all threads available. It might decide to start the runtime in a thread, and run the main routine in the same thread (concurrently). That would leave you with 7 actual threads available. The runtime could use one for the GC, but then decide to pair up the other 4 routines in pairs on 2 threads, so you'd end up using half of the threads available. Doesn't seem ideal, unless your application can suddenly require a lot more routines to spin up, in which case the runtime was right to keep 4 threads open/available" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T13:52:42.730", "Id": "471635", "Score": "0", "body": "@EliasVanOotegem Initially all go-routines sit in GCQ. Go scheduler will assign each go-routine to an idle OS thread's(LCQ). Isn't it? First goroutine of my 4 go-routines(`max`) is already busy on OS-thread-1(say), Does Go scheduler assign second go-routine to new OS-thread-2( LCQ)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T14:03:48.553", "Id": "471638", "Score": "0", "body": "when you say: \"then decide to pair up the other 4 routines in pairs on 2 threads\". How can a scheduling algorithm follow such scheduling policy?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T14:06:13.130", "Id": "471639", "Score": "0", "body": "The scheduler is quite a lot to get into, but basically, there's a queue per processor, if a routine is waiting for IO or something, the scheduler will use the idle CPU time to run another routine concurrently (not in parallel). It could be that one thread depletes its queue, while the other processor still has 3 routines waiting. Just a couple of things to show that a routine doesn't map directly to a thread" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T14:09:30.237", "Id": "471640", "Score": "0", "body": "@EliasVanOotegem Another point... just assuming two go-routines(of `max`) running parallel on 2 OS threads. How the above code is ensuring that `list` is accessed atomically, by two go-routines?Because I dont know the mechanics of using `wg.Add(1)` and `wg.Done()`...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-05T06:53:56.063", "Id": "477765", "Score": "0", "body": "@overexchange - list is not accessed atomically, it may be accessed in parallel. But that's not an issue, since it was created before the 4 goroutines are created (thus happens-before) and it's never modified. There's no data race there. Regarding the WaitGroup, wg.Done() happens-before wg.Wait(), meaning that the writes to max1 etc will be safely readable after wg.Wait(). Finally, if you do want to force each one of those 4 goroutines into its own thread, you can: in each one, call runtime.LockOSThread(). You should also probably call runtime.UnlockOSThread() in the end of each goroutine" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "19", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T02:08:38.543", "Id": "240081", "Score": "1", "Tags": [ "multithreading", "recursion", "go", "api" ], "Title": "Recursion - Max of integers in slice" }
240081
<p>I am not sure whether this is the right place to ask this, so please correct me if it's not.</p> <p>I am following <a href="https://arxiv.org/pdf/1108.6032.pdf" rel="nofollow noreferrer">this paper</a> (e.g., Corollary 3.3) for some derived functional representations of the densities and writing code for those. The code for one of the families:</p> <p>(<code>x</code> will be a vector of 1xd between [0,1], <code>tau</code> - scalar in [1, infty).)</p> <pre><code>'joe_density' &lt;- function(x, tau){ require(gmp) require(Rmpfr) require(magrittr) d &lt;- length(x) P_d &lt;- function(x, tau, d){ alpha &lt;- 1/tau lapply(1:d, function(k){ as.numeric(gmp::Stirling2(n = d, k = k)) * gamma(k - alpha) / gamma(1 - alpha) * x^(k-1) }) %&gt;% do.call(sum, .) } h &lt;- prod((1 - (1 - x)^tau)) mpfr( tau^(d-1), 16) * mpfr( prod((1 - x)^(tau - 1)), 16) / mpfr( (1 - h)^(1 - 1/tau), 16) * mpfr( P_d( h/(1-h), tau, d), 16) } </code></pre> <p>Example call:</p> <pre><code># Simple case x &lt;- pnorm(rnorm(100)) joe_density(x, tau = 2) # Longer performance time when looping, d=2 expand.grid(x = seq(-5,5,by=0.1), y = seq(-5,5,by=0.1)) %&gt;% apply(.,1,function(z){ x &lt;- pnorm(z) joe_density(x, tau = 2) }) </code></pre> <p>In essence, the typical calculations require tons of looping, gamma/Stirling numbers, and I have noticed that the default precision is usually not enough, hence the <code>Rmpfr</code> usage. One time evaluation of the code is not a problem, however, the calculations become very lengthy when the function is called thousands of time (e.g., passing it to <code>optim</code> and the likes). </p> <p>Are there simpler ways to program this? This particular function is just an example, but most of the different functions follow similar approach, with a high usage of Stirling/gamma, lengthy products and etc. </p> <p>Could, for example, rewriting parts of the code in <code>Rcpp</code> be helpful, or is this not the type of task that we could expect gains here? I have no experience in writing <code>cpp</code> code, so am not sure what to expect. </p>
[]
[ { "body": "<p>Some suggestions:</p>\n\n<ul>\n<li><p>split code more, line by line, so it is easier to profile and see bottlenecks</p></li>\n<li><p>use <code>profvis</code></p></li>\n<li><p>use <code>%&gt;%</code> less often if that part of code is called frequently, it has some overhead</p></li>\n<li><p>separate function definitions</p></li>\n</ul>\n\n<p>This should run a little bit faster: (15s vs 27s on your example)</p>\n\n<pre><code>P_d &lt;- function(x, tau, d){\n alpha &lt;- 1/tau\n l &lt;- sapply(1:d, function(k){\n p1 &lt;- Stirling2(n = d, k = k)\n p1 &lt;- as.numeric(p1)\n p1 * gamma(k - alpha) / gamma(1 - alpha) * x^(k-1)\n })\n sum(l)\n}\n\njoe_density &lt;- function(x, tau){\n d &lt;- length(x)\n h &lt;- prod((1 - (1 - x)^tau))\n\n v1 &lt;- tau^(d-1)\n v2 &lt;- prod((1 - x)^(tau - 1))\n v3 &lt;- (1 - h)^(1 - 1/tau)\n v4 &lt;- P_d( h/(1-h), tau, d)\n\n p1 &lt;- mpfr(v1, 16) # slow\n p1 * v2 / v3 * v4 # slow\n}\n</code></pre>\n\n<p>The slowest part is <code>mpfr</code> &amp; the last line, because each value is converted to <code>mpfr</code>.\nMaybe you can deal with precision loss in some kind of different way?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T11:08:41.803", "Id": "470918", "Score": "0", "body": "Thanks, all very good points! Will add ``profvis`` to the toolbox, looks promising. For larger dimensions, ``Stirling2`` seems to be the largest bottleneck, as can be expected. About the ``mpfr`` - will have to test when can I really drop it; it was added to deal with extreme numeric values, both explosive and very close to 0, but maybe some approximations at both ends will work too." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T09:20:39.843", "Id": "240090", "ParentId": "240086", "Score": "2" } } ]
{ "AcceptedAnswerId": "240090", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T06:17:48.607", "Id": "240086", "Score": "4", "Tags": [ "performance", "r", "rcpp" ], "Title": "Function for calculating Archimedean density functions" }
240086
<p>Following great feedback given in response to my previous <a href="https://codereview.stackexchange.com/questions/239878/a-heap-queue-in-dyalog-apl">question</a>, I was encouraged to consider a different type of heap structure, the Leftist Tree. It lends itself better to a functional implementation. It's already shorter, but is there anything else I should consider in order to make this more idiomatic APL? Many thanks.</p> <pre><code>⍝ APL implementation of a leftist tree. ⍝ ⍝ https://en.wikipedia.org/wiki/Leftist_tree ⍝ http://typeocaml.com/2015/03/12/heap-leftist-tree/ ⎕io←0 Insert←{ ⍝ Insert item into leftist tree, returning the resulting tree (tree item)←⍵ 1 item ⍬ ⍬ Merge tree } Pop←{ ⍝ Pop off smallest element from a leftist tree 0=≢⍵:⍬ (v l r)←1↓⍵ ⍝ value left right (l Merge r) v ⍝ Return the resulting tree and the value } Merge←{ ⍝ Merge two leftist trees, t1 and t2 t1←⍺ ⋄ t2←⍵ 0=≢t1:t2 ⋄ 0=≢t2:t1 ⍝ If either is a leaf, return the other (key1 left right)←1↓t1 ⋄ key2←1⌷t2 key1&gt;key2:t2∇t1 ⍝ Flip to ensure smallest is root of merged merged←right∇t2 ⍝ Merge rightwards (⊃left)≥⊃merged:(1+⊃merged) key1 left merged ⍝ Right is shorter (1+⊃left) key1 merged left ⍝ Left is shorter; make it the new right } ⍝ Example heap merge from http://typeocaml.com/2015/03/12/heap-leftist-tree/ h←Insert ⍬ 2 h←Insert h 10 h←Insert h 9 s←Insert ⍬ 3 s←Insert s 6 h Merge s ┌→─────────────────────────────────────────────────────────────┐ │ ┌→────────────────────────────────────┐ ┌→─────────────┐ │ │ 2 2 │ ┌→────────────┐ ┌→────────────┐ │ │ ┌⊖┐ ┌⊖┐ │ │ │ │ 2 3 │ ┌⊖┐ ┌⊖┐ │ │ ┌⊖┐ ┌⊖┐ │ │ │ 1 10 │0│ │0│ │ │ │ │ │ 1 6 │0│ │0│ │ │ 1 9 │0│ │0│ │ │ │ └~┘ └~┘ │ │ │ │ │ └~┘ └~┘ │ │ └~┘ └~┘ │ │ └∊─────────────┘ │ │ │ └∊────────────┘ └∊────────────┘ │ │ │ └∊────────────────────────────────────┘ │ └∊─────────────────────────────────────────────────────────────┘ </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T09:18:37.130", "Id": "470912", "Score": "0", "body": "`⎕io←0` Is the correct character shown here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T09:19:40.317", "Id": "470913", "Score": "1", "body": "@Mast Yes, that is an APL \"Quad\" symbol which is a stylised console, so it is supposed to render as a rectangle." } ]
[ { "body": "<p>I think your code generally looks good.</p>\n\n<h3>Comments</h3>\n\n<p>I recommend annotating functions with what the structure of their argument(s) and result are, especially when not just simple arrays, at the top of the function, rather than relying on code comments to reveal this.</p>\n\n<h3>Take benefit of dyadic functions</h3>\n\n<p>If you define <code>Insert</code> and <code>Pop</code> as dyadic functions both code and usage can be simplified. You can even let <code>⍬</code> be the default left argument, allowing easy initialisation of a tree.</p>\n\n<pre><code>Insert←{ ⍝ Insert item ⍵ into leftist tree ⍺, returning the resulting tree\n ⍺←⍬ ⍝ default to init\n 1 ⍵ ⍬ ⍬ Merge ⍺ \n}\n</code></pre>\n\n<pre><code>h←Insert 2\nh Insert←10\nh Insert←9\n\ns←Insert 3\ns Insert←6\n</code></pre>\n\n<h3>Full variable names or not?</h3>\n\n<p>This is a personal style thing. Some people prefer mathematical-looking single-letter variables, others like full variable names that obviate comments. However, at least be consistent. (I've also moved the first element of <code>⍵</code> to become <code>⍺</code>, as per above.)</p>\n\n<pre><code>Pop←{ ⍝ Pop off smallest element from a leftist tree\n 0=≢⍺:⍬\n (value left right)←⍵\n (left Merge right) value\n}\n</code></pre>\n\n<h3>Unnecessary naming</h3>\n\n<p><code>⍺</code> and <code>⍵</code> are well understood to be the left and right arguments. I don't think renaming them <code>t1</code> and <code>t2</code> brings much, other than the ability to create matching <code>keyN</code> variables. However, here you only ever use <code>key2</code> once, and its definition is very simple, and in fact as short or shorter than any appropriate name, so you might as well use it inline, freeing up <code>key</code> to only apply to <code>⍵</code>:</p>\n\n<pre><code>Merge←{ ⍝ Merge leftist trees ⍺ and ⍵\n 0=≢⍺:⍵ ⋄ 0=≢⍵:⍺ ⍝ If either is a leaf, return the other\n (key left right)←1↓⍺\n key&gt;1⌷⍵:⍵∇⍺ ⍝ Flip to ensure smallest is root of merged\n merged←right∇⍵ ⍝ Merge rightwards\n (⊃left)≥⊃merged:(1+⊃merged) key left merged ⍝ Right is shorter\n (1+⊃left) key merged left ⍝ Left is shorter; make it the new right\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T11:38:43.067", "Id": "470924", "Score": "0", "body": "Many thanks for helpful review. I really like the `h Insert←10` approach, once I understood it. Small typo -- first line of your version of Merge should be `0=≢⍺:⍵ ⋄ 0=≢⍵:⍺`, I think." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T11:39:49.200", "Id": "470925", "Score": "0", "body": "@xpqz Fixed. Thanks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T09:38:26.407", "Id": "240091", "ParentId": "240089", "Score": "4" } }, { "body": "<h2>APL-specific</h2>\n\n<h3>Keep the nesting levels consistent</h3>\n\n<p>At this line:</p>\n\n<pre><code>(key1 left right)←1↓t1 ⋄ key2←1⌷t2\n</code></pre>\n\n<p><code>key1</code> is effectively disclosed one level, while <code>key2</code> is not. It doesn't matter in this code because both <code>key1</code> and <code>key2</code> are assumed to be scalars, but they are semantically different:</p>\n\n<pre><code> ⍝ Assume ⎕IO←1\n (a b c)←nested←(1 2 3)(4 5 6)(7 8 9)\n 1 2 3≡a\n1\n (⊂1 2 3)≡1⌷nested\n1\n 1 2 3≡1⊃nested\n1\n</code></pre>\n\n<p>Semantically correct one would be <code>key2←1⊃t2</code> instead.</p>\n\n<hr>\n\n<h2>General tips</h2>\n\n<h3>Give a name to algorithm-wise important constant(s)</h3>\n\n<p>In this code, <code>⍬</code> is being used to signify the empty heap. It appears in <code>Insert</code> and <code>Pop</code>, and is also used as the initial heap in the testing code. You can give it a meaningful name:</p>\n\n<pre><code>empty←⍬\n</code></pre>\n\n<p>That way, you can make several parts of the code easier to understand, and you can even write <code>empty≡t1:...</code> to test if a (sub-)tree is empty, instead of a roundabout way <code>0=≢t1:...</code>.</p>\n\n<h3>Name meaningful intermediate values</h3>\n\n<p>At the bottom of <code>Merge</code>:</p>\n\n<pre><code> (⊃left)≥⊃merged:(1+⊃merged) key1 left merged\n (1+⊃left) key1 merged left\n</code></pre>\n\n<p>Both <code>⊃left</code> and <code>⊃merged</code> are used twice in the code, and both have a good meaning -- the rank of the corresponding tree. We can name both:</p>\n\n<pre><code> leftRank←⊃left ⋄ mergedRank←⊃merged\n leftRank≥mergedRank:(1+mergedRank) key1 left merged\n (1+leftRank) key1 merged left\n</code></pre>\n\n<h3>Check the time complexity of your function</h3>\n\n<p>Algorithm is all about correctness <em>and</em> performance. If you checked that your implementation gives correct results, the next step is to measure its time complexity. Dyalog APL provides multiple ways to measure it:</p>\n\n<ul>\n<li><a href=\"http://dfns.dyalog.com/n_time.htm\" rel=\"nofollow noreferrer\"><code>dfns.time</code></a>, <a href=\"http://dfns.dyalog.com/n_cmpx.htm\" rel=\"nofollow noreferrer\"><code>dfns.cmpx</code></a>, and <a href=\"http://dfns.dyalog.com/n_profile.htm\" rel=\"nofollow noreferrer\"><code>dfns.profile</code></a></li>\n<li>User commands <code>]runtime</code> and <code>]profile</code> (IIRC)</li>\n</ul>\n\n<p>Learn how and when to use them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T10:28:18.513", "Id": "470916", "Score": "1", "body": "Thank you! I do struggle with the enclose/disclose thing and how they relate to indexing." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T10:22:24.090", "Id": "240092", "ParentId": "240089", "Score": "2" } } ]
{ "AcceptedAnswerId": "240091", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T08:52:33.053", "Id": "240089", "Score": "5", "Tags": [ "tree", "apl" ], "Title": "Leftist Tree in Dyalog APL -- can it be made more compact/idiomatic?" }
240089
<p>I've written an interactive function which lets me shudown, reboot my machine as well as put it to sleep.</p> <p>I'm using emacs and I'm just starting out getting into ELISP programming. As I'm a total beginner, I'd like to know what you would do differently in the following code to make it better, lighter and so on. Many thanks in advance.</p> <pre class="lang-lisp prettyprint-override"><code>(defun db/power-menu () "Interactive menu for shutdown, reboot or sleep." (interactive) (let ((actions '("Shutdown" "Reboot" "Sleep"))) (setq action (ivy-completing-read "What do you want to do?" actions )) (if (y-or-n-p (concat "Execute " action "? Unsaved progress will be lost. ")) (let ((default-directory "/sudo::")) (cond ((equal action "Shutdown") (shell-command "systemctl poweroff")) ((equal action "Reboot") (shell-command "systemctl reboot")) ((equal action "Sleep") (shell-command "systemctl suspend"))))))) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T11:10:32.637", "Id": "470919", "Score": "0", "body": "Seems simple enough, from where are you calling this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T11:18:33.723", "Id": "470920", "Score": "1", "body": "I'm just calling this manually at the moment. But I plan on intercepting the ACPI event when the power button is pressed to execute emacsclient and this function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T15:43:54.497", "Id": "470958", "Score": "0", "body": "This is gathering close votes for having an incomplete description. You may want to separate talking about yourself and talking about the program. This will make it harder to mistake your description as just a long winded \"I'm a beginner\"." } ]
[ { "body": "<p><strong>Disclaimer:</strong> Total beginner here too. So take everything with a grain of salt.</p>\n<p>That being said this looks perfectly fine. However, I suggest you to use <code>completing-read</code> instead of <code>ivy-completing-read</code> as it will provide more flexibility. Don't worry, if you use <code>ivy-mode</code> (or customize <code>completing-read-function</code> to <code>ivy-completing-read</code>), then <code>completing-read</code> will use <code>ivy-completing-read</code>.This is especially helpful if you want to copy your snippet to another Emacs configuration where <code>ivy</code> isn't installed.</p>\n<p>Other than that, I <em>guess</em> you want to introduce <code>action</code> before you <code>setq</code> it. However, I'm not really sure whether it's necessary.</p>\n<p>Note that I will probably use your <code>db/power-menu</code> in my configuration. Well done :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-17T08:50:40.350", "Id": "250784", "ParentId": "240093", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T10:32:52.047", "Id": "240093", "Score": "3", "Tags": [ "elisp" ], "Title": "Power menu (Shutdown, Reboot, Sleep) in ELISP" }
240093
<p>First off, not the greatest with jQuery but know enough to get by. I created this mock up that is base on my application and wanted to see if there is a better way to update hidden values and a tags. When the form is saved I am using the sortorder to find the corresponding .ui-sortable li that has a tag and hidden fields to get updated on the page. I am trying to update the correct one and looping all of them checking with the sortorder I just wanted to know if there is a better way to do this?</p> <pre><code>https://jsfiddle.net/tjmcdevitt/vh9n5srL/35/ </code></pre> <p>actual code from a project</p> <pre><code>$("#submit-form").submit(function (event) { event.preventDefault(); var sortOrder = $(this).data('sortorder'); $('.ui-sortable li').each(function (i) { if (i == sortOrder) { console.log('Updating'); $("#References_0_UI").html(data.referenceText); $("#References_0_UI").attr("href", data.GuidelineExternalReference); $('input[name="References[0].Text"]').val(data.referenceText); $('input[name="References[0].Link"]').val(data.GuidelineExternalReference); $('input[name="References[0].GuidelineId"]').val(data.Value); console.log("Completed Task"); } }); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T15:26:22.950", "Id": "470956", "Score": "0", "body": "`I created this mock up` You're around long enough to know [actual code from a project](https://codereview.stackexchange.com/help/on-topic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T15:49:17.943", "Id": "470960", "Score": "2", "body": "@greybeard A mock up is still an actual project. The code doesn't look like it's psudocode or has sections of it missing with some nice comment like `// Do my project`. There are various places on Meta where producing a mock up is suggested by previous moderators and high rep users. Is there actually any context missing from the above code or are you just triggered over some minor words?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T16:33:26.857", "Id": "470964", "Score": "0", "body": "(@Peilonrayz triggered by `this […] is base on my application` - bee-holder, anyone?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T16:47:41.340", "Id": "470965", "Score": "0", "body": "@greybeard That's been recommended on meta." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T17:03:59.260", "Id": "470966", "Score": "0", "body": "I updated with the actual code from a project not sure how that helps" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T17:08:45.837", "Id": "470967", "Score": "0", "body": "It makes it a concrete example of working code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T20:58:28.547", "Id": "470995", "Score": "0", "body": "In the code in your question, the `$(\"#References_0_UI\").html` and similar lines look like they wouldn't work, since the index is being hard-coded. Did you mean `$('References_'+ sortOrder + '_UI').html` like in the fiddle? Also, I don't understand the purpose of iterating over the `.ui-sortable li`s, since the found `li` is never used. (The `li` isn't in any of the code I see either)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T21:13:19.820", "Id": "471001", "Score": "0", "body": "Yes still working out the application part to this. I guess there is no need to loop all the li." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T21:45:42.707", "Id": "471004", "Score": "0", "body": "@certainperformane is there a better way to set the values for all the hidden fields?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T14:29:34.613", "Id": "471051", "Score": "0", "body": "@greybeard the UI to close should contain a button to retract the VTC - see [this meta answer](https://meta.stackexchange.com/a/167514/341145) for more information" } ]
[ { "body": "<p>The <em>main</em> issue I see is that the looping doesn't accomplish anything useful, since you never reference the <code>li</code> that you iterate over - just take the <code>sortOrder</code> from the form and concatenate it into the selectors you try to find.</p>\n\n<p>Because you reference the <code>#References_##_UI</code> twice, consider saving it in a variable first - or, even better, since this is jQuery, you can chain methods on the selected collection.</p>\n\n<p>It sounds like the <code>data.referenceText</code> is <em>text</em>, not HTML markup - in which case you should insert it into the DOM with <code>.text</code>, not with <code>.html</code>. (<code>.text</code> is faster and safer)</p>\n\n<pre><code>$('#submit-form').submit(function (event) {\n event.preventDefault();\n const sortOrder = $(this).data('sortorder');\n $(`#References_${sortOrder}_UI`)\n .text(data.referenceText)\n .prop('href', data.GuidelineExternalReference);\n $(`input[name='References[${sortOrder}].Text']`).val(data.referenceText);\n $(`input[name='References[${sortOrder}].Link']`).val(data.GuidelineExternalReference);\n $(`input[name='References[${sortOrder}].GuidelineId']`).val(data.Value);\n});\n</code></pre>\n\n<p>The above looks <em>mostly</em> reasonable to me, but I'd change the HTML too, if that's permitted. Numeric-indexed IDs are never a good idea; IDs should be reserved for singular, unique elements. (You can also consider not using IDs at all, because every time there is one, a <a href=\"https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables\">global variable</a> is created, and globals can result in confusing behavior).</p>\n\n<p>A related issue is that the submit handler here is attached to:</p>\n\n<pre><code>$('#submit-form').submit(\n</code></pre>\n\n<p>Since IDs must be unique in a document, this will only attach a listener to a single form, but it sounds like you have multiple forms that you want to listen for <code>submit</code> events to.</p>\n\n<p>To solve the duplicate IDs and the numeric-indexed IDs, use the already-existing class to select the forms instead, and once you have a reference to the form in the handler, use <code>.find</code> to select its children elements that need to be populated.</p>\n\n<p>Your 3 hidden inputs are somewhat repetitive. It might look somewhat tolerable now, but if you might add more, or for the general case of linking each data property name to a particular input, consider using an object or array linking each property to the selector:</p>\n\n<pre><code>const inputNamesByDataProps = {\n referenceText: 'Text',\n GuidelineExternalReference: 'Link',\n Value: 'GuidelineId',\n};\n$('.form-horizontal').on('submit', (event) =&gt; {\n event.preventDefault();\n const $this = $(this);\n $this.find('a')\n .text(data.referenceText)\n .prop('href', data.GuidelineExternalReference);\n for (const [dataProp, inputName] of Object.entries(inputNamesByDataProps)) {\n $this.find(`input[name$=${inputName}]`).val(data[dataProp]);\n }\n});\n</code></pre>\n\n<p>(The <code>[name$=${inputName}]</code> means: \"Find an element whose <code>name</code> attribute ends with what's in <code>inputName</code>\")</p>\n\n<pre><code>&lt;form class=\"form-horizontal\" data-sortorder=\"1\"&gt;\n &lt;p&gt;Update Values&lt;/p&gt;\n &lt;a class=\"References_1_UI\" href=\"www.current.com\" target=\"_blank\"&gt;Testing html&lt;/a&gt;.\n &lt;input type='hidden' name='References[1].Index' value=\"1\"&gt;\n &lt;input type='hidden' name='References[1].Link' value=\"www.oldlink.com\"&gt;\n &lt;input type='hidden' name='References[1].Id' value=\"88\"&gt;\n &lt;div class=\"text-center\"&gt;\n &lt;button type=\"submit\"&gt;Save&lt;/button&gt;\n &lt;button type=\"button\" data-dismiss=\"modal\"&gt;Close&lt;/button&gt;\n &lt;/div&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>The input HTML name attributes look pretty repetitive too, but repetitive HTML <em>usually</em> isn't something to worry about, especially if your backend logic is easier to work with when the attributes are like <code>References[1].Index</code>. But if you wanted, you could change it to something like</p>\n\n<pre><code>&lt;input type='hidden' name='sortorder' value=\"1\"&gt;\n&lt;input type='hidden' name='Index' value=\"1\"&gt;\n&lt;input type='hidden' name='Link' value=\"www.oldlink.com\"&gt;\n&lt;input type='hidden' name='Id' value=\"88\"&gt;\n</code></pre>\n\n<p>putting the <code>[1]</code> into the hidden <code>sortorder</code> input instead, and then parse the form values on the backend.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T14:01:43.163", "Id": "471050", "Score": "0", "body": "is this the correct format (`#References_${sortOrder}_UI`) I am getting an error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T19:12:12.947", "Id": "471074", "Score": "0", "body": "Yes, that's valid syntax, see https://jsfiddle.net/61z4u7jc/ - that's a template literal, which is more readable than concatenation IMO. If your environment doesn't support ES2015, you should strongly consider upgrading - that was an eternity ago in web development terms." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T22:42:52.987", "Id": "240120", "ParentId": "240097", "Score": "1" } } ]
{ "AcceptedAnswerId": "240120", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T13:28:40.653", "Id": "240097", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "jquery update hidden and a tags" }
240097
<p>Given an array of integer (all different from each other), this program creates a BST with the array elements in order to sort them and put them back into the array, using the BST properties.</p> <pre><code>#include&lt;iostream&gt; using namespace std; struct Node { int label; Node* left; Node* right; ~Node() { delete left; delete right; } }; void insertSearchNode(Node* &amp;tree, int x) //insert integer x into the BST { if(!tree){ tree = new Node; tree-&gt;label = x; tree-&gt;right = NULL; tree-&gt;left = NULL; return; } if(x &lt; tree-&gt;label) insertSearchNode(tree-&gt;left, x); if(x &gt; tree-&gt;label) insertSearchNode(tree-&gt;right, x); return; } void insertArrayTree(int arr[], int n, Node* &amp;tree) //insert the array integer into the nodes label of BST { for(int i=0; i&lt;n; i++){ insertSearchNode(tree, arr[i]); } return; } int insertIntoArray(int arr[], Node* &amp;tree, int i) //insert into the array the node label touched during an inorder tree traversal { if(!tree) return i; i = insertIntoArray(arr, tree-&gt;left, i); arr[i] = tree-&gt;label; i++; i = insertIntoArray(arr, tree-&gt;right, i); return i; } int main() { Node* maintree; maintree = NULL; int num = 7; int arr[num] = {120, 30, 115, 40, 50, 100, 70}; insertArrayTree(arr, num, maintree); //insert elements into BST insertIntoArray(arr, maintree, 0); //modify array sorting his elements using the BST for(int y=0; y&lt;num; y++) cout&lt;&lt; arr[y] &lt;&lt; ' '; return 0; } </code></pre> <p>Output:</p> <pre><code>30 40 50 70 100 115 120 </code></pre> <p>Any advice is welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T18:10:38.050", "Id": "470972", "Score": "0", "body": "@S.S.Anne Not sure you really needed to delete all that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T18:22:22.087", "Id": "470976", "Score": "1", "body": "@pacmaninbw The information there could be more easily expressed in tags, which is why I edited. The rest of that wasn't really necessary for a review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T19:11:34.723", "Id": "470982", "Score": "0", "body": "@pacmaninbw what information could I keep in your opinion? I would like to know so that I can write a better question next time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T19:14:28.460", "Id": "470984", "Score": "0", "body": "Use the tags as much as possible because they are searchable. Give an overview of what the code does in text, most reviewers can get a lot from the code. This first attempt was better than many." } ]
[ { "body": "<p>Your code is readable and easy to understand. Said that I would like to make you think about how you handle the operations in your BSTree.</p>\n\n<p>You are building the functions <strong>alone</strong>, and what that causes is to manually manage these functions and compromise the structure of your tree if accidentally you write something wrong. </p>\n\n<p>You should opt for an Internal management rather than external one. For example:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>struct BinaryNode\n{\n int label_;\n Node* left_;\n Node* right_;\n\n //having constructors makes you write less code\n\n BinaryNode(Node *left, const int &amp;label, Node *right) : \n label_(label), left_(left), right_(right)\n {\n }\n\n //const [datatype]&amp; \n //means to not copy the value of the parameter\n BinaryNode(const int &amp;label) :\n //nullptr is typesafe use it instead of NULL which is a macro\n label_(label), left_(nullptr), right_(nullptr)\n {\n }\n\n ~BinaryNode() {\n delete left_;\n delete right_;\n }\n};\n\nclass BinarySearchTree\n{\nprivate:\n BinaryNode *root_;\n\nprotected://if some derived class is needed (as an AVLTree)\n //Google about virtual functions for abstract classes (pure virtual too)\n virtual void Insert(const int &amp;x, Node *node)\n {\n if (x &lt; node-&gt;label_)\n if (node-&gt;left_ == nullptr)\n node-&gt;left_ = new BinaryNode(t);\n else Insert(t, node-&gt;left_);\n else if (x &gt; node-&gt;label_)\n if (node-&gt;right_ == nullptr)\n node-&gt;right_ = new BinaryNode(t);\n\n //If x is in the tree it does not include x again\n }\n\npublic:\n virtual void Insert(const int &amp;x)\n {\n Insert(x, this-&gt;root_);\n }\n};\n</code></pre>\n\n<p>Don't misunderstand me, Your code is useful and is pretty (is something good to read). But, manage things externally can be messy.</p>\n\n<p>Also, I recommend you to read the <a href=\"https://google.github.io/styleguide/cppguide.html\" rel=\"nofollow noreferrer\">Google C++ Code Style</a></p>\n\n<p>Hope it helped.</p>\n\n<h3>Edit: What does <code>const int&amp; x</code> means?</h3>\n\n<p><code>const int&amp; x</code> is a <em>constant reference</em> to a value of type <code>int</code> so, when you use it, your function does not <em>copy</em> the sent value, instead it \"sees where the value is allocated\" takes it in account and then starts the procedure you describe within the function, additionally you cannot modify that value (because it's constant [<code>const</code>])</p>\n\n<p><strong>the main difference is</strong> with <code>const [datatype]&amp;</code> you save space. With <code>[datatype] [paramName]</code> you Copy the value which implies allocate the copied value.</p>\n\n<p>If you feel lost in some part read it slowly it has many concepts, and remember practice makes this make sense.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T18:18:19.830", "Id": "470975", "Score": "1", "body": "I don't know if the poster is ready for object oriented programming yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T19:44:30.617", "Id": "470987", "Score": "0", "body": "Ok, I tried to understand your code with my poor knowledge and I understood the main idea. Avoid to write, like you said, functions alone (I imagine them without a sort of protection, if I get right). The code you wrote is sometimes hard to me to understand; for example I don't understand the use of virtual in \" virtual void Insert(const int &x, Node *node) \" , what does it mean exactly? I read about virtual function and I only understand that it can be useful when it is called for different derived class, but doesn't the obj type itself enough to get the right function? Hope I'm clear enough" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T19:52:10.177", "Id": "470989", "Score": "0", "body": "@Miguel Avila Also, I do not understand the Insert public function too. It received a const int& but then it calls another Insert function with different parameters. At last I don't fully understand the body of the constructor BinaryNode(Node *left, const int &label, Node *right). For example: what left_(left) does? It assign the \"left\" to left_ so that left_ point the same Node* as \"left\" ? Is it some sort of writing shortcut? Sorry about these many questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T21:52:37.890", "Id": "471006", "Score": "0", "body": "The public function is a \"facade\", it is because you will need to insert elements in your tree recursively but you want to hide that because you always will use the `root_` node for that purpose (inserting elements).\n\nAbout the constructor. `left_(left)` is the way you initialize `struct` and `class` members (attributes) here `left_` refers to the atribute of BinaryNode and `left` refers to the parameter you receive in the constructor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T11:48:14.550", "Id": "471039", "Score": "0", "body": "Ok now I almost fully understand the code, but I still don't get the \"virtual\" function (when these are necessary?) and never used a initializer list for the costructor. I will read more documentation on these things. Thanks for the effort to explain everything." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T17:50:14.647", "Id": "240109", "ParentId": "240098", "Score": "4" } }, { "body": "<p>Overall the code looks good and you seem to have some good programming habits. You need to try to use more of the features available in C++ and the STL.</p>\n\n<h2>Avoid <code>using namespace std;</code></h2>\n\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code>&lt;&lt;</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n\n<h2>Variable in Array Declarations</h2>\n\n<p>Using a strict C++ compiler the following code does not compile</p>\n\n<pre><code> int num = 7;\n int arr[num] = {120, 30, 115, 40, 50, 100, 70};\n</code></pre>\n\n<p><em>Use the std::vector container class. Most or all of the container of the container classes have a size() member that returns the number of items stored in the container. This means if you have to pass the array you only have to pass the container class and not the number of elements in the container.</em></p>\n\n<pre><code> std::vector&lt;int&gt; arr = {120, 30, 115, 40, 50, 100, 70};\n</code></pre>\n\n<p><em>If you insist on using old style C programming arrays you can get num after the initialization of the array.</em></p>\n\n<pre><code> int arr[] = {120, 30, 115, 40, 50, 100, 70};\n size_t num = sizeof(arr)/ sizeof(*arr);\n</code></pre>\n\n<p><em>Declare num as a constexpr.</em></p>\n\n<pre><code> constexpr size_t num = 7;\n int arr[num] = {120, 30, 115, 40, 50, 100, 70};\n</code></pre>\n\n<p>Prefer container classes over old C style arrays. They are easier to use, here's an example updating on of the functions in the code. Note that the `std::vector.size() function is not referenced in the following code.</p>\n\n<pre><code>void insertArrayTree(std::vector&lt;int&gt; arr, Node* &amp;tree) //insert the array integer into the nodes label of BST\n{\n for (int i: arr)\n {\n insertSearchNode(tree, i);\n }\n return;\n}\n</code></pre>\n\n<p>The above for loop is called a <a href=\"https://en.cppreference.com/w/cpp/language/range-for\" rel=\"nofollow noreferrer\">ranged for loop</a>.</p>\n\n<h2>Use Modern C++ Constructs</h2>\n\n<p>In several places in the code there is the assignment of <code>NULL</code> to pointers. In modern C++ <code>NULL</code> has been replaced by nullptr.</p>\n\n<pre><code>void insertSearchNode(Node* &amp;tree, int x) //insert integer x into the BST\n{\n if(!tree){\n tree = new Node;\n tree-&gt;label = x;\n tree-&gt;right = nullptr;\n tree-&gt;left = nullptr;\n return;\n }\n if(x &lt; tree-&gt;label) insertSearchNode(tree-&gt;left, x);\n if(x &gt; tree-&gt;label) insertSearchNode(tree-&gt;right, x);\n return;\n}\n</code></pre>\n\n<h2>Possible Bug</h2>\n\n<p>The above code does not handle the case where x is already in the tree, in large lists of values there may be duplicates.</p>\n\n<h2>Return from Main()</h2>\n\n<p>In a program as simple as this the <code>return 0;</code> statement is not necessary, the compiler will take care of it. The <code>return</code> statement is necessary when the program might exit due to failures <code>return ;</code>. In this case you would need both <code>return 1;</code> and <code>return 0;</code>. It would also be better in this case to include <code>cstdlib</code> and use <code>return EXIT_SUCCESS;</code> and <code>return EXIT_FAILURE;</code> to make the code more readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T19:05:34.943", "Id": "470981", "Score": "0", "body": "I will try to avoid the use of namespace. Thank you very much for the tips about the ranged for loop, I did not know about it at all. Then comes the vector structure; I am honestly afraid to use it because I never had the knowledge on how to use it properly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T19:11:57.823", "Id": "470983", "Score": "0", "body": "Convert this problem to vectors, then the link I shared for `ranged for` is a good place for C++ reference. Just keep trying." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T20:26:22.043", "Id": "470990", "Score": "0", "body": "I woudl add prefer to use `size_t num = std::size(arr)` rather than `size_t num = sizeof(arr)/ sizeof(*arr);`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T21:05:34.277", "Id": "470999", "Score": "0", "body": "@MartinYork Thank you, I will use that in the future if I need to." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T18:07:56.197", "Id": "240112", "ParentId": "240098", "Score": "2" } } ]
{ "AcceptedAnswerId": "240109", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T13:29:19.370", "Id": "240098", "Score": "3", "Tags": [ "c++", "beginner", "algorithm", "reinventing-the-wheel", "binary-search" ], "Title": "Sorting an array using a Binary Search Tree with C++" }
240098
<p>I'm a novice programmer. I started with Java years back and now mostly use VBA to automate tasks for my internships. I want to graduate from VBA and get into Python/R to properly automate tasks. The below code is my first Python project. I would like any of you to point out how it can be improved. </p> <p>The program is meant to take in a time in HH:MM format and print out at what degrees (from 12:00) each of the hands will be at. This was adapted from a common finance interview brainteaser guide.</p> <p>I'm thinking that if I get some good suggestions for this code I'll go ahead and make one that includes a second hand.</p> <pre><code>input_time = input("Please input a time (HH:MM)") time = input_time.split(":") clock_degrees = 360 clock_hours = 12 clock_minutes = 60 clock_degreesperhour = clock_degrees/clock_hours clock_degreesperminute = clock_degrees/clock_minutes miunte_hand_degrees = int(time[1])*clock_degreesperminute if (time[0] == "12"): time[0] = "0" hour_hand_degrees = (int(time[0])*clock_degreesperhour)+((int(time[1])/clock_minutes)*clock_degreesperhour) print("When the time is", input_time, 'the hour hand is at', hour_hand_degrees, "° and the minute hand is at", miunte_hand_degrees, "°") </code></pre>
[]
[ { "body": "<p>Currently your code has user input, calculation and output all mixed up. This is OK as a first step (your code works, yay!), but the next step should be separating the calculation from the IO part. For this a simple function which takes the input already as parsed numbers will do:</p>\n\n<pre><code>def clock_angles(hour, minute, second):\n \"\"\"Convert the time in hour, minute, second into angles of clock hands\n on a 12 hour clock, in degrees.\"\"\"\n if hour &gt;= 12:\n hour -= 12\n assert 0 &lt;= hour &lt; 12 and 0 &lt;= minute &lt; 60 and 0 &lt;= second &lt; 60\n degrees_per_hour = 360 / 12\n degrees_per_minute = degrees_per_second = 360 / 60\n return (hour * degrees_per_hour,\n minute * degrees_per_minute,\n second * degrees_per_second)\n</code></pre>\n\n<p>It even has a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\"><code>docstring</code></a> describing what it does and some simple input validation.</p>\n\n<p>Your IO can then be wrapped under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> which ensures it is not being run when you import from this script from another script. You can also use a <a href=\"https://realpython.com/python-f-strings/\" rel=\"noreferrer\"><code>f-string</code></a> to make formatting the output slightly easier.</p>\n\n<pre><code>if __name__ == \"__main__\":\n input_time = input(\"Please input a time (HH:MM:SS): \")\n hour, minute, second = map(int, input_time.split(\":\"))\n\n hour_angle, minute_angle, second_angle = clock_angles(hour, minute, second)\n print(f\"When the time is {input_time} the hour hand is at {hour_angle}°, the minute hand is at {minute_angle}° and the second hand is at {second_angle}°.\")\n</code></pre>\n\n<p>I included the second hand here. Being able to parse the input without the seconds is left as an exercise.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T14:35:31.727", "Id": "240101", "ParentId": "240100", "Score": "18" } }, { "body": "<p>One thing that is missing is <strong>validation of user input</strong>.</p>\n\n<p>If you omit the colon you get this: <code>IndexError: list index out of range</code>.\nIf you enter an invalid time like 25:99 you obviously get inconsistent results. There is no point trying to process invalid input.</p>\n\n<p>Fix: validate the input with a <strong>regular expression</strong> and capture values to hour and minute variables.</p>\n\n<p>Then, reuse those variables, rather than repeating <code>time[0]</code>, <code>time[1]</code>. Type casting (<code>int</code>) should then be done at the source as well. Don't repeat unnecessary operations.</p>\n\n<p>Proposed code:</p>\n\n<pre><code>import sys\nimport re\n\ninput_time = input(\"Please input a time (HH:MM): \")\n\nm = re.search(\"^(0[0-9]|1[0-9]|2[0-3]):?([0-5][0-9])$\", input_time)\nif m:\n hours = m.group(1)\n minutes = m.group(2)\nelse:\n print(\"Invalid time, try again\")\n sys.exit(0)\n\n# verification\nprint(f\"Hours: {hours}, minutes: {minutes}\")\n</code></pre>\n\n<p>To improve user experience, I have made the colon optional. Thus, 2359 will be treated like 23:59. This regex expects a leading zero in both minutes and hours, but you could change that. However if you decide the allow single digits, you will have to reintroduce the separator to avoid the ambiguity, because 01:08 can be expressed as 1:8 or 1:08 - without a separator you can't reliably tell hours from minutes.</p>\n\n<p>Regular expressions are a complex subject and a full explanation is beyond the scope of this review. In short this expression validates a time in the range 00:00 to 23:59, with or without colon separator. The parentheses delimit the <strong>capture groups</strong> while the question mark indicates that the preceding symbol (<code>:</code>) is optional.</p>\n\n<p>Note that there is a typo: <code>miunte_hand_degrees</code>. The danger would be that you assign another variable elsewhere in the code with the proper spelling (<code>minute_hand_degrees</code>) and you end up with two variables that are assigned different values, and you have introduced a bug in your program.</p>\n\n<p>I have not verified the algo.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T15:02:31.163", "Id": "471147", "Score": "3", "body": "`0[0-9]|1[0-9]` can be simplified to `[0-1][0-9]`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T15:39:51.363", "Id": "240104", "ParentId": "240100", "Score": "10" } } ]
{ "AcceptedAnswerId": "240101", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T14:12:15.047", "Id": "240100", "Score": "15", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Calculate the Degrees of a Clock Hand Based on Input Time" }
240100
<p>I have made a flashcard program. It opens a small window and displays a series of questions.</p> <p>Since I am new to programming, how can my code be improved?</p> <pre><code>from tkinter import * # This opening code is to create a window and menu options. I'm going for a # basic framework here in which everything else will fall under. def center_window(width=300, height=200): # get screen width and height screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() # calculate position x and y coordinates x = (screen_width/2) - (width/2) y = (screen_height/2) - (height/2) root.geometry('%dx%d+%d+%d' % (width, height, x, y)) def finished(): root.destroy() # Variables used throughout the code top_color = 'royalblue' bottom_color = 'lightsteelblue' background_color = 'navy' button_color = 'powderblue' card_num = 0 questions = [ 'Who is the first Pokemon?', 'Who is the first President?', 'What did MLK have?', 'Are you already dead?' ] answers = [ 'Mew', 'G. Washington', 'A dream', 'Yes' ] fanswers1 = [ 'Pikachu', 'T. Biggums', 'A thought', 'No' ] fanswers2 = [ 'Agumon', 'Big John', 'An idea', 'Perhaps' ] fanswers3 = [ 'Exodia', 'M. Robbins', 'A concept', 'Maybe' ] root = Tk() root.title('Flashcard Application') root.resizable(width=0, height=0) center_window(600, 350) root.configure(bg=background_color) # Makes sure the items in the root grid are stretched to capacity root.grid_rowconfigure(0, weight=3) root.grid_columnconfigure(0, weight=1) root.grid_rowconfigure(1, weight=1) def clicked_correct(): try: global card_num card_num += 1 question_label.configure(text=questions[card_num]) btn1.configure(text=answers[card_num]) btn2.configure(text=fanswers1[card_num]) btn3.configure(text=fanswers2[card_num]) btn4.configure(text=fanswers3[card_num]) except IndexError: finished() def clicked_incorrect(): question_label.configure(text='Incorrect. Try Again.') # Menu functions def res(): global card_num card_num = 0 question_label.configure(text=questions[0]) btn1.configure(text=answers[0]) btn2.configure(text=fanswers1[0]) btn3.configure(text=fanswers2[0]) btn4.configure(text=fanswers3[0]) # Menu bar options menu = Menu(root) reset = Menu(menu, tearoff=0) reset.add_command(label='Reset', command=res) menu.add_cascade(label='File', menu=reset) menu.add_command(label='Edit') root.config(menu=menu) # Creates root frame containers top_frame = Frame(root, bg=top_color, width=600, height=225) bottom_frame = Frame(root, bg=bottom_color, width=600, height=125) # Places root frame containers top_frame.grid(row=0, sticky='wens', padx=5, pady=(5, 0)) bottom_frame.grid(row=1, sticky='wens', padx=5, pady=5) # Makes sure items in the top frame grid are stretched to capacity top_frame.grid_rowconfigure(0, weight=1) top_frame.grid_columnconfigure(0, weight=1) # Creates top frame widgets question_label = Label(top_frame, bg=top_color, text=questions[card_num], font=('Arial Bold', 30)) # Place top frame widgets question_label.grid(row=0, column=0) # Makes sure items in bottom frame grid are stretched to capacity bottom_frame.grid_rowconfigure(0, weight=1) bottom_frame.grid_rowconfigure(1, weight=1) bottom_frame.grid_columnconfigure(0, weight=1) bottom_frame.grid_columnconfigure(1, weight=1) # Creates bottom widgets btn1 = Button(bottom_frame, text=answers[card_num], bg=button_color, command=clicked_correct) btn2 = Button(bottom_frame, text=fanswers1[card_num], bg=button_color, command=clicked_incorrect) btn3 = Button(bottom_frame, text=fanswers2[card_num], bg=button_color, command=clicked_incorrect) btn4 = Button(bottom_frame, text=fanswers3[card_num], bg=button_color, command=clicked_incorrect) # Place top frame widgets btn1.grid(row=0, column=0) btn2.grid(row=0, column=1) btn3.grid(row=1, column=0) btn4.grid(row=1, column=1) root.mainloop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T16:00:00.677", "Id": "470962", "Score": "2", "body": "This has accumulated a close vote for having an incomplete description. Personally I think it's fine, however you may want to flesh out what flash cards and Anki are. At first I thought you were building a deck builder game. Best of luck." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T15:53:21.747", "Id": "471057", "Score": "1", "body": "Your edit 23 hours ago didn't add information about what your code is doing, it removed most of the explanation. Please don't fill up questions with the fact you want a review, we know that since you've posted a question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T16:27:40.150", "Id": "471066", "Score": "0", "body": "If this is a learning/student project that's fine. If you're expecting a future user base, have you considered building on Anki instead of reinventing the wheel? https://en.wikipedia.org/wiki/Anki_(software)" } ]
[ { "body": "<h2>Namespace pollution</h2>\n\n<p>It's usually a bad idea to do this:</p>\n\n<pre><code>from tkinter import *\n</code></pre>\n\n<p>This forces every bell and whistle from <code>tkinter</code> to be imported. Instead, either</p>\n\n<ul>\n<li><code>import tkinter as tk</code>, or</li>\n<li><code>from tkinter import Tk, ...</code> if you aren't importing a lot of symbols.</li>\n</ul>\n\n<h2>Order of operations</h2>\n\n<p>The parens here:</p>\n\n<pre><code>x = (screen_width/2) - (width/2)\ny = (screen_height/2) - (height/2)\n</code></pre>\n\n<p>can all be dropped.</p>\n\n<h2>String interpolation</h2>\n\n<pre><code>root.geometry('%dx%d+%d+%d' % (width, height, x, y))\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>root.geometry(f'{width}x{height}+{x}+{y}')\n</code></pre>\n\n<h2>Constants</h2>\n\n<p>These are good to remain in global scope but should be capitalized:</p>\n\n<pre><code>top_color = 'royalblue'\nbottom_color = 'lightsteelblue'\nbackground_color = 'navy'\nbutton_color = 'powderblue'\n</code></pre>\n\n<h2>Global code</h2>\n\n<p>These statements should be pulled into one or more functions:</p>\n\n<pre><code>root = Tk()\nroot.title('Flashcard Application')\nroot.resizable(width=0, height=0)\ncenter_window(600, 350)\nroot.configure(bg=background_color)\n# Makes sure the items in the root grid are stretched to capacity\nroot.grid_rowconfigure(0, weight=3)\nroot.grid_columnconfigure(0, weight=1)\nroot.grid_rowconfigure(1, weight=1)\n\n# ...and everything after\n# Menu bar options\n</code></pre>\n\n<h2>Immutable sequences</h2>\n\n<p>Your <code>questions</code>, etc. are immutable, so make them tuples, not lists.</p>\n\n<h2>Computers are good at loops</h2>\n\n<pre><code># Creates bottom widgets\nbtn1 = Button(bottom_frame, text=answers[card_num], bg=button_color, command=clicked_correct)\nbtn2 = Button(bottom_frame, text=fanswers1[card_num], bg=button_color, command=clicked_incorrect)\nbtn3 = Button(bottom_frame, text=fanswers2[card_num], bg=button_color, command=clicked_incorrect)\nbtn4 = Button(bottom_frame, text=fanswers3[card_num], bg=button_color, command=clicked_incorrect)\n\n# Place top frame widgets\nbtn1.grid(row=0, column=0)\nbtn2.grid(row=0, column=1)\nbtn3.grid(row=1, column=0)\nbtn4.grid(row=1, column=1)\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>for ans, command, row, col in (\n (answer, clicked_correct, 0, 0),\n (fanswers1, clicked_incorrect, 0, 1),\n (fanswers2, clicked_incorrect, 1, 0),\n (fanswers3, clicked_incorrect, 1, 1),\n):\n btn = Button(bottom_frame, text=ans[card_num], bg=button_color, command=command)\n btn.grid(row=row, column=col)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T18:17:28.873", "Id": "470974", "Score": "0", "body": "I appreciate your help. This will definitely save me time in the future and I'm looking forward to developing better habits with your advice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T04:14:54.843", "Id": "471022", "Score": "6", "body": "While the parens _can_ be dropped, I don't think they _should_ be dropped. Parens add clarity. This is especially important for people just now learning the language as it helps them to show what they intend. As a reviewer, if I see an expression without parenthesis I usually have to slow down and read it more closely to make sure the expression is correct. When I see parenthesis I don't have to guess as to what the author intended." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T04:18:06.403", "Id": "471023", "Score": "2", "body": "Your \"computers are good at loops\" advice is good, but in this case you've swapped 8 exceptionally clear lines of code with 8 lines of code that require a bit more time to understand." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T12:57:15.110", "Id": "471042", "Score": "0", "body": "Re. parens: I'll agree to disagree. Proper use of whitespace (as has already been done) along with elementary-school math makes the author's intent more than clear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T16:57:48.647", "Id": "471069", "Score": "0", "body": "You seem to assume people remember \"elementary-school math\". I've reviewed enough code in my career to know that's not always the case." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T17:51:32.897", "Id": "240110", "ParentId": "240106", "Score": "5" } }, { "body": "<p>First off, it's fantastic that you're grouping your widgets together when you create them, and then grouping your calls to <code>grid</code> together. Most people who are starting to learn tkinter don't do that. The way you've done it makes the code much easier to understand than if you mixed it all together.</p>\n\n<h2>Don't use wildcard imports</h2>\n\n<p>Wildcard imports are discouraged by <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>. Instead, I recommend doing imports like this:</p>\n\n<pre><code>import tkinter as tk\n</code></pre>\n\n<p>You will then have to change all of the code that references classes, functions, and constants to include the prefix <code>tk.</code> (eg: <code>root = tk.Tk()</code>)</p>\n\n<p>This has two advantages: it helps keep the global namespace from getting too large (which can lead to difficult-to-spot problems), and it makes the fact that you're using tk explicit. This is especially important if you also import ttk, as both tk and ttk have classes with the same name (<code>Button</code>, <code>Label</code>, etc).</p>\n\n<h2>Use a data structure that links questions with answers</h2>\n\n<p>Imagine if you had 100 questions, and you needed to change the answer or a false answer to question 77. You would have to manually count down 77 lines in one of the lists and hope you didn't miscount. Even worse, what if you decide to re-order all of your questions and answers? It could take you all day to reorganize the data.</p>\n\n<p>Instead, a simple technique is to use a dictionary where the keys are the questions and the values are a list of answers. You could always put the correct answer as the first item in the list. </p>\n\n<p>Dictionaries have a way to iterate over the values by key, so you can easily step over the flash cards in the order they are defined, or in sorted order, or in random order, or in any other way you see fit.</p>\n\n<p>For example:</p>\n\n<pre><code>flashcards = {\n \"Who is the first pokemon?\": [\n \"Mew\", \"Pikachu\", \"Agumon\", \"Exodia\",\n ],\n \"Who is the first president?\": [\n \"G. Washington\", \"T.Biggums\", \"Big John\", \"M.Robbins\",\n ],\n \"What did MLK have?\": [\n \"A dream\", \"A thought\", \"An idea\", \"A concept\",\n ],\n \"Are you already dead?\": [\n \"Yes\", \"No\", \"Perhaps\", \"Maybe\",\n ]\n}\n...\n</code></pre>\n\n<p>Another alternative would be to use a list of lists, if you want to keep your current logic that depends on the question index.</p>\n\n<p>For example, </p>\n\n<pre><code>flashcards = [\n [\"Who is the first pokemon?\", \"Mew\", \"Pikachu\", \"Agumon\", \"Exodia\"],\n [\"Who is the first president?\", ...],\n ...\n]\n</code></pre>\n\n<p>Even better would be to define a <code>Flashcard</code> class, but I don't know if you're familar with classes yet.</p>\n\n<h2>Create a main function</h2>\n\n<p>I recommend putting the main application inside a function. Call it <code>main</code> (or anything else, but <code>main</code> will be instantly recognizable by most programmers). Then, call <code>main()</code> as the last step in the file.</p>\n\n<p>For example:</p>\n\n<pre><code>def main():\n global root\n\n root = Tk()\n root.title('Flashcard Application')\n root.resizable(width=0, height=0)\n center_window(600, 350)\n root.configure(bg=background_color)\n # Makes sure the items in the root grid are stretched to capacity\n root.grid_rowconfigure(0, weight=3)\n root.grid_columnconfigure(0, weight=1)\n root.grid_rowconfigure(1, weight=1)\n\n... the rest of your function definitions ...\n\nif __name__ == \"__main__\":\n main()\n# end of the file\n</code></pre>\n\n<p>This last condition (<code>if __name__ == \"__main__\"</code>) is a common python trick which lets you import this file as a library, or use it as a script. Why is that important? It makes your code more portable, but more importantly, it makes the code more <em>testable</em>. You more easily write unit tests that can load up all of your functions and test them independently of the main program.</p>\n\n<p>While testability isn't terribly important in such a small program, this is a good habit to form.</p>\n\n<p>For more information see <a href=\"https://stackoverflow.com/q/419163/7432\">https://stackoverflow.com/q/419163/7432</a></p>\n\n<h2>Move all of the other code into functions too</h2>\n\n<p>A good rule of thumb is to have almost no code running in the global scope. While that's not overly important for such a small script, it's good to get into the habit of organizing your code into functions.</p>\n\n<p>So, perhaps create a function called <code>create_ui</code> with all of the other tkinter code. Or, create a couple of functions such as <code>create_menubar</code> and <code>create_main_ui</code> or something like that. </p>\n\n<p>This will help you to be more explicit about your use of global variables, and to think about how code logically groups together. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T18:14:58.477", "Id": "470973", "Score": "0", "body": "Thank you so much! I appreciate your effort. This is exactly the feedback I was looking for and I will begin implementing these better habits immediately and in the future." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T03:59:15.980", "Id": "471021", "Score": "2", "body": "The other advantage to organizing your questions and answers into data objects is you can then randomize the question order. Which from a pedagogy perspective will keep people from memorizing the click through order. But also gives you a challenge you can move forward with to learn more and improve your code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T17:51:59.503", "Id": "240111", "ParentId": "240106", "Score": "12" } }, { "body": "<p>This is my revision using the advice found here.\nThe flashcards themselves are not as easily displayed yet, but I'm going to figure that out later.</p>\n\n<pre><code># Begin coding\nfrom tkinter import Tk, Menu, Button, Label, Frame\n\ncard_num = 0\n\n\ndef main():\n # Use this function to create root window\n background_color = 'navy'\n root = Tk()\n root.title('Flashyr')\n root.resizable(0, 0)\n root.configure(bg=background_color)\n # Makes sure the items in the root grid are stretched to capacity\n root.grid_rowconfigure(0, weight=3)\n root.grid_columnconfigure(0, weight=1)\n root.grid_rowconfigure(1, weight=1)\n\n def center_window(width=300, height=200):\n # get screen width and height\n screen_width = root.winfo_screenwidth()\n screen_height = root.winfo_screenheight()\n\n # calculate position x and y coordinates\n x = (screen_width / 2) - (width / 2)\n y = (screen_height / 2) - (height / 2)\n root.geometry('%dx%d+%d+%d' % (width, height, x, y))\n\n def clicked_incorrect():\n question_label.configure(text='Incorrect. Try Again.')\n\n def clicked_correct():\n try:\n global card_num\n card_num += 1\n question_label.configure(text=c_l[card_num][card_num])\n btn2.configure(text=c_l[card_num][card_num])\n btn1.configure(text=c_l[card_num][card_num])\n btn3.configure(text=c_l[card_num][card_num])\n btn4.configure(text=c_l[card_num][card_num])\n except IndexError:\n root.destroy()\n\n def menu_bar():\n # Menu bar options\n menu = Menu(root)\n reset = Menu(menu, tearoff=0)\n\n # Menu functions\n def res():\n global card_num, btn1, btn2, btn3, btn4, question_label\n card_num = 0\n question_label.configure(text=c_l[0][0])\n btn1.configure(text=c_l[0][0])\n btn2.configure(text=c_l[0][0])\n btn3.configure(text=c_l[0][0])\n btn4.configure(text=c_l[0][0])\n\n reset.add_command(label='Reset', command=res)\n menu.add_cascade(label='File', menu=reset)\n\n menu.add_command(label='Edit')\n root.config(menu=menu)\n\n def top():\n global question_label\n top_color = 'royalblue'\n # Creates/place root container\n top_frame = Frame(root, bg=top_color, width=600, height=225)\n top_frame.grid(row=0, sticky='wens', padx=5, pady=(5, 0))\n top_frame.grid_rowconfigure(0, weight=1)\n top_frame.grid_columnconfigure(0, weight=1)\n\n # Place top frame widgets\n question_label = Label(top_frame, bg=top_color, text='Hello World', font=('Arial Bold', 30))\n question_label.grid(row=0, column=0)\n\n def bottom():\n bottom_color = 'lightsteelblue'\n bottom_frame = Frame(root, bg=bottom_color, width=600, height=125)\n bottom_frame.grid(row=1, sticky='wens', padx=5, pady=5)\n bottom_frame.grid_rowconfigure(0, weight=1)\n bottom_frame.grid_rowconfigure(1, weight=1)\n bottom_frame.grid_columnconfigure(0, weight=1)\n bottom_frame.grid_columnconfigure(1, weight=1)\n\n def buttons():\n global btn1, btn2, btn3, btn4\n button_color = 'blue'\n button_color_active = 'light blue'\n\n # Creates bottom widgets\n btn1 = Button(bottom_frame, text=c_l[card_num][card_num], bg=button_color,\n activebackground=button_color_active, command=clicked_correct)\n btn2 = Button(bottom_frame, text=c_l[0][card_num], bg=button_color,\n activebackground=button_color_active, command=clicked_incorrect)\n btn3 = Button(bottom_frame, text=c_l[0][card_num], bg=button_color,\n activebackground=button_color_active, command=clicked_incorrect)\n btn4 = Button(bottom_frame, text=c_l[0][card_num], bg=button_color,\n activebackground=button_color_active, command=clicked_incorrect)\n\n # Place top frame widgets\n btn1.grid(row=0, column=0)\n btn2.grid(row=0, column=1)\n btn3.grid(row=1, column=0)\n btn4.grid(row=1, column=1)\n buttons()\n\n top()\n bottom()\n center_window(600, 350)\n menu_bar()\n root.mainloop()\n\n\nclass Flashcard:\n def __init__(self, q, a, x, y, z, num):\n self.q = q\n self.a = a\n self.x = x\n self.y = y\n self.z = z\n self.num = num\n\n\nc_l = [\n ['What is my first name?', 'Robert', 'Bobert', 'Trebor', 'Bortre'],\n ['What is my middle name?', 'James', 'Ames', 'Semaj', 'Majse'],\n ['What is my last name?', 'Johnson', 'Sonjohn', 'Johnston', 'Smith'],\n ['What is my suffix?', 'III', 'IV', 'PhD', 'Esq']\n]\n\ncard1 = Flashcard(q=c_l[0][0], a=c_l[0][1], x=c_l[0][2], y=c_l[0][3], z=c_l[0][4], num=1)\ncard2 = Flashcard(q=c_l[1][0], a=c_l[1][1], x=c_l[1][2], y=c_l[1][3], z=c_l[1][4], num=2)\n\nif __name__ == '__main__':\n main()\n# end of file\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T22:14:28.087", "Id": "240234", "ParentId": "240106", "Score": "1" } } ]
{ "AcceptedAnswerId": "240111", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T15:51:17.527", "Id": "240106", "Score": "10", "Tags": [ "python", "beginner", "tkinter" ], "Title": "Python Flashcards" }
240106
<p>I've written a short web scraper in Lua (run in LuaJIT for speed) to download every post from a specific forum (not general purpose... yet). It takes about 12 hours to run and download 500,000 posts and there are no errors. I'm wondering how I can make it faster. I know different places where the code can be <em>better</em> in readability and structure, but not how it could be better in speed.</p> <pre><code>local https = require("ssl.https") local tcount, pcount = 0,0 local threads = {} local posts = {} local root = --the forum url local output = io.open("output.txt", "a") function scrape(address, p) local request_body = [[]] local response_body = {} local res, code, response_headers = https.request{ url = address, method = "GET", source = ltn12.source.string(request_body), sink = ltn12.sink.table(response_body), } if res ~= 1 or code ~= 200 then print(res, code) end if type(response_headers) == "table" and p then --if the function is called with a p param, print the response headers for k,v in pairs(response_headers) do print(k, v) end end if code == 301 then print("Location", response_headers["location"]) end if type(response_body) == "table" then response_body = table.concat(response_body) --every response in this instance is a table, so I would probably be able to take out this if statement. else print("Not a table:", type(response_body)) end return response_body end function parse_posts(response_body) for match in string.gmatch(response_body, '&lt;div class="post%-body"&gt;.-&lt;/div&gt;') do local m = string.gsub(match, '&lt;span class="quote%-attr"&gt;.-&lt;/span&gt;', ""):gsub([[&lt;/?[^&gt;q]+&gt;]], ""):gsub("\n", "&lt;br&gt;") output:write(m..'\n') pcount = pcount+1 end end function get_threads(response_body) string.gsub(response_body, [[&lt;a href="(/%d+/[^"]+)" class="title"]], function (m) local d = tonumber(m:match("%d+")) threads[d] = root..m end) end function get_pages(response_body, url) local p = 0 string.gsub(response_body, [[class="btn mod%-page"&gt;(%d+)&lt;/a&gt;]], function (m) if tonumber(m) &gt; p then p = tonumber(m) end end) for i = p, 1, -1 do parse_posts(scrape(url.."/?page="..tostring(i))) --print("Scraping", url.."/?page="..tostring(i)) end end do print("Getting threads") for i = 1528, 1, -1 do local url = root .. '/threads/?page='..tostring(i) get_threads(scrape(url)) end end do print("Getting pages on each thread") for id,url in pairs(threads) do print("Writing for id", id) if id ~= 1121 and id ~= 1217 and id ~= 441 then --exclude three specific large threads, i intend to remove this next iteration in favor of just removing them: threads[1121] = nil, but i do not believe that will improve speed at all. get_pages(scrape(url), url) end tcount = tcount+1 end end print(string.format("Finished scraping %d posts across %d threads.", pcount, tcount)) output:close() <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T21:11:51.157", "Id": "471000", "Score": "0", "body": "Would the user that voted down on this question please indicate in a comment why they voted down." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-30T12:56:49.483", "Id": "477220", "Score": "0", "body": "Out of interest how long does it take you to download an equivalent amount of data on your internet connection? I haven't looked at your code, but wonder if you may be optimising at the wrong side of a bottleneck" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-30T17:46:55.300", "Id": "477235", "Score": "0", "body": "The entire txt post of everything I downloaded was like 120 MB, my internet DL speed is 73 Mbps, without doing the math, that definitely doesn't add to 12 hr run time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T07:43:59.790", "Id": "494426", "Score": "0", "body": "Have you tried benchmarking the different sections of the program? (downloading vs. parsing, mostly)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T05:15:44.183", "Id": "494509", "Score": "0", "body": "@DarkWiiPlayer I did not. I probably would try it but its been 6 months and I've lost interest / had no need of the project since I originally wrote it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T19:14:58.463", "Id": "240115", "Score": "2", "Tags": [ "performance", "web-scraping", "lua" ], "Title": "Forum web scraper in Lua" }
240115
<p>In my Player.java class, I want to incorporate a function that moves my player according to the left or right swipes. I also used time in seconds in order to vary the movement in an cyclic way:</p> <pre><code>''' class MyGestureDetector extends SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-4:00")); Date currentLocalTime = cal.getTime(); DateFormat date = new SimpleDateFormat("KK:mm"); date.setTimeZone(TimeZone.getTimeZone("GMT-4:00")); String localTime = date.format(currentLocalTime); try { if (Math.abs(e1.getY() - e2.getY()) &gt; SWIPE_MAX_OFF_PATH) return false; // right to left swipe if(e1.getX() - e2.getX() &gt; SWIPE_MIN_DISTANCE &amp;&amp; Math.abs(velocityX) &gt; SWIPE_THRESHOLD_VELOCITY) { X-=K; int currentSeconds = cal.get(Calendar.SECOND); Y=Y*Math.cos(18.currentSeconds); } else if (e2.getX() - e1.getX() &gt; SWIPE_MIN_DISTANCE &amp;&amp; Math.abs(velocityX) &gt; SWIPE_THRESHOLD_VELOCITY) { X+=K; int currentSeconds = cal.get(Calendar.SECOND); Y=Y*Math.cos(18.currentSeconds); } } catch (Exception e) { // nothing } return false; } ''' </code></pre> <p>After some research, this is the class I included in player.java. So my question is: Is there a more efficient way to detect swiping directions(without creating any additional class) and what is your opinion about the code structure knowing that the objective is to change X according to swipe direction.</p> <p>Thank you.</p>
[]
[ { "body": "<p>I changed some local variables and make them static variables, why ? because these are created and destroyed if you use serveral times the method <code>onFling</code>. The main Idea is to improve the performance and decrease the space your method uses.</p>\n\n<p>Also I refactorized some pieces of code </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>class MyGestureDetector extends SimpleOnGestureListener {\n private static DateFormat date = new SimpleDateFormat(\"KK:mm\");\n private static Calendar cal; \n\n MyGestureDetector() {\n date.setTimeZone(TimeZone.getTimeZone(\"GMT-4:00\"));\n }\n\n @Override\n public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {\n cal = Calendar.getInstance(TimeZone.getTimeZone(\"GMT-4:00\"));\n String localTime = date.format(cal.getTime());\n try {\n if (Math.abs(e1.getY() - e2.getY()) &gt; SWIPE_MAX_OFF_PATH)\n return false;\n // right to left swipe\n if(e1.getX() - e2.getX() &gt; SWIPE_MIN_DISTANCE &amp;&amp; Math.abs(velocityX) &gt; SWIPE_THRESHOLD_VELOCITY) {\n X -= K;\n Y *= Math.cos(18*cal.get(Calendar.SECOND)); //18 * currentSeconds i think\n } else if (e2.getX() - e1.getX() &gt; SWIPE_MIN_DISTANCE &amp;&amp; Math.abs(velocityX) &gt; SWIPE_THRESHOLD_VELOCITY) {\n X += K;\n Y *= Math.cos(18*cal.get(Calendar.SECOND));\n }\n } catch (Exception e) {\n // Perhaps if the program does nothing or have an unexpected behavior\n // you are silencing the cause (it has happened to me)\n e.printStackTrace();\n }\n return false;\n }\n</code></pre>\n\n<p>Hope it helped.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T22:43:04.953", "Id": "240121", "ParentId": "240116", "Score": "1" } } ]
{ "AcceptedAnswerId": "240121", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T19:54:20.477", "Id": "240116", "Score": "2", "Tags": [ "java", "android" ], "Title": "moving player right or left depending on swipe" }
240116
<p>I wrote the following C++ code and since I am a novice in C++ and do not really have anybody who can give me advice, I think this site would be a good place to ask. </p> <p>The algorithm takes the first two elements <code>a1</code> and <code>a2</code> of an array, calculate the difference <code>a2 - a1</code>. Then the first two elements <code>a1</code> and <code>a2</code> will be removed from the array and the calculated difference will be inserted in front of the array. This will be repeated until there is only one element left. The last element of the array will be the hash value of the array. </p> <p>The initial array will be mutated <code>q</code> times with the following formula: <code>increase all elements in the segment [lj,rj] by vj</code>, after each mutation the hash value should be printed.</p> <p>The input will look something like following </p> <pre><code>7 4 2 -5 10 4 -2 6 4 2 4 -8 5 7 2 3 3 -1 3 7 3 </code></pre> <p>where the first line indicates the length of the array. The next line will be the content of the array, the third line would be <code>q</code> and every following line is <code>lj, rj, vj</code>.</p> <p>This is how my code looks like at the moment. I would appreciate every critic.</p> <pre><code>#include &lt;vector&gt; #include &lt;iostream&gt; #define ll long long ll __hash__(const std::vector&lt;int&gt; &amp;arr) { ll front = arr[0]; for(ll i = 1; i &lt; arr.size(); i++){ front = arr[i] - front; } return front; } int main() { std::vector&lt;int&gt; arr; ll size; std::cin &gt;&gt; size; for (ll i = 0; i &lt; size; ++i) { ll c; std::cin &gt;&gt; c; arr.push_back(c); } ll q; std::cin &gt;&gt; q; for (ll i = 0; i &lt; q; ++i) { ll l, r, v; std::cin &gt;&gt; l &gt;&gt; r &gt;&gt; v; for(ll j = l - 1; j &lt; r; ++j){ arr[j] += v; } std::cout &lt;&lt; __hash__(arr) &lt;&lt; std::endl; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T23:05:11.243", "Id": "471009", "Score": "2", "body": "You are briteforcing. Once the initial hash is computed, the subsequent queries shall be answered in constant time. Hint: pay attention to the parities of `rj - lj` and `n - rj`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T23:08:54.490", "Id": "471010", "Score": "0", "body": "@vnp well that is a great hint." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T11:45:15.657", "Id": "471127", "Score": "0", "body": "Do I understand it correctly if I say that `[1,2,3]` will have the same hash value as `[2,4]`?" } ]
[ { "body": "<h2>The Good</h2>\n\n<p>The code is fairly readable, horizontal spacing is good.</p>\n\n<p>The variables are declared as they are needed.</p>\n\n<p>You didn't use <code>using namespace std;</code> which is very good for a beginner.</p>\n\n<h2>Macros in C++</h2>\n\n<p>Macros are included in C++ to support some backward compatibility with the C programming language that it grew out of, but they generally aren't used in C++ because they aren't type safe. Replacements for macros are inline functions, and lambda expressions or closures.</p>\n\n<p>An alternate to what is in the code is to use <code>typedef</code>. A second alternative is to use <code>using ll = long long;</code>.</p>\n\n<p>The best thing might be to find what types C++ supports and use that instead. You can find a list of the types provided by the <code>cstdint</code> header file <a href=\"https://en.cppreference.com/w/cpp/header/cstdint\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Another alternative is to just use <code>long long</code> rather than shortening it. C++ is not a scripting language and C++ coders are used to things like this.</p>\n\n<h2>Beginning a Variable or Function with Double Underscore.</h2>\n\n<p>Function names and variables should start with letters rather than underscores, double underscore is reserved for special usage.</p>\n\n<h2>Variable Names</h2>\n\n<p>Single letter variable names make the code very hard to understand, I don't even have a clue what <code>c</code>, <code>q</code>, <code>l</code>, <code>r</code> or <code>v</code> are or I would try to guess at their meanings.</p>\n\n<p>Variables <code>i</code> and <code>j</code> are used as indexes into the vector, it would be better if these variables were of type <code>size_t</code> rather than <code>long long</code> because <code>size_t</code> is defined as unsigned and can't be negitive. It would very rare to have an array or vector that would require the address space of a <code>long long</code>.</p>\n\n<h2>One Variable Declaration Per Line</h2>\n\n<p>The code contains this line</p>\n\n<pre><code> ll l, r, v;\n</code></pre>\n\n<p>To make the code more maintainable each variable should be declared and initialized on it's own line.</p>\n\n<pre><code> ll l = 0;\n ll r = 0;\n ll v = 0;\n</code></pre>\n\n<h2>Vertical Spacing</h2>\n\n<p>To make the code more readable it needs some vertical spacing, one line between logical blocks:</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;iostream&gt;\n\nusing ll = long long;\n\nll __hash__(const std::vector&lt;int&gt; &amp;arr) {\n ll front = arr[0];\n for(ll i = 1; i &lt; arr.size(); i++){\n front = arr[i] - front;\n }\n return front;\n}\n\nint main() {\n std::vector&lt;int&gt; arr;\n\n ll size;\n std::cin &gt;&gt; size;\n for (ll i = 0; i &lt; size; ++i) {\n ll c;\n std::cin &gt;&gt; c;\n arr.push_back(c);\n }\n\n ll q;\n std::cin &gt;&gt; q;\n for (size_t i = 0; i &lt; q; ++i) {\n ll l, r, v;\n std::cin &gt;&gt; l &gt;&gt; r &gt;&gt; v;\n for(size_t j = l - 1; j &lt; r; ++j){\n arr[j] += v;\n }\n std::cout &lt;&lt; __hash__(arr) &lt;&lt; std::endl;\n }\n\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T09:22:50.310", "Id": "471032", "Score": "1", "body": "Thank you, those are some tips I could really need" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T13:39:45.500", "Id": "471130", "Score": "0", "body": "1. It will be good if every \"{\" goes to next or new line.\n2. using intList = std::vector<int>;" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T14:56:43.860", "Id": "471143", "Score": "0", "body": "@Mannoj Yes, but that is a style issue generally covered in a style guide." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T16:20:43.333", "Id": "471149", "Score": "0", "body": "Ok, but it's also help readability" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T00:10:03.077", "Id": "240126", "ParentId": "240117", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T21:55:51.737", "Id": "240117", "Score": "3", "Tags": [ "c++", "performance", "beginner" ], "Title": "Optimizing performance of hashing array algorithm's implementation" }
240117
<p>I have to find where a given string is in my multidimensional array. So this is my array</p> <pre><code>$input = array(array('time' =&gt; '18:31:00', 'artist' =&gt; 'LUIS RODRIGUEZ &amp; DEN HARROW'), array('time' =&gt; '18:32:00', 'artist' =&gt; 'J BALVIN'), array('time' =&gt; '18:33:00', 'artist' =&gt; 'THE BLACK EYED PEAS FT J BALVIN'), array('time' =&gt; '18:34:00', 'artist' =&gt; 'THE BLACK EYED PEAS FT J BALVIN'), array('time' =&gt; '18:35:00', 'artist' =&gt; 'J BALVIN')); </code></pre> <p>I have to find at what time I can find this</p> <pre><code>$artista_inserito = 'THE BLACK EYED PEAS FT J BALVIN'; </code></pre> <p>So I use a function to delimiter my array and even string</p> <pre><code>function multiexplode($delimiters, $string) { $ready = str_replace($delimiters, $delimiters[0], $string); $launch = explode($delimiters[0], $ready); return $launch; } // array with string delimeter $array_delimiter_artisti = array(' FEAT ', ' feat ', ' FT ', ' ft ', ' + ', ' AND ', ' and ', ' E ', ' e ', ' VS ', ' vs ', ' FEAT. ', ' feat. ', ' FT. ', ' ft. ', ' VS. ', ' vs. ', ' , ', ' &amp; '); // I split the current artist $artisti_inseriti = multiexplode($array_delimiter_artisti, $artista_inserito); </code></pre> <p>So I search the given string un my array</p> <pre><code>foreach ($input as $split) { $time = $split['time']; $artist = $split['artist']; $lista_artisti = multiexplode($array_delimiter_artisti, $artist); foreach ($lista_artisti as $nuovo) { $artista_split = $nuovo; // copy all new data in new array $nuovo_array_dati[] = array('time' =&gt; $time, 'artist' =&gt; $artista_split); } } foreach ($nuovo_array_dati as $controllo) { $time = $controllo['time']; $artist = $controllo['artist']; foreach ($artisti_inseriti as $trova_artista) { $artista_singolo = $trova_artista; foreach ($controllo as $index =&gt; $a) { if (strstr($a, $artista_singolo)) { // now I can print where I found the given string $artista_inserito echo "$artista_singolo is at $time "; } } } } </code></pre> <p>So this is my output</p> <pre><code>J BALVIN is at 18:32:00 THE BLACK EYED PEAS is at 18:33:00 J BALVIN is at 18:33:00 THE BLACK EYED PEAS is at 18:34:00 J BALVIN is at 18:34:00 J BALVIN is at 18:35:00 </code></pre> <p>Can I improve this? Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T00:09:40.700", "Id": "471014", "Score": "0", "body": "Merely splitting on whitespaces may not be a reliable way to search the haystacks with the generated needles. I feel like this topic has been reviewed before. https://codereview.stackexchange.com/q/178870/141885 Also, according to the php documentation, it is not advised to use `strstr()` to check the existence of a substring in a string -- using `strpos()` is a better performer. I don't see any reason to check the time column's data. Why do you only use the first element of `$array_delimiter_artisti`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T07:20:04.793", "Id": "471028", "Score": "1", "body": "@mickmackusa Please don't use duplicates like this on Code Review. Our policy on duplicates [is a bit different from other Q&A sites](https://codereview.meta.stackexchange.com/a/3821/52915)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T08:46:34.967", "Id": "471031", "Score": "0", "body": "@mickmackusa I have to log at what time there is the same artist, so I have to check also the time" } ]
[ { "body": "<p>I have a bias <em>toward</em> regex because I'm generally comfortable with most techniques, so I'll recommend condensing your array of delimiters into a single regex pattern and employ <code>preg_split()</code> to execute the explosion.</p>\n\n<p>After splitting the search string into its separate artists, I am flipping the values &amp; keys to optimize the lookup for later use in the nested loop.</p>\n\n<p>Then as you iterate the haystack of artist times, you can re-use the splitting pattern, then iterate each individual artist and store the desired data for qualifying rows.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/bRaJl\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$fullArtistTimes = [\n ['time' =&gt; '18:31:00', 'artist' =&gt; 'LUIS RODRIGUEZ &amp; DEN HARROW'],\n ['time' =&gt; '18:32:00', 'artist' =&gt; 'J BALVIN'],\n ['time' =&gt; '18:33:00', 'artist' =&gt; 'THE BLACK EYED PEAS FT J BALVIN'],\n ['time' =&gt; '18:34:00', 'artist' =&gt; 'THE BLACK EYED PEAS FT J BALVIN'],\n ['time' =&gt; '18:35:00', 'artist' =&gt; 'J BALVIN']\n];\n\n$fullArtist = 'THE BLACK EYED PEAS FT J BALVIN';\n\n$artistDelimiters = '~ (?:[+e,&amp;]|and|f(?:ea)?t\\.?|vs\\.?) ~i';\n\n$artists = array_flip(preg_split($artistDelimiters, $fullArtist));\n\n$result = [];\nforeach ($fullArtistTimes as $row) {\n foreach (preg_split($artistDelimiters, $row['artist']) as $artist) {\n if (isset($artists[$artist])) {\n $result[] = \"{$artist} is at {$row['time']}\";\n }\n }\n}\n\nvar_export($result);\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>array (\n 0 =&gt; 'J BALVIN is at 18:32:00',\n 1 =&gt; 'THE BLACK EYED PEAS is at 18:33:00',\n 2 =&gt; 'J BALVIN is at 18:33:00',\n 3 =&gt; 'THE BLACK EYED PEAS is at 18:34:00',\n 4 =&gt; 'J BALVIN is at 18:34:00',\n 5 =&gt; 'J BALVIN is at 18:35:00',\n)\n</code></pre>\n\n<p>If this does not work for all of your cases, then I would need to see more test cases and your desired result before I could properly adjust my snippet.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T16:00:05.920", "Id": "471058", "Score": "0", "body": "Thanks, my only problem is the $artistDelimiters, I have to retrieve the delimiters from a mysql table where the user can add or remove some words, so the delimiters has to be more simple" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T20:34:49.457", "Id": "471078", "Score": "0", "body": "`'~ (?:' . implode('|', array_map(function($v){ return preg_quote($v, '~'); }, $databaseDelimiters)) . ') ~'`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T22:04:51.020", "Id": "471084", "Score": "0", "body": "If I use this I haven't same result\n`code\n $databaseDelimiters = array(' FEAT ', ' feat ', ' FT ', ' ft ', ' + ', ' AND ', ' and ', ' E ', ' e ', ' VS ', ' vs ', ' FEAT. ', ' feat. ', ' FT. ', ' ft. ', ' VS. ', ' vs. ', ' , ', ' & ');\n\n$artistDelimiters = '~ (?:' . implode('|', array_map(function ($v) {\n return preg_quote($v, '~');\n}, $databaseDelimiters)) . ') ~';\n\n$artists = array_flip(preg_split($artistDelimiters, $fullArtist));\n`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T22:13:14.983", "Id": "471085", "Score": "0", "body": "I'm sorry, I have to delete the blank spaces... it is right? Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T22:24:34.350", "Id": "471087", "Score": "0", "body": "Ah yes, I forgot that bit. Yes, `trim()` them (before even saving them to the db -- keep your data tidy)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T22:26:00.277", "Id": "471088", "Score": "0", "body": "Thanks! It's fully working" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T13:22:59.803", "Id": "240143", "ParentId": "240118", "Score": "2" } } ]
{ "AcceptedAnswerId": "240143", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T22:07:59.813", "Id": "240118", "Score": "3", "Tags": [ "php", "array" ], "Title": "Find if some words in array value are in same array php" }
240118
<p>I am creating a translation application and the users can add new translations to the "core" language, e.g. a Latin translation of the German word, and other users can vote on this translation. A translation can only be voted up or down once by the same user.</p> <p>Here are my django models for these purposes, could you please look through this code and give me some feedback. </p> <pre><code>class BaseModel(models.Model): class PublishingStatus(models.TextChoices): DRAFT = 'draft', _('Draft') ACCEPTED = 'accepted', _('Accepted'), REJECTED = 'rejected', _('Rejected') publishing_status = models.CharField( max_length=9, choices=PublishingStatus.choices, default=PublishingStatus.DRAFT, help_text="Publishing status represents the state of the object. By default it is 'draft'" ) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name='%(class)s_created_by', null=True, blank=True) modified_at = models.DateTimeField(auto_now=True) modified_by = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name='%(class)s_modified_by', null=True, blank=True) accepted_at = models.DateTimeField(null=True) accepted_by = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name='%(class)s_accepted_by', null=True, blank=True) rejected_at = models.DateTimeField(null=True) rejected_by = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name='%(class)s_rejected_by', null=True, blank=True) rejection_reason = models.TextField(blank=True, default="") class Meta: abstract = True class LatinGermanTranslation(BaseModel): lt = models.ForeignKey( LtWords, on_delete=models.CASCADE, related_name="lt_de_translations", null=True, blank=True) de = models.ForeignKey( 'GermanWord', on_delete=models.CASCADE, related_name="de_lt_translations", null=True, blank=True) vote = models.IntegerField(default=0) class Meta: verbose_name = 'Latin German Translations' verbose_name_plural = 'Latin German Translations' def up_vote(self, created_by): try: self.de_transl.create( voted_by=created_by, transl=self, vote_type=GermanTranslationVote.Vote.UP) self.vote += 1 self.save() except (DatabaseError, IntegrityError, ValueError) as e: raise Exception(f'Some error occurred during up vote: {e}') return 'ok' def down_vote(self, created_by): try: self.de_transl.create( voted_by=created_by, transl=self, vote_type=GermanTranslationVote.Vote.DOWN) self.vote -= 1 self.save() except (DatabaseError, IntegrityError, ValueError) as e: raise Exception(f'Some error occurred during down vote: {e}') return 'ok' def __str__(self): return f'{self.lt} - {self.de}' class GermanWord(BaseModel): word = models.CharField(max_length=255, default="", blank=True) lt_word = models.ManyToManyField( LtWords, through=LatinGermanTranslation, through_fields=('de', 'lt'), blank=True) class Meta: indexes = [models.Index(fields=['word'])] verbose_name = 'German Word' verbose_name_plural = 'German Words' def __str__(self): return self.word class GermanTranslationVote(models.Model): class Vote(models.TextChoices): UP = 'up', _('Up') DOWN = 'down', _('Down') translation = models.OneToOneField( LatinGermanTranslation, on_delete=models.CASCADE, related_name='de_transl') voted_by = models.OneToOneField( get_user_model(), on_delete=models.CASCADE, related_name='vore_de', null=True, blank=True) vote_type = models.CharField( max_length=4, choices=Vote.choices, default=None) class Meta: indexes = [models.Index(fields=['translation', 'voted_by'])] verbose_name = 'Latin Word Vote' verbose_name_plural = 'Latin Words Votes' </code></pre> <p>Espetially I'd like to hear about the <code>translation</code> and <code>voted_by</code> attributes inside <code>GermanTranslationVote</code> model, since I'm not sure about OneToOne implementation.</p>
[]
[ { "body": "<p>I've honestly never used Django before, so I'm not going to touch on that aspect.</p>\n\n<p>You can reduce a little duplication that exists in your <code>*_vote</code> methods though:</p>\n\n<pre><code>def _vote(self, created_by, vote_change, vote_type):\n try:\n self.de_transl.create(\n voted_by=created_by, transl=self, vote_type=vote_type)\n self.vote += vote_change\n self.save()\n except (DatabaseError, IntegrityError, ValueError) as e:\n direction = \"down\" if vote_change &lt; 0 else \"up\" # Will say \"up\" on 0.\n raise Exception(f'Some error occurred during {direction} vote: {e}')\n return 'ok'\n\ndef up_vote(self, created_by):\n return self._vote(created_by, 1, GermanTranslationVote.Vote.UP)\n\ndef down_vote(self, created_by):\n return self._vote(created_by, -1, GermanTranslationVote.Vote.DOWN)\n</code></pre>\n\n<p>Now you only need to have the bulky exception handling and database management once.</p>\n\n<hr>\n\n<p>You can do something similar for the repeated <code>*_at</code> and <code>*_by</code> variables inside <code>BaseModel</code>:</p>\n\n<pre><code>def atByPair(related_name):\n at_model = models.DateTimeField(auto_now_add=True)\n by_model = models.ForeignKey(\n get_user_model(), on_delete=models.CASCADE,\n related_name=related_name, null=True, blank=True)\n\n return at_model, by_model \n\ncreated_at, created_by = atByPair('%(class)s_created_by')\n\nmodified_at, modified_by = atByPair('%(class)s_modified_by')\n\naccepted_at, accepted_by = atByPair('%(class)s_accepted_by')\n\nrejected_at, rejected_by = atByPair('%(class)s_rejected_by')\nrejection_reason = models.TextField(blank=True, default=\"\")\n</code></pre>\n\n<p>Much less duplication and worrying about needing to make consistent changes in multiple places.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T13:31:24.610", "Id": "471046", "Score": "0", "body": "Thank you so much! I especially like your implementation of the `_vote` method. I'm not sure about defining attributes with the `atByPair` method, because django suggests to set all methods after the `Meta` class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T13:34:07.980", "Id": "471047", "Score": "0", "body": "You're welcome. And I was going to comment on how odd the setup is here (classes inside of classes and many class-level attributes), but I figured that it had something to do with Django. If something I suggested doesn't work with Django, then ignore it. I'm not sure how Django operates." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-31T12:45:15.500", "Id": "477279", "Score": "0", "body": "`atByPair` should be converted to lowercase (Python code style)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T00:02:47.593", "Id": "240124", "ParentId": "240123", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T23:31:01.693", "Id": "240123", "Score": "3", "Tags": [ "python", "python-3.x", "django" ], "Title": "Django voting implementation" }
240123
<p>I have a python code in Airflow Dag. This Dag performs 3 tasks:</p> <ol> <li>Authenticate the user and get access token</li> <li>Create a Databricks cluster using rest API and Submit a notebook job on a cluster using rest API. Pass access token created in the first step as input.</li> <li>Check the status of notebook job</li> </ol> <p>Please help me with code review for this Airflow Dag.</p> <pre><code>from airflow.operators.python_operator import PythonOperator from airflow.models import DAG from datetime import datetime,timedelta import json import os import requests import time import logging auth_file = "my-token.txt" idds_cluster_id_file = "my-cluster-id.txt" path = "/airflow/tokens/" cluster_id = "0408-000631" path= "/airflow/tokens/" temp_run_id_file = "my_save_run_id.txt" databeicks_token_file= "databricks-token.txt" auth_url = "https://snapdeal.com/authentication" cluster_url = "https://snapdeal.com/clustermanager" exec_url = "https://snapdeal.com/databricksexecutor" args = { 'owner': "airflow", 'start_date': datetime.now() } dag = DAG( dag_id="my-notebook-job-trigger-dev", default_args=args, max_active_runs=1, concurrency=1 ) status_dict = { "action": "get_job_status" } auth_dict = { "refresh_token": "" } cluster_dict = { "payload": { "cluster_id": cluster_id }, "databricks_token": "" } cluster_status_dict = { "payload": { "cluster_id": cluster_id }, "databricks_token": "" } search_dict= { "action": "run_job", "auth_token": "", "payload": { "job_id": "956" } } def write_json(response): with open(path + auth_file, 'wb') as file: file.write(json.dumps(response["result"])) def read_tokens(): with open(path + auth_file) as f: data = json.load(f) return data def get_authentication(): data = read_tokens() auth_dict["refresh_token"] = data["refresh_token"] auth_response_raw = requests.post(url=auth_url, json=auth_dict, headers={"Content-Type": "application/json"}) if auth_response_raw.status_code == 200: auth_response = auth_response_raw.json() if auth_response["status"] == "FAILED": logging.info(json.dumps(auth_response_raw.json())) status_message = auth_response["error"]["message"] raise Exception(status_message) else: write_json(auth_response) logging.info("Successfully got authentication.") else: logging.info(json.dumps(auth_response_raw.json())) raise Exception("Got a bad response.") def read_databricks_token(): with open(path + databeicks_token_file, 'r') as infile: token = infile.read() return token.rstrip() def check_cluster_status(status): data = read_tokens() access_token = data["token_type"] + " " + data["access_token"] cluster_status_dict["operation"] = "getinfo" cluster_status_dict["databricks_token"] = read_databricks_token().rstrip() cluster_response_raw = requests.post(url=cluster_url, json=cluster_status_dict, headers={"Content-Type": "application/json", "Authorization": access_token}) if cluster_response_raw.status_code == 200: cluster_response = cluster_response_raw.json() if cluster_response["status"] == "FAILED": logging.info(json.dumps(cluster_response_raw.json())) status_message = cluster_response["error"]["message"] raise Exception(status_message) else: while cluster_response["result"]["info"]["state"] != status: logging.info("Waiting for Cluster to be in "+ status + " status") time.sleep(30) cluster_response_raw = requests.post(url=cluster_url, json=cluster_status_dict, headers={"Content-Type": "application/json", "Authorization": access_token}) if cluster_response_raw.status_code != 200: logging.info(json.dumps(cluster_response_raw.json())) raise Exception("Got a bad response.") else: cluster_response = cluster_response_raw.json() logging.info("Cluster is " + status + " now") else: logging.info(json.dumps(cluster_response_raw.json())) raise Exception("Got a bad response.") def create_cluster(): data = read_tokens() access_token = data["token_type"] + " " + data["access_token"] cluster_dict["databricks_token"] = read_databricks_token() cluster_response_raw = requests.post(url=cluster_url, json=cluster_dict, headers={"Content-Type": "application/json", "Authorization": access_token}) if cluster_response_raw.status_code == 200: cluster_response = cluster_response_raw.json() if cluster_response["status"] == "FAILED": logging.info(json.dumps(cluster_response_raw.json())) status_message = cluster_response["error"]["message"] raise Exception(status_message) else: logging.info("Cluster Creation Started") else: logging.info(json.dumps(cluster_response_raw.json())) raise Exception("Got a bad response.") cluster_status_dict["payload"]["cluster_id"] = cluster_response["result"]["cluster_id"] with open(path + idds_cluster_id_file, 'wb') as file: file.write(cluster_response["result"]["cluster_id"]) check_cluster_status("RUNNING") def submit_job(): auth = read_tokens() access_token = auth["token_type"] + " " + auth["access_token"] create_cluster() search_dict["auth_token"] = read_databricks_token() job_response_raw = requests.post(url=exec_url, json=search_dict, headers={"Content-Type": "application/json", "Authorization": access_token}) if job_response_raw.status_code == 200: job_response = job_response_raw.json() if job_response["status"] == "FAILED": logging.error(json.dumps(job_response_raw.json())) status_message = job_response["error"]["message"] raise Exception(status_message) else: logging.info("Starting to write run id in file") run_id = str(job_response["result"]["run_id"]) with open(path + temp_run_id_file, 'w') as file: file.write(run_id) return run_id else: logging.error("Failed to execute Job") logging.error(json.dumps(job_response_raw.json())) raise Exception("Got a bad response.") def delete_cluster(): data = read_tokens() access_token = data["token_type"] + " " + data["access_token"] cluster_status_dict["operation"] = "delete" cluster_status_dict["databricks_token"] = read_databricks_token().rstrip() with open(path + idds_cluster_id_file, 'r') as file: cluster_id = file.read() cluster_status_dict["payload"]["cluster_id"] = cluster_id cluster_response_raw = requests.post(url=cluster_url, json=cluster_status_dict, headers={"Content-Type": "application/json", "Authorization": access_token}) if cluster_response_raw.status_code == 200: cluster_response = cluster_response_raw.json() if cluster_response["status"] == "FAILED": logging.info(json.dumps(cluster_response_raw.json())) status_message = cluster_response["error"]["message"] raise Exception(status_message + " " + cluster_status_dict["payload"]["cluster_id"]) else: logging.info("Deleting Cluster") else: logging.info(json.dumps(cluster_response_raw.json())) raise Exception("Got a bad response.") def check_status(): with open(path + temp_run_id_file, 'r') as file: RUN_ID = file.read() os.remove(path + temp_run_id_file) logging.info(RUN_ID) status_dict["run_id"] = RUN_ID status_dict["auth_token"] = read_databricks_token() logging.info(status_dict) auth = read_tokens() access_token = auth["token_type"] + " " + auth["access_token"] job_status_response_raw = requests.post(url=exec_url, json=status_dict, headers={"Content-Type": "application/json", "Authorization": access_token}) if job_status_response_raw.status_code == 200: job_status_response = job_status_response_raw.json() logging.info(job_status_response) else: logging.info(json.dumps(job_status_response_raw.json())) raise Exception("Got a bad response.") while job_status_response["result"]["state"]["life_cycle_state"] == "PENDING" or job_status_response["result"]["state"]["life_cycle_state"] == "RUNNING": logging.info("Waiting for job to finish!") time.sleep(30) job_status_response_raw = requests.post(url=exec_url, json=status_dict, headers={"Content-Type": "application/json", "Authorization": access_token}) if job_status_response_raw.status_code == 200: job_status_response = job_status_response_raw.json() logging.info(job_status_response) else: raise Exception("Got a bad response.") if "result_state" in job_status_response["result"]["state"]: if job_status_response["result"]["state"]["result_state"] == "FAILED": logging.info(json.dumps(job_status_response_raw.json())) status_message = job_status_response["result"]["state"]["state_message"] logging.info("Failed with error: " + status_message) logging.info(job_status_response) delete_cluster() check_cluster_status("TERMINATED") raise Exception(status_message) elif job_status_response["result"]["state"]["result_state"] == "SUCCESS": logging.info("Job ran successfully") logging.info(job_status_response) delete_cluster() check_cluster_status("TERMINATED") t1 = PythonOperator( task_id='get_authentication', python_callable=get_authentication, dag=dag ) t2 = PythonOperator( task_id='run_notebook_job', python_callable=submit_job, dag=dag ) t3 = PythonOperator( task_id='check_notebook_status', python_callable=check_status, dag=dag ) t1.set_downstream(t2) t2.set_downstream(t3) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T03:35:10.417", "Id": "471019", "Score": "3", "body": "Welcome to code review. Does this code work as expected? We can only review working code, we can't help you debug your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T11:46:21.777", "Id": "471038", "Score": "0", "body": "Yes, this is working expected. But as code interacts with internal enterprise APIs there are just accessible within the enterprise network." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T14:34:10.877", "Id": "471052", "Score": "1", "body": "In addition to the 2 down votes that you can see, there has been one vote to close this question. The person that voted to close felt that there needed to be more description about what the program does. Take a look at our help center at https://codereview.stackexchange.com/help/how-to-ask and see if you can add a few details." } ]
[ { "body": "<h2>Typo</h2>\n\n<p><code>databeicks_token_file</code> -> <code>databricks_token_file</code></p>\n\n<h2>Exceptions</h2>\n\n<pre><code> raise Exception(status_message)\n</code></pre>\n\n<p>is going to make it problematic for callers to meaningfully catch this separate from other exceptions, if they need to. Instead, raise a more specific exception, possibly a custom one - they're easy to define in Python.</p>\n\n<h2>Global code</h2>\n\n<pre><code>t1 = PythonOperator(\n task_id='get_authentication',\n python_callable=get_authentication,\n dag=dag\n)\n\n\nt2 = PythonOperator(\n task_id='run_notebook_job',\n python_callable=submit_job,\n dag=dag\n)\nt3 = PythonOperator(\n task_id='check_notebook_status',\n python_callable=check_status,\n dag=dag\n)\n\nt1.set_downstream(t2)\nt2.set_downstream(t3)\n</code></pre>\n\n<p>should be pulled into a <code>main</code> function.</p>\n\n<h2>Global variables</h2>\n\n<p>These:</p>\n\n<pre><code>auth_file = \"my-token.txt\"\nidds_cluster_id_file = \"my-cluster-id.txt\"\npath = \"/airflow/tokens/\"\ncluster_id = \"0408-000631\"\npath= \"/airflow/tokens/\"\ntemp_run_id_file = \"my_save_run_id.txt\"\ndatabeicks_token_file= \"databricks-token.txt\"\nauth_url = \"https://snapdeal.com/authentication\"\ncluster_url = \"https://snapdeal.com/clustermanager\"\nexec_url = \"https://snapdeal.com/databricksexecutor\"\n</code></pre>\n\n<p>are fine-ish where they are, though the names should be capitalized. These might also benefit from being pulled out into a configuration file or environment variables.</p>\n\n<p>However, the rest of it (<code>args</code> through <code>search_dict</code>) probably doesn't belong here. <code>args</code> should just be moved to a nested literal initializer inside the <code>DAG</code> constructor; these other dictionaries should be passed - or parts of them passed, where appropriate - between functions. Having various functions mutate various keys in these dictionaries before they're passed to <code>requests</code> is not very maintainable. Something like <code>check_cluster_status</code> is better off constructing <code>cluster_status_dict</code> in its own scope.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T21:17:49.510", "Id": "240168", "ParentId": "240128", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T03:18:21.920", "Id": "240128", "Score": "0", "Tags": [ "python" ], "Title": "Python Code in Airflow Dag" }
240128
<p>I made a simple django migration that adds two field to our Invoices model : <code>first_payment</code> and <code>first_paying_month</code>.</p> <p><code>first_payment</code> is obvious : is this the user's first payment, <code>first_paying_month</code> answers to the question: Was this payment made in the same month as the first payment, I'd love a more obvious name for this field. </p> <p>The values for these fields used to be computed dynamically but now we need them all the time for performance reasons.</p> <p>The schema part of the migration in handled by Django so there's not much to show. But I'd like inputs on this script, I'm mostly looking for performance optimizations but I'm really open to any feedback :)</p> <pre class="lang-py prettyprint-override"><code>from django.db.models import Count from wallet.models import Invoice from account.models import User def set_first_payment_flags(): # We don't use a RunPython for out-of-scope reasons users_by_invoice_count = User.objects.annotate(Count("invoice")) users_with_one_invoice = users_by_invoice_count.filter( invoice__count=1 ).values_list("id", flat=True) users_with_many_invoice = users_by_invoice_count.filter( invoice__count__gt=1 ) Invoice.objects.filter(user__id__in=users_with_one_invoice).update( first_payment=True, first_paying_month=True ) invoices_to_save = [] for user in users_with_many_invoices: # This part has a lot of queries and I'd like to reduce them but I could'nt find anything. # I don't see how to reference the first field of a relation in an F expression. first_invoice = user.invoice_set.order_by("date_created").first() first_invoice.first_payment = True invoices_to_save.append(first_invoice) user.invoice_set.filter( date_created__month=first_invoice.date_created.month ).update(first_paying_month=True) Invoice.objects.bulk_update(invoices_to_save, fields=["first_payment"]) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T08:40:38.633", "Id": "240131", "Score": "3", "Tags": [ "python", "performance", "python-3.x", "django", "postgresql" ], "Title": "Django migration script to add metadata" }
240131
<p>I faced the following problem.</p> <p>I have a Server object <code>server</code> which exposes <code>TriggerStateChangeAsync()</code> which return an <code>Task&lt;bool&gt;</code> this task finished with <code>true</code> as soon the request for the state changed is send off to the server and with <code>false</code> if the request could not be send to the server. The object also exposses the event <code>StateChanged</code> which will be raised if the server reports that the state has changed.</p> <p>What I now wanted to do is to write a wrapper Methode which will finishes (async) if after the state has changed or the request could not be send to the server.</p> <p>It looks like:</p> <pre class="lang-cs prettyprint-override"><code>public static async Task&lt;boo&gt; TriggerStateChangeAndWaitAsync(this Server server, int stateId) { var stateChanged = new TaskCompletionSource&lt;bool&gt;(); // local methode void handler(object sender, StateEventArgs e) { // this handels that the state has now actually changed if (e.StateId = id) { server.StateChanged -= handler; stateChanged.SetResult(true); } } try { server.StateChanged += handler; // this task finishes when the request is send off to the server bool sendToServer = await server.TriggerStateChangeAsync(id); if (sendToServer) { await stateChanged.Task.WithTimeout(1000); } return sendToServer; } finally { server.StateChanged -= handler; } } </code></pre> <p>Is this an good approch for that? And is it okay to leave the <code>TaskCompletionSource</code> uncompleted in the case that the request could not be sent?</p> <hr> <p>The method <code>WithTimeout(1000)</code> is just an extension methode for <code>Task</code>that is just </p> <pre class="lang-cs prettyprint-override"><code>public static async Task&lt;R&gt; WithTimeout&lt;R&gt;(this Task&lt;R&gt; task, int timeout) { using (var timeoutCancellationTokenSource = new CancellationTokenSource()) { var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token)); if (completedTask == task) { timeoutCancellationTokenSource.Cancel(); return await task; } else { throw new TimeoutException("The operation has timed out."); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T12:33:25.207", "Id": "471041", "Score": "0", "body": "Could someone explain the downvote? Can I somehow improve the question?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T08:59:53.777", "Id": "240133", "Score": "1", "Tags": [ "c#", "asynchronous", "async-await" ], "Title": "Awaiting the completion of a server request" }
240133
<p>I developed a card game engine for a german three player card game called <em>Skat</em>. The operating code lives in a <code>StateT SkatEnv (WriterT [Trick] IO)</code> Monad.</p> <pre><code>data SkatEnv = SkatEnv { piles :: Piles , turnColour :: Maybe TurnColour , skatGame :: Game , players :: Players , currentHand :: Hand , skatSinglePlayer :: Hand } deriving Show type Skat = StateT SkatEnv (WriterT [Trick] IO) </code></pre> <p>To force the three player character on the typelevel, I decided to use a special <code>Players</code> datatype instead of a list, that uses an existentially quantified type <code>PL</code> that can hold any kind of player, that implements the <code>Player</code> typeclass. To make match specific information available to the Player, the <code>chooseCard</code> etc. functions live in a <code>MonadPlayer</code> Monad.</p> <pre><code>class (Monad m, MonadIO m) =&gt; MonadPlayer m where trump :: m Trump turnColour :: m (Maybe TurnColour) singlePlayer :: m Hand game :: m Game class (Monad m, MonadIO m, MonadPlayer m) =&gt; MonadPlayerOpen m where showPiles :: m (Piles) class Player p where team :: p -&gt; Team hand :: p -&gt; Hand chooseCard :: (HasCard d, HasCard c, MonadPlayer m) =&gt; p -&gt; [CardS Played] -&gt; [CardS Played] -&gt; Maybe [d] -&gt; [c] -&gt; m (Card, p) onCardPlayed :: MonadPlayer m =&gt; p -&gt; CardS Played -&gt; m p chooseCardOpen :: MonadPlayerOpen m =&gt; p -&gt; m Card data PL = forall p. (Show p, Player p) =&gt; PL p data Players = Players PL PL PL deriving Show </code></pre> <p>By using the <code>MonadPlayer</code> interface I can use my <code>Skat</code> monad for calling the <code>Player</code>'s functions without exposing unallowed information, e.g. the other players' cards.</p> <pre><code>instance MonadPlayer Skat where trump = getTrump &lt;$&gt; P.game turnColour = gets turnColour singlePlayer = gets skatSinglePlayer game = gets skatGame </code></pre> <p>I used the <code>PL</code> wrapper, to be able to implement different players in seperate modules, to keep the code clean and extendible, since I have many different players, e.g. an online player that communicates via a socket or a bot, that heuristically decides which card to play.</p> <p>Another concern for me is the need of the <code>MonadIO</code> restriction for the <code>MonadPlayer</code> typeclass. This is needed, because my online player for example needs to send messages via a socket, which obviously needs to live in <code>IO</code>, although the bot player could perfectly deal without it. But since I have one common <code>Player</code> interface, I have to make <code>IO</code> available to every player.</p> <p>Is it better style, not to use the <code>PL</code> wrapper but implement the <code>Players</code> type as</p> <pre><code>data Players a b c = Players a b c </code></pre> <p>This would lead to type variables all over the place, especially for everything <code>SkatEnv</code> related.</p> <p>I left out many implementation details, e.g. many small type definitions. Please let me know, if you need more details about a specific type.</p>
[]
[ { "body": "<p>Can you make Player a datatype instead of a typeclass? The datatype can have exactly the same methods but with the first argument elided. Make Player an instance of Show, and voilá, <code>data Players = Players Player Player Player</code>. One implications is that a bot and a human player are now both just values of the same type, Player. Thus the chooseCard, chooseCardOpen and onCardPlayed of a bot can yield a human with a hand and cards on the table mid-game, and vice versa. I'd love to have the freedom to have a bot play the first few rounds for me, yield to me when the game starts going, and play out the last couple of rounds when I feel victory is secure! And as you note, you already opted to give every player type MonadIO, anyway, so these types are not really looser.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T08:44:27.160", "Id": "471745", "Score": "0", "body": "This is actually a pretty good idea, although I'm afraid it does not work for me, because my different player types should be able to store additional data they need, to process `chooseCard` etc. I would have to add these data fields to the general `Player` data type, which does not fit the idea of an abstract player interface, that is independent of the implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T13:09:53.260", "Id": "471873", "Score": "0", "body": "Can you parameterize Player by the type of the additional information (or the unit type if none) and add one field of that type to Player? Failing that, is this level of extensibility needed (it could well be if you're writing a library!), or can Player be a sum type and Human, Bot and so on be alternate constructors instead of instances?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T13:48:42.613", "Id": "471877", "Score": "0", "body": "It is supposed to be a library, so I really need the extensibility. Parameterizing `Player` is an option, but I feel like it is not necessarily a style improvement over what I currently have :/ How do you feel about this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T19:05:50.250", "Id": "472603", "Score": "0", "body": "I feel like explicit record passing would be a marginal improvement, hopefully ergonomically but IMO also conceptually. It means that any function that accepts one kind of a player as an argument must be able to handle any of them. If that's unreasonable, then I recommend keeping the typeclass. Since you're writing a library, you're not only making that trade-off between freedom and constraint for yourself but also for code that uses the library." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T19:12:58.370", "Id": "472607", "Score": "0", "body": "I can't foresee how your library is going to be used so I can't make the final call either way. Nor can I rid you of constraints except by recommending requiring concrete types upfront. I find the interplay between the Ord typeclass and Set from containres enlightening in this regard. Ord happens to be a typeclass, meaning that there is a canonical order for many types. That means Set can indulge in being a type. But then again, most interesting operations on Set state an Ord constraint. But I digress, this is not directly comparable to your situation." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T23:21:12.360", "Id": "240423", "ParentId": "240134", "Score": "3" } } ]
{ "AcceptedAnswerId": "240423", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T09:54:24.503", "Id": "240134", "Score": "3", "Tags": [ "haskell" ], "Title": "Existential quantification versus explicit types" }
240134
<p>I wrote some code to create marketshare reports. However, I'm sure it can be improved. The tasks performed are:</p> <ol> <li>Open the global data file, refresh the data, import its content as a DF.</li> <li>Create a backup copy of the old report file.</li> <li>Read the list of Distribution companies who should receive the report with their data (plus anonymize data of others).</li> <li>Perform data preprocessing tasks.</li> <li>Swap the Data sheet in the report file, change its name accordingly (name of the report, name of the Distribution company, month number).</li> </ol> <p>I'm not expecting anyone to get too much into "how it works" (tried to explain it as much as possible in the comments), but is there anything you see that could be improved in this code from the technical point of view?</p> <p>Much appreciated!</p> <pre><code># Import the necessary libraries import pandas as pd import numpy as np import unidecode as ud import string import re from openpyxl import load_workbook import os import win32com.client as win32 import datetime from shutil import copyfile, move # Define the methods needed # This one is for refreshing the Excel files without having to do it manually def refresh(directory, file_name): xlapp = win32.DispatchEx('Excel.Application') xlapp.DisplayAlerts = False xlapp.Visible = True xlbook = xlapp.Workbooks.Open(directory + '\\' + file_name) xlbook.RefreshAll() xlbook.Save() xlbook.Close() xlapp.Quit() # This one is to clean up Distribution company names def remove_stopwords(text): stopword_list = ['SP', 'S', 'SPZOO', 'ZOO', 'OO', 'POLSKA', 'SPZ', 'Z', 'A', 'AKCYJNA', 'SPOLKA', 'KOMANDYTOWA', 'SPK', 'SK', 'K', 'O', 'SA', 'SJ', 'SPJ', 'J', 'JAWNA'] text_nopunct = ''.join([char.upper() for char in text if char not in string.punctuation]) text_unidecoded = ud.unidecode(text_nopunct) tokens = re.split('\W+', text_unidecoded) tokens_no_stopwords = [word for word in tokens if word not in stopword_list] formatted_text = ' '.join(tokens_no_stopwords) return formatted_text # This one is to swap sheets in the Excel file and rename it def excel_rewriter(data_source, df_name, target_file): book = load_workbook(data_source) writer = pd.ExcelWriter(data_source, engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) df_name.to_excel(writer, 'Data', index=False) writer.save() os.rename(data_source, target_file) # Define timeframes month_ago = str(int(datetime.datetime.today().strftime('%Y%m'))-1) two_months_ago = str(int(datetime.datetime.today().strftime('%Y%m'))-2) # Data location and file name data_folder = os.getcwd() backup_folder = data_folder + '\\backup' chdna_data_file = 'ChannelDnAReport.xlsx' # Open list of Distribution companies from the text file distis = [] with open('distis.txt', 'r') as filehandle: for line in filehandle: currentDisti = line[:-1] distis.append(currentDisti) # List names for old and new files old_list = [] new_list = [] for disti in distis: old = disti + '_marketshare_' + two_months_ago + '.xlsx' old_list.append(old) new = disti + '_marketshare_' + month_ago + '.xlsx' new_list.append(new) # Create backup copies and place them in the backup folder for old in old_list: copyfile(old, old + '_copy.xlsx') move(old + '_copy.xlsx', backup_folder) os.rename(backup_folder + '\\' + old + '_copy.xlsx', backup_folder + '\\' + old) # Refresh the main data file refresh(data_folder, chdna_data_file) # Read it as a dataframe df_chdna = pd.read_excel(chdna_data_file, sheet_name='Data') # Standarize Disti names in the DF column (they are a mess otherwise..) df_chdna['Reporter HQ Name'] = df_chdna['Reporter HQ Name'].apply(lambda x: remove_stopwords(x)) # Create DF Total with anonymized data df_total = df_chdna.copy() df_total.loc[:, ]['Reporter HQ Name'] = 'TOTAL' # Create DFs for each Disti df_list = [] distis_chdna = [] for disti in distis: df_list.append('df_' + disti) distis_chdna.append(disti.upper().replace('_', ' ')) for df, disti_chdna in zip(df_list, distis_chdna): vars()[df] = pd.concat([df_chdna[df_chdna['Reporter HQ Name']==disti_chdna], df_total]) # Swap the Data sheet and refresh Pivots in Excel report files for old, df, new in zip(old_list, df_list, new_list): excel_rewriter(old, vars()[df], new) refresh(data_folder, new) </code></pre>
[]
[ { "body": "<h2>Path management</h2>\n\n<p>This:</p>\n\n<pre><code>directory + '\\\\' + file_name\n</code></pre>\n\n<p>would be better represented by a <code>Path</code>:</p>\n\n<pre><code>from pathlib import Path\n# ...\n\ndef refresh(path: Path):\n # ...\n xlbook = xlapp.Workbooks.Open(str(path))\n\n# ...\n\n# Refresh the main data file\nrefresh(Path(data_folder) / chdna_data_file)\n</code></pre>\n\n<p>Also, this:</p>\n\n<pre><code># Data location and file name\ndata_folder = os.getcwd()\nbackup_folder = data_folder + '\\\\backup'\n</code></pre>\n\n<p>can be</p>\n\n<pre><code># Data location and file name\nbackup_folder = Path.cwd() / 'backup'\n</code></pre>\n\n<p>and similarly for</p>\n\n<pre><code>os.rename(backup_folder + '\\\\' + old + '_copy.xlsx', backup_folder + '\\\\' + old)\n</code></pre>\n\n<h2>Set lookup</h2>\n\n<p><code>stopword_list</code> should be a set, i.e.</p>\n\n<pre><code>stopwords = {'SP', 'S', 'SPZOO', 'ZOO', 'OO', 'POLSKA', 'SPZ', 'Z', 'A', 'AKCYJNA', 'SPOLKA', 'KOMANDYTOWA', 'SPK', 'SK', 'K', 'O', 'SA', 'SJ', 'SPJ', 'J', 'JAWNA'}\n</code></pre>\n\n<p>This allows for efficient O(1) instead of O(n)-time lookup.</p>\n\n<h2>Generator materialization</h2>\n\n<p>Drop the inner brackets here:</p>\n\n<pre><code>text_nopunct = ''.join([char.upper() for char in text if char not in string.punctuation])\n</code></pre>\n\n<p>so that the generator goes straight to the <code>join</code> without first being saved to an in-memory list.</p>\n\n<p>For the same reason,</p>\n\n<pre><code>tokens_no_stopwords = [word for word in tokens if word not in stopword_list]\n</code></pre>\n\n<p>should use parentheses instead of brackets.</p>\n\n<h2>String interpolation</h2>\n\n<pre><code>old = disti + '_marketshare_' + two_months_ago + '.xlsx'\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>old = f'{disti}_marketshare_{two_months_ago}.xlsx'\n</code></pre>\n\n<h2>Global code</h2>\n\n<p>Pull everything after</p>\n\n<pre><code># Define timeframes\n</code></pre>\n\n<p>into one or more functions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T15:52:22.970", "Id": "240147", "ParentId": "240136", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T09:58:38.880", "Id": "240136", "Score": "3", "Tags": [ "python", "performance", "excel", "database", "pandas" ], "Title": "Python script for refreshing and preprocessing data in Excel report files" }
240136
<p>I created a Custom view to select a value. I use horizontal Recyclerview to select an integer value and 2 buttons that decrease or increase the values. Could you consider the code and tell how it can be improved?</p> <p>SliderValueSelectorView</p> <pre><code>public class SliderValueSelectorView extends ConstraintLayout implements View.OnClickListener { private TextView valueText; private View selectValueView; private RecyclerView valueRecyclerView; private LinearSnapHelper valueSnapHelper = new LinearSnapHelper(); private RecyclerView.LayoutManager valueLayoutManager; private ValueSelectAdapter valueAdapter; private SnapRecyclerUtil recyclerUtil = new SnapRecyclerUtil(); private BigDecimal value = new BigDecimal(70); private BigDecimal valueStep = new BigDecimal(0.1); private int minValue = 1; private int maxValue = 300; private int scale = 1; private RoundingMode roundingMode = RoundingMode.HALF_UP; public SliderValueSelectorView(Context context) { super(context); initView(); } public SliderValueSelectorView(Context context, AttributeSet attrs) { super(context, attrs); initView(); } public SliderValueSelectorView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(); } private void initView() { View view = inflate(getContext(), R.layout.slider_selector_layout, this); initValue(); initRecycler(view); valueText = view.findViewById(R.id.value); view.findViewById(R.id.increase).setOnTouchListener(new RepeatListener(200, this)); view.findViewById(R.id.reduce).setOnTouchListener(new RepeatListener(200, this)); } private void initValue() { value = value.setScale(scale, roundingMode); valueStep = valueStep.setScale(scale, roundingMode); } private void initRecycler(View view) { valueAdapter = new ValueSelectAdapter(maxValue + 1, minValue); valueRecyclerView = view.findViewById(R.id.values); valueLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false); OffsetItemDecoration itemDecoration = new OffsetItemDecoration(); valueRecyclerView.addItemDecoration(itemDecoration); recyclerUtil.installationRecyclerView( valueRecyclerView, valueSnapHelper, valueLayoutManager, valueAdapter, recyclerViewScrollListener, getRecyclerPosition()); } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.increase) { stepWeight(valueStep); } else if (id == R.id.reduce) { stepWeight(valueStep.negate()); } } private void stepWeight(BigDecimal stepFractional) { double result = getValueText() + stepFractional.doubleValue(); if ((result &gt; minValue + 1 || stepFractional.doubleValue() &gt; 0) &amp;&amp; (result &lt;= maxValue || stepFractional.doubleValue() &lt; 0)) { int startPosition = value.intValue(); value = value.add(stepFractional); if (startPosition != value.intValue()) { scrollToCurrentValue(); } } valueText.setText(this.toString()); } private RecyclerView.OnScrollListener recyclerViewScrollListener = new RecyclerView.OnScrollListener() { @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); selectValueView = recyclerUtil.getCenterView(valueSnapHelper, valueLayoutManager); showSelectValue(); } }; @SuppressLint("SetTextI18n") private void showSelectValue() { TextView selectView = selectValueView.findViewById(R.id.select_weight); int newWeight = Integer.parseInt(selectView.getText().toString()); value = value.add(new BigDecimal(newWeight - value.intValue())); valueText.setText(this.toString()); } @Override @NonNull public String toString() { return value.toString(); } public void setString(String weightStr) { try { value = new BigDecimal(weightStr); scrollToCurrentValue(); } catch (NumberFormatException ex) { throw new RuntimeException(weightStr + " not a number, therefore it is impossible to convert " + weightStr + " to mass"); } } public float getValueText() { return Float.parseFloat(this.toString()); } private void scrollToCurrentValue() { recyclerUtil.toTargetPosition(valueLayoutManager, valueSnapHelper, valueRecyclerView, getRecyclerPosition()); } public BigDecimal getValueStep() { return valueStep; } public void setValueStep(BigDecimal valueStep) { this.valueStep = valueStep.setScale(scale, roundingMode); } public int getMinValue() { return minValue; } public void setMinValue(int minValue) { this.minValue = minValue; this.valueAdapter.setMinValue(minValue); this.valueAdapter.notifyDataSetChanged(); } private int getRecyclerPosition() { return value.intValue() - minValue; } public int getMaxValue() { return maxValue; } public void setMaxValue(int maxValue) { this.maxValue = maxValue; this.valueAdapter.setMaxValue(maxValue + 1); this.valueAdapter.notifyDataSetChanged(); } public BigDecimal getValue() { return value; } public void setValue(BigDecimal value) { this.value = value.setScale(scale, roundingMode); scrollToCurrentValue(); } public int getScale() { return scale; } public void setScale(int scale) { this.scale = scale; } public RoundingMode getRoundingMode() { return roundingMode; } public void setRoundingMode(RoundingMode roundingMode) { this.roundingMode = roundingMode; } } </code></pre> <p>slider_selector_layout.xml</p> <pre><code>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/weightSelector" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/border" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/description"&gt; &lt;ImageButton android:id="@+id/reduce" android:layout_width="@dimen/image_icon" android:layout_height="@dimen/image_icon" android:layout_weight="1" android:background="@null" android:rotation="180" android:scaleType="fitCenter" android:src="@drawable/weight_change" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /&gt; &lt;TextView android:id="@+id/value" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:textColor="@color/darkGreen" android:textSize="32sp" app:layout_constraintEnd_toStartOf="@+id/increase" app:layout_constraintStart_toEndOf="@+id/reduce" app:layout_constraintTop_toTopOf="parent" /&gt; &lt;ImageButton android:id="@+id/increase" android:layout_width="@dimen/image_icon" android:layout_height="@dimen/image_icon" android:layout_weight="1" android:background="@null" android:gravity="end" android:scaleType="fitCenter" android:src="@drawable/weight_change" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" /&gt; &lt;androidx.recyclerview.widget.RecyclerView android:id="@+id/values" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/border" app:layout_constraintTop_toBottomOf="@+id/increase" /&gt; &lt;ImageView android:id="@+id/top_indicator" android:layout_width="@dimen/image_icon" android:layout_height="@dimen/image_icon" android:rotation="180" android:src="@drawable/weight_indicator" app:layout_constraintEnd_toEndOf="@+id/values" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="@+id/values" /&gt; &lt;ImageView android:id="@+id/bottom_indicator" android:layout_width="@dimen/image_icon" android:layout_height="@dimen/image_icon" android:src="@drawable/weight_indicator" app:layout_constraintBottom_toBottomOf="@+id/values" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /&gt; </code></pre> <p></p> <p>RepeatListener</p> <pre><code>public class RepeatListener implements View.OnTouchListener { private Handler handler = new Handler(); private final int initialInterval; private final View.OnClickListener clickListener; private View touchedView; private Runnable handlerRunnable = new Runnable() { @Override public void run() { if (touchedView.isEnabled()) { handler.postDelayed(this, initialInterval); clickListener.onClick(touchedView); } else { handler.removeCallbacks(handlerRunnable); touchedView.setPressed(false); touchedView = null; } } }; public RepeatListener(int initialInterval, View.OnClickListener clickListener) { if (clickListener == null) throw new IllegalArgumentException("null runnable"); if (initialInterval &lt; 0) throw new IllegalArgumentException("negative interval"); this.initialInterval = initialInterval; this.clickListener = clickListener; } public boolean onTouch(View view, MotionEvent motionEvent) { switch (motionEvent.getAction()) { case MotionEvent.ACTION_DOWN: handler.removeCallbacks(handlerRunnable); handler.postDelayed(handlerRunnable, initialInterval); touchedView = view; touchedView.setPressed(true); clickListener.onClick(view); return true; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: handler.removeCallbacks(handlerRunnable); touchedView.setPressed(false); touchedView = null; return true; } return false; } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T10:02:23.397", "Id": "240137", "Score": "1", "Tags": [ "java", "beginner", "android", "xml", "layout" ], "Title": "Custom view to select a value" }
240137
<p>This code solves the problem of how to share user inputs throughout a large application when using dependency injection. To achieve this, I'm using a static (through DI) store and injecting it at those places, where the inputs are needed. In an application without dependency injection, arguments would be passed via constructor, what is not possible when using DI. Alternatives would be to call after injection some <code>Init</code>/<code>Start</code>/<code>Load</code> function. </p> <p>Please tell me your thoughts and concerns.</p> <p>Fiddle: <a href="https://dotnetfiddle.net/8VqsGz" rel="nofollow noreferrer">https://dotnetfiddle.net/8VqsGz</a></p> <p>Landmarks:</p> <ul> <li>Landmark 1: Register all components in DI</li> <li>Landmark 1.1: Store is marked as singleton, therefore all injections use the same data</li> <li>Landmark 1.2: Store has a readonly interface on business logic side, writable interface is only used in the "ui"</li> <li>Landmark 2: Execute user input</li> <li>Landmark 3: User inputs and data will be saved in static store</li> <li>Landmark 4: Create instance </li> <li>Landmark 5: Resolve many IValidation checks</li> <li>Landmark 6: Rules will be executed</li> <li>Landmark 7: Rule is directly accessing the readonly store to validate the data</li> </ul> <p>Code:</p> <pre><code>// Add reference "Microsoft.Extensions.DependencyInjection" Version="3.1.3" using System; using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; namespace sample_di_user_input { class Program { static void Main(string[] args) { var serviceProvider = ConfigureServices(); try { // Landmark 2: Execute user input serviceProvider.GetService&lt;SampleInputApplication&gt;().Run(); // Landmark 4: Create instance serviceProvider.GetService&lt;InputValidationService&gt;().Run(); } catch (System.Exception e) { Console.WriteLine(e); } } private static IServiceProvider ConfigureServices() { var services = new ServiceCollection(); IServiceProvider serviceProvider = null; // Caution! This scopes the singletons // Landmark 1: Register all components in DI // Landmark 1.1: Store is marked as singleton, therefore all injections use the same data // Landmark 1.2: Store has a readonly interface on businesslogic side, writable interface is only used in the "ui" var store = new InputDataStore(); services.AddSingleton&lt;InputDataStore&gt;(x =&gt; store); services.AddSingleton&lt;IInputDataStore, InputDataStore&gt;(x =&gt; store); services.AddTransient&lt;SampleInputApplication&gt;(); services.AddTransient&lt;IValidation, InputAgeValidation&gt;(); services.AddTransient&lt;IValidation, InputNameValidation&gt;(); services.AddTransient&lt;InputValidationService&gt;(x =&gt; { // Landmark 5: Resolve many IValidation checks var validationRules = serviceProvider.GetServices&lt;IValidation&gt;(); return new InputValidationService(validationRules); }); return serviceProvider = services.BuildServiceProvider(); } } public interface IInputDataStore { string Name { get; } string Age { get; } } public class InputDataStore : IInputDataStore { public string Name { get; set; } public string Age { get; set; } } public class SampleInputApplication { private readonly InputDataStore inputDataStore; public SampleInputApplication(InputDataStore inputDataStore) { this.inputDataStore = inputDataStore; } public void Run() { // Landmark 3: User inputs and data will be saved in static store Console.WriteLine("What is your name?"); inputDataStore.Name = "SampleName"; // inputDataStore.Name = Console.ReadLine(); Console.WriteLine("What is your age?"); inputDataStore.Age = "21"; // inputDataStore.Age = Console.ReadLine(); } } public interface IValidation { void Validate(); } public class InputAgeValidation : IValidation { private readonly IInputDataStore inputDataStore; public InputAgeValidation(IInputDataStore inputDataStore) { this.inputDataStore = inputDataStore; } public void Validate() { // Landmark 7: Rule is directly accessing the readonly store to validate the data if (string.IsNullOrEmpty(inputDataStore.Age)) { throw new Exception("No age input"); } if (!int.TryParse(inputDataStore.Age, out int age)) { throw new Exception("Not a valid age number"); } if (age &lt;= 20) { throw new Exception("Sorry! You are not old enough"); } } } public class InputNameValidation : IValidation { private readonly IInputDataStore inputDataStore; public InputNameValidation(IInputDataStore inputDataStore) { this.inputDataStore = inputDataStore; } public void Validate() { if (inputDataStore.Name.Length &gt; 5) { throw new Exception("You are not allowed!"); } } } public class InputValidationService { private IEnumerable&lt;IValidation&gt; validationRules; public InputValidationService(IEnumerable&lt;IValidation&gt; validationRules) { this.validationRules = validationRules; } internal void Run() { // Landmark 6: Rules will be executed foreach (var rule in validationRules) { rule.Validate(); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T15:30:44.567", "Id": "471056", "Score": "0", "body": "You are sacrificing channels like method parameters and return values for nothing. Only to force yourself to do a silly thing like making user input a DI service. You should really have a service that can ask user for the input and the caller would then pass it around to those who need it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T16:17:15.947", "Id": "471060", "Score": "0", "body": "This is perhaps a good way to practice design patterns for a very large, complex application, but if your end goal is really to do something simple -- sometimes simple is better. Stuffing a bunch of code into a method is sometimes more readable and easier to work with. As someone who loves abstractions, I say abstractions aren't necessarily the \"right\" way to do things. Abstractions are a tradeoff." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T16:30:16.350", "Id": "471067", "Score": "0", "body": "@slepic What is the difference between a \"user input DI service\" and a \"service that can ask user for the input\". Apart from one may not be injected...? Also the \"caller\" of what is not clear. Pass \"it\" around... do you mean the user input or the user input service?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T17:21:59.110", "Id": "471070", "Score": "0", "body": "@Tom \"user input DI service\" being data structure holding values inputted from user. \"Service that can ask user for the input\" would be a service with a method that collects the user input and returns it as a data struct/tuple. The \"caller\" Is the one who calls the service that collects the input. And \"it\" referrs to the collected user input data structure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T05:41:13.517", "Id": "471107", "Score": "0", "body": "Hi, thank you for your feedback. It was not possible to do the real world example, therefore i choose a simplified codebase, maybe it looks to simple but for concept it should be enough. Sadly, if this is not the right way to handle user inputs with DI, please tell me your solution. I'd love to see some code :) I created another sample how i wouldn't make it https://dotnetfiddle.net/TcE4vq" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T21:24:06.580", "Id": "471169", "Score": "0", "body": "In the presented code, you really don't need a DI container. Is your real-world scenario for sure going to need that? I'd say that any ASP.NET Core application should use DI as it is constructor injected into your artifacts seamlessly by the framework, but in other cases it might make sense to create a composition root in `Main` and create your dependencies there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T09:24:43.040", "Id": "471357", "Score": "0", "body": "@AndreasHassing Thank you. Yes a DI container is in my opinion highly recommended. Its a larger business application with a plugin structure." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T11:41:09.390", "Id": "240140", "Score": "4", "Tags": [ "c#", "dependency-injection" ], "Title": "Sharing User Inputs via Dependency Injection" }
240140
<p>Yesterday I hacked up a simple component selection program. An example is shown at the bottom for the application, though this can be used generally for a lot of different simple circuits I come across.</p> <p>It requires Python 3; I've only tested it on 3.8.</p> <p>About the code:</p> <ul> <li>It is self-contained</li> <li>The only really notable violation of PEP8 is capitalized local variables, but they're there for a reason - that's electronics notation</li> <li>There are no unit tests, but the code is probably correct given the output of the example, at least for non-corner-cases</li> <li>I know there are some algorithmic inefficiencies, in particular in dealing with minima/maxima</li> <li>The display of output values that are non-zero but below the noise level of floating-point math is awkward</li> </ul> <p>Commentary of any kind welcome.</p> <pre><code>""" Do a quick, sequential, numerical (not symbolic) exploration of some electronic component values to propose solutions that use standard, inexpensive parts. """ from bisect import bisect_left from functools import partial from itertools import islice from math import log10, floor from typing import ( Iterable, List, Optional, Protocol, Sequence, Set, Tuple, ) # See https://en.wikipedia.org/wiki/E_series_of_preferred_numbers E24 = ( 1.0, 1.1, 1.2, 1.3, 1.5, 1.6, 1.8, 2.0, 2.2, 2.4, 2.7, 3.0, 3.3, 3.6, 3.9, 4.3, 4.7, 5.1, 5.6, 6.2, 6.8, 7.5, 8.2, 9.1, ) def bisect_lower(a: Sequence[float], x: float) -&gt; int: """ Run bisect, but use one index before the return value of `bisect_left` :param a: The sorted haystack :param x: The needle :return: The index of the array element that equals or is lesser than `x` """ i = bisect_left(a, x) if i &lt; len(a) and a[i] &gt; x: i -= 1 return i def approximate(x: float) -&gt; (int, float): """ Approximate a value by using the E24 series. :param x: Any positive value :return: An integer index into E24 for the element lesser than or equal to the value's mantissa, and the value's decade - a power of ten """ decade = 10**floor(log10(x)) mantissa = x / decade index = bisect_lower(E24, mantissa) if index &gt;= len(E24): return 0, decade * 10 return index, decade def fmt_eng(x: float, unit: str, sig: int = 2) -&gt; str: """ Format a number in engineering (SI) notation :param x: Any number :param unit: The quantity unit (Hz, A, etc.) :param sig: Number of significant digits to show :return: The formatted string """ if x == 0: p = 0 else: p = floor(log10(abs(x))) e = floor(p / 3) digs = max(0, sig - p%3 - 1) mantissa = x / 10**(3*e) if e == 0: prefix = '' elif 0 &lt; e &lt; 9: # See https://en.wikipedia.org/wiki/Metric_prefix prefix = ' kMGTPEZY'[e] elif 0 &gt; e &gt; -8: prefix = 'mμnpfazy'[-e] else: raise IndexError(f'Number out of SI range: {x:.1e}') fmt = '{:.%df} {:}{:}' % digs return fmt.format(mantissa, prefix, unit) class CalculateCall(Protocol): """ Protocol-notation to type-hint a callable with any number of floating-point arguments, returning a float """ def __call__(self, *args: Iterable[float]) -&gt; float: ... class ComponentValue: """ A component value, without knowledge of the component it's from - to track approximated values """ def __init__( self, decade: Optional[float] = None, index: Optional[int] = None, exact: Optional[float] = None, ): """ Valid combinations: exact - approximated value will be calculated exact, index, decade - approximated value = E24[index]*decade index, decade - approximated value = E24[index]*decade; exact=approximate :param decade: The quantity's power-of-ten :param index: The integer index into E24 for the quantity's mantissa :param exact: The exact quantity, if known """ if index is None: assert decade is None assert exact is not None self.exact = exact self.index, self.decade = approximate(exact) else: assert decade is not None self.index, self.decade = index, decade self.approx = E24[self.index] * self.decade if index is not None: if exact is None: self.exact = self.approx else: self.exact = exact @property def error(self) -&gt; float: return self.approx / self.exact - 1 def get_other(self) -&gt; Optional['ComponentValue']: """ :return: If this approximated value is below its exact value, then the next-highest E24 value; otherwise None """ if self.approx &gt;= self.exact: return None index, decade = self.index + 1, self.decade if index &gt;= len(E24): index = 0 decade *= 10 return ComponentValue(exact=self.exact, index=index, decade=decade) def __str__(self): e = floor(log10(self.exact) / 3) * 3 v = self.approx / 10**e return f'{v:.3f}e{e} {self.error:.1%}' class Component: """ A component, without knowledge of its value - only bounds and defining formula """ def __init__( self, prefix: str, suffix: str, unit: str, calculate: Optional[CalculateCall] = None, minimum: float = 0, maximum: Optional[float] = None, use_for_err: bool = True, ): """ :param prefix: i.e. R, C or L :param suffix: Typically a number, i.e. the "2" in R2 :param unit: i.e. Hz, A, F, ... :param calculate: A callable that will be given all values of previous components in the calculation sequence. These values are floats, and the return must be a float. If this callable is None, the component will be interpreted as a degree of freedom. :param minimum: Min allowable value; the return of calculate will be checked against this and failures will be silently dropped. Must be at least zero, or greater than zero if calculate is not None. :param maximum: Max allowable value; the return of calculate will be checked against this and failures will be silently dropped. :param use_for_err: If True, error from this component's ideal to approximated value will influence the solution rank. """ ( self.prefix, self.suffix, self.unit, self.calculate, self.min, self.max, self.use_for_err, ) = prefix, suffix, unit, calculate, minimum, maximum, use_for_err assert minimum &gt;= 0 assert maximum is None or maximum &gt;= minimum if calculate: self.values = self._calculate_values else: assert minimum &gt; 0 self.start_index, self.start_decade = approximate(minimum) self.values = self._iter_values def __str__(self): return self.name @property def name(self) -&gt; str: return f'{self.prefix}{self.suffix}' def _calculate_values(self, prev: Sequence[ComponentValue]) -&gt; Iterable[ComponentValue]: def values(): # Get the value based on exact values first from_exact_val = self.calculate(*(p.exact for p in prev)) if from_exact_val &lt;= 0: return from_exact = ComponentValue(exact=from_exact_val) yield from_exact other = from_exact.get_other() if other: yield other # See if there's a difference when calculating against approximated values from_approx_val = self.calculate(*(p.approx for p in prev)) if from_approx_val &gt; 0: from_approx = ComponentValue(exact=from_approx_val) if from_approx.exact != from_exact.exact: yield from_approx other = from_approx.get_other() if other: yield other for v in values(): if self.min &lt;= v.exact &lt;= self.max: yield v def _all_values(self) -&gt; Iterable[Tuple[int, float]]: decade = self.start_decade for index in range(self.start_index, len(E24)): yield index, decade while True: decade *= 10 for index in range(len(E24)): yield index, decade def _iter_values(self, prev: Sequence[ComponentValue]) -&gt; Iterable[ComponentValue]: for index, decade in self._all_values(): value = ComponentValue(index=index, decade=decade) if value.approx &gt; self.max: return yield value class Resistor(Component): def __init__( self, suffix: str, calculate: Optional[CalculateCall] = None, minimum: float = 0, maximum: Optional[float] = None, use_for_err: bool = True, ): super().__init__('R', suffix, 'Ω', calculate, minimum, maximum, use_for_err) class Capacitor(Component): def __init__( self, suffix: str, calculate: Optional[CalculateCall] = None, minimum: float = 0, maximum: Optional[float] = None, use_for_err: bool = True, ): super().__init__('C', suffix, 'F', calculate, minimum, maximum, use_for_err) class Output: """ A calculated parameter - potentially but not necessarily a circuit output - to be calculated and checked for error in the solution ranking process. """ def __init__(self, name: str, unit: str, expected: float, calculate: CalculateCall): """ :param name: i.e. Vout :param unit: i.e. V, A, Hz... :param expected: The value that this parameter would assume under ideal circumstances :param calculate: A callable accepting a sequence of floats - one per component, in the same order as they were passed to the Solver constructor; returning a float. """ self.name, self.unit, self.expected, self.calculate = name, unit, expected, calculate def error(self, value: float) -&gt; float: """ :return: Absolute error, since the expected value might be 0 """ return value - self.expected def __str__(self): return self.name class Solver: """ Basic recursive solver class that does a brute-force search through some component values. """ def __init__( self, components: Sequence[Component], outputs: Sequence[Output], threshold: float = 1e-3, ): """ :param components: A sequence of Component instances. The order of this sequence determines the order of parameters passed to Output.calculate and Component.calculate. :param outputs: A sequence of Output instances - can be empty. :param threshold: Maximum error above which solutions will be discarded """ self.components, self.outputs = components, outputs self.candidates: List[Tuple[ float, # error Sequence[float], # output values Sequence[ComponentValue], # component values to get the above ]] = [] self.approx_seen: Set[Tuple[float, ...]] = set() self.threshold = threshold def _recurse(self, values: List[Optional[ComponentValue]], index: int = 0): if index &gt;= len(self.components): self._evaluate(values) else: comp = self.components[index] for v in comp.values(values[:index]): values[index] = v self._recurse(values, index+1) def solve(self): """ Recurse through all of the components, doing a brute-force search. Results are stored in self.candidates and sorted in order of increasing error. """ values = [None]*len(self.components) self._recurse(values) self.candidates.sort(key=lambda v: v[0]) def _evaluate(self, values: Sequence[ComponentValue]): approx = tuple(v.approx for v in values) if approx in self.approx_seen: return outputs = tuple( o.calculate(*approx) for o in self.outputs ) err = sum( o.error(v)**2 for o, v in zip(self.outputs, outputs) ) + sum( v.error**2 for c, v in zip(self.components, values) if c.use_for_err ) if err &lt; self.threshold: self.candidates.append((err, outputs, tuple(values))) self.approx_seen.add(approx) def print(self, top: int = 10): """ Print a table of all component values, output values and output error. :param top: Row limit. """ print(' '.join( f'{comp.name:&gt;6}' for comp in self.components ), end=' ') print(' '.join( f'{output.name:&gt;10} {"Err":&gt;8}' for output in self.outputs )) for err, outputs, values in islice(self.candidates, top): print(' '.join( f'{fmt_eng(value.approx, comp.unit):&gt;6}' for value, comp in zip(values, self.components) ), end=' ') print(' '.join( f'{fmt_eng(value, output.unit, 4):&gt;10} ' f'{output.error(value):&gt;8.1e}' for value, output in zip(outputs, self.outputs) )) def example(): """ This represents a simple level shifter; see https://electronics.stackexchange.com/a/491649/10008 Output: R1 R2 R4 R3 Voutmin Err Voutmax Err 120 Ω 30 kΩ 7.5 kΩ 16 kΩ 0.000 V 0.0e+00 3.300 V 0.0e+00 150 Ω 12 kΩ 3.0 kΩ 24 kΩ 0.000 V 0.0e+00 3.300 V 0.0e+00 33 Ω 30 kΩ 7.5 kΩ 1.5 kΩ 55.51 zV 5.6e-17 3.300 V 4.4e-16 75 Ω 12 kΩ 3.0 kΩ 2.0 kΩ -55.51 zV -5.6e-17 3.300 V 4.4e-16 110 Ω 30 kΩ 7.5 kΩ 12 kΩ 166.5 zV 1.7e-16 3.300 V 4.4e-16 160 Ω 12 kΩ 3.0 kΩ 75 kΩ 600.0 nV 6.0e-04 3.303 V 3.0e-03 160 Ω 30 kΩ 7.5 kΩ 200 kΩ -1.000 μV -1.0e-03 3.295 V -5.0e-03 160 Ω 33 kΩ 8.2 kΩ 220 kΩ 2.885 μV 2.9e-03 3.294 V -5.6e-03 160 Ω 27 kΩ 6.8 kΩ 180 kΩ -5.748 μV -5.7e-03 3.296 V -4.3e-03 130 Ω 36 kΩ 9.1 kΩ 27 kΩ -7.463 μV -7.5e-03 3.299 V -6.5e-04 """ Vcc = 3.3 Imin, Imax = 4e-3, 20e-3 def Vout(Iin: float, R1: float, R2: float, R4: float, R3: float) -&gt; float: Vin = R1*Iin I4 = (Vcc - Vin)/R2 - Vin/R3 return Vin - R4*I4 s = Solver( ( Resistor( '1', None, 30, Vcc/Imax, False ), Resistor( '2', None, 1e3, 100e3, False, ), Resistor( '4', lambda R1, R2: R2/(Imax/Imin - 1), 1e3, 1e6, False ), Resistor( '3', lambda R1, R2, R4: 1/((Vcc/R1/(Imax - Imin) - 1)/R4 - 1/R2), 1e3, 1e6, False ), ), ( Output('Voutmin', 'V', 0, partial(Vout, Imin)), Output('Voutmax', 'V', Vcc, partial(Vout, Imax)), ), threshold=1e-4, ) s.solve() s.print(10) </code></pre>
[]
[ { "body": "<p>First of all, I find your code very clean and I want to stress my Python proficiency is quite below yours. So I am learning more from you than you will from me. Nonetheless code review exercises are interesting because they force me to do research and learn more in the process.</p>\n\n<p>My background in electronics is rather basic so I have only one remark at the moment. In the <code>Solver</code> class you have defined a <code>print</code> function. Probably I would have simply called the function <code>print_table</code> or similar. You are even using <code>print</code> in a function that is named the same. I find that slightly odd given that <code>print</code> is already a built-in function personally but I may be too conservative. I would be worried about potential downsides or risk of redefining an existing function.</p>\n\n<p>I looked up the list of reserved keywords and built-in names in Python. For reference here is one topic on SO: <a href=\"https://stackoverflow.com/a/22864250/6843158\">Is the list of Python reserved words and builtins available in a library?</a></p>\n\n<p>Demonstration code based on the above mentioned topic:</p>\n\n<pre><code>import builtins\n\n# dump the whole list\ndir(builtins)\n\n# returns True\n'print' in dir(builtins)\n</code></pre>\n\n<p>Not sure if this a real problem.</p>\n\n<hr>\n\n<p>I ran your example:</p>\n\n<pre>\n R1 R2 R4 R3 Voutmin Err Voutmax Err\n 120 Ω 30 kΩ 7.5 kΩ 16 kΩ 0.000 V 0.0e+00 3.300 V 0.0e+00\n 150 Ω 12 kΩ 3.0 kΩ 24 kΩ 0.000 V 0.0e+00 3.300 V 0.0e+00\n 33 Ω 30 kΩ 7.5 kΩ 1.5 kΩ 55.51 zV 5.6e-17 3.300 V 4.4e-16\n 75 Ω 12 kΩ 3.0 kΩ 2.0 kΩ -55.51 zV -5.6e-17 3.300 V 4.4e-16\n 110 Ω 30 kΩ 7.5 kΩ 12 kΩ 166.5 zV 1.7e-16 3.300 V 4.4e-16\n 160 Ω 12 kΩ 3.0 kΩ 75 kΩ 600.0 nV 6.0e-04 3.303 V 3.0e-03\n 160 Ω 30 kΩ 7.5 kΩ 200 kΩ -1.000 μV -1.0e-03 3.295 V -5.0e-03\n 160 Ω 33 kΩ 8.2 kΩ 220 kΩ 2.885 μV 2.9e-03 3.294 V -5.6e-03\n 160 Ω 27 kΩ 6.8 kΩ 180 kΩ -5.748 μV -5.7e-03 3.296 V -4.3e-03\n 130 Ω 36 kΩ 9.1 kΩ 27 kΩ -7.463 μV -7.5e-03 3.299 V -6.5e-04\n</pre>\n\n<hr>\n\n<p>Regarding <strong>tabular output</strong> I have found the <a href=\"https://pypi.org/project/tabulate/\" rel=\"nofollow noreferrer\">tabulate module</a> to be great and quite flexible so I often use it in conjunction with Pandas. I am not sure it supports merged cells which may come in handy, but it should not be difficult to get around this if needed.\nOf course I can easily understand that you don't want to import or install another dependency for something you can perform efficiently in 10 lines of code. And here you are gathering the data on the fly, it's not like you have an already populated dataframe just waiting to be printed out.</p>\n\n<p>I might like to enhance this part of the code to customize the output of the results, for example to export the data to <strong>CSV</strong> instead of tabular format. This could be interesting if you want to use this procedure to automatically generate <strong>bills of materials</strong> for ordering electronic components. Since you are mentioning a \"simple component selection program\" I was thinking that could have been the original intention.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T18:42:01.270", "Id": "471072", "Score": "0", "body": "Re. `print` - it's a valid point. It's less of a concern because a `print` function bound to an object will not shadow the built-in `print` function - unlike if I had defined a non-bound function or a variable, in which case it would shadow the built-in." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T18:43:45.200", "Id": "471073", "Score": "0", "body": "Re. bill of materials - also a valid point; however, the CSV would only be used as a starting point since it would be missing vendor, price and model information, etc." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T18:05:05.897", "Id": "240158", "ParentId": "240141", "Score": "2" } } ]
{ "AcceptedAnswerId": "240158", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T12:55:19.893", "Id": "240141", "Score": "3", "Tags": [ "python", "algorithm", "python-3.x", "search" ], "Title": "Brute-force electronic component selection space search" }
240141
<p>I am quite new to the MVC concept. I already know how to program object-orientated from other languages like C++ or Java. I have implemented a little login system for test purpose. I am not sure if my implementation is the best way to follow MVC. Any feedback is welcome.</p> <p>The class <code>ControllerUser</code> is instantiated in a file called <code>init.php</code>. The <code>$controllerUser</code> variable is therefore accessible on every page. I am also not sure if this is the best way. Can somebody also explain to me when to use the view class and which functions should it have? I know that it should render/output the page and the data... does this mean that it should print the logout/login form?</p> <p>This is my database class in which the connection is established. All models will inherit from this class.</p> <p><code>class.database.php</code></p> <pre><code>class Database { protected $pdo; public function connect() { $datahost = 'localhost'; $datauser = 'root'; $datapass = 'PASSWORD'; $database = 'DATABASE'; try { $options = [ PDO::ATTR_DEFAULT_FETCH_MODE =&gt; PDO::FETCH_ASSOC ]; $this-&gt;pdo = new PDO('mysql:host='.$datahost.';dbname='.$database.'', $datauser, $datapass, $options); } catch (PDOException $e) { print "Mysql Connection failed: " . $e-&gt;getMessage(); die(); } } public function disconnect() { $this-&gt;pdo = NULL; } } </code></pre> <p>Everything will have an own model, controller and view, when necessary. In this case it is the user.</p> <p>User controller:<br> <code>controller.user.php</code></p> <pre><code>&lt;?php class ControllerUser { private $model; function __construct($datatable) { $this-&gt;model = new ModelUser($datatable); } public function login($email, $password) { $user = $this-&gt;model-&gt;getByEmail($email); if($user &amp;&amp; password_verify($password,$user['password'])) { if($user['status']==1) { if($user['verified']==1) { $_SESSION['id'] = $user['id']; $this-&gt;model-&gt;updateIP($user['id']); return true; } else { throw new Exception('Not verified!'); } } else { throw new Exception('Your account is locked. Contact a staff member.'); } } else { throw new Exception('Email or password wrong!'); } } public function logout() { if($this-&gt;isLoggedIn()) { session_destroy(); unset($_SESSION['id']); return true; } } public function isLoggedIn() { if(isset($_SESSION['id'])) { $status = $this-&gt;model-&gt;getById($_SESSION['id'])['status']; if($status==1) { return true; } else { throw new Exception('Your account is locked. Contact a staff member.'); } } } } ?&gt; </code></pre> <p>User model:<br> <code>model.user.php</code></p> <pre><code>&lt;?php class ModelUser extends Database { private $datatable; function __construct($datatable) { $this-&gt;connect(); $this-&gt;datatable = $datatable; } public function getByEmail($email) { $stmt = $this-&gt;pdo-&gt;prepare("SELECT * FROM ". $this-&gt;datatable ." WHERE email = :email"); $result = $stmt-&gt;execute(['email' =&gt; $email]); return $stmt-&gt;fetch(); } public function getById($id) { $stmt = $this-&gt;pdo-&gt;prepare("SELECT * FROM ". $this-&gt;datatable ." WHERE id = :id"); $result = $stmt-&gt;execute(['id' =&gt; $id]); return $stmt-&gt;fetch(); } public function updateIP($id) { $statement = $this-&gt;pdo-&gt;prepare("UPDATE ". $this-&gt;datatable ." SET ip = :ip WHERE id = :id"); return $statement-&gt;execute(['ip' =&gt; $_SERVER['REMOTE_ADDR'], 'id' =&gt; $id]); } function __destruct() { $this-&gt;disconnect(); } } ?&gt; </code></pre> <p>User view... I am not sure what could be inside of view... The function there is only for test purpose:<br> <code>view.user.php</code></p> <pre><code>&lt;?php class ViewUser { public function printUserInformation($data) { foreach($data as $key =&gt; $value){ echo $key.': '.$value.'&lt;br&gt;'; } } } ?&gt; </code></pre> <p>Everything comes to use on the login page:<br> <code>login.php</code></p> <pre><code>&lt;?php if(isset($_GET['login'])) { $viewUser = new ViewUser(); //test $modelUser = new ModelUser("users"); //test try { $controllerUser-&gt;login($_POST['email'], $_POST['password']); $viewUser-&gt;printUserInformation($modelUser-&gt;getById($_SESSION['id'])); //just a test } catch(Exception $e) { echo $e-&gt;getMessage(); } } if(isset($_GET['logout'])) { $controllerUser-&gt;logout(); } if(!$controllerUser-&gt;isLoggedIn()) { ?&gt; &lt;form class="login-form" action="?login=1" method="post"&gt; &lt;input type="email" size="40" maxlength="250" name="email" placeholder="Email address" required&gt; &lt;input type="password" size="40" maxlength="250" name="password" placeholder="Password" required&gt; &lt;button type="submit" value="Login" class="button style1"&gt;login&lt;/button&gt; &lt;input type="checkbox" id="stayloggedin" name="stay_loggedin"&gt;&lt;label for="stay_loggedin" &gt;stay logged in&lt;/label&gt; &lt;/form&gt; &lt;?php } else { ?&gt; &lt;form class="logout" action="?logout=1" method="POST" style="display: inline-block;"&gt; &lt;button type="submit" name="logout"&gt;logout&lt;/button&gt; &lt;/form&gt; &lt;?php } ?&gt; </code></pre>
[]
[ { "body": "<p>You have a lot of problems in your code, so let's break them down.</p>\n\n<p>First, you have a database class that is useless. Add all of your database access config (user, password, host, etc) in configuration files. Preferably in environment variables. Then, use PDO directly when you need a connection.</p>\n\n<p>Second, you have a <code>ModelUser</code> class. Imagine your manager comes and requests you a feature to notify the user when he doesn't log in for a month. Is he gonna say \"I want to notify the model user\" or \"I wan to notify the user\"? So, rename your classe to <code>User</code>.</p>\n\n<p>Third, your domain class (<code>User</code>) knows about database details. What if you want to save it in a file? Or send it throught a message queue? An <code>User</code> must have <code>email</code>, <code>password</code>, etc. It doesn't have a <code>$database</code>. That doesn't make sense.\nSearch for <code>Entity</code> and <code>Repository</code> patterns.</p>\n\n<p>Fourth, you said: \"The class ControllerUser is instantiated in a file called init.php\". That's not cool. You should use the front controller pattern. You have a single entry point in your application that configures routes and tells to which controller a request should go.</p>\n\n<p>Fifth, a Controller must only:</p>\n\n<ol>\n<li>Receive a request</li>\n<li>Return a response</li>\n</ol>\n\n<p>Sixth, the view layer can't have any logic. It should be just html.</p>\n\n<p>Seventh, you should follow the PSR-12 in you code style: <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"noreferrer\">https://www.php-fig.org/psr/psr-12/</a></p>\n\n<p>I strongly sugest you study more about OOP, Domain-Driven Design, design patterns, etc.</p>\n\n<p>I have a simple MVC example but the code is in Portuguese:\n<a href=\"https://github.com/CViniciusSDias/php-mvc\" rel=\"noreferrer\">https://github.com/CViniciusSDias/php-mvc</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T14:48:24.513", "Id": "471792", "Score": "1", "body": "I am a little bit confused. You said that the controller must only get a request and return a response. I read on many pages that the controller has all the logic and the model all the database stuff. Therefore, when a user should be notified there would be a function in the controller called notifyInactive() or so which then calls the function of the model to get data of inactive users. Then the controller would use that and send an email to those. That is how I understand it..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T17:53:26.763", "Id": "471823", "Score": "3", "body": "On many pages they were wrong. You can read the books related to MVC from the 80's that used smaltalk to understand how MVC really works.\nImagine this: You have all your business logic in your controller, and now you need to run the same logic from the CLI. How would you do it? You can't run the Controller from the CLI, right? That's why the controller just receives a request and returns a response. The logic HAS to be elsewhere." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T21:13:19.210", "Id": "471830", "Score": "2", "body": "Well... that's unfortunate that many pages are wrong on that topic. I'll then have to rethink everything. But the concept of OOP is not stuck together with MVC, meaning that you don't need to know MVC to know OOP. The only thing I need to investigate further are those books you named (and maybe the standard coding styles). Thanks for the feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T20:36:10.033", "Id": "471948", "Score": "0", "body": "You are right. OOP is not stuck with MVC. You can study more robust architecture patterns other than MVC, like: Hexagonal Architecture, Clean Architecture, SOA, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T13:02:53.207", "Id": "472026", "Score": "1", "body": "Looking at the tag page I thought at first: gosh, a spammer! But now I see you know your stuff. Welcome to codereview!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T23:56:52.897", "Id": "240469", "ParentId": "240144", "Score": "6" } } ]
{ "AcceptedAnswerId": "240469", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T13:56:35.747", "Id": "240144", "Score": "5", "Tags": [ "php", "mvc" ], "Title": "PHP OOP MVC structure" }
240144
<p>I'm currently trying to process a corpus of a million patent text files, which contain about 10k non-unique words on average. My current data pipeline works as follows:</p> <ol> <li>Load the patent texts as strings from a local sqlite database table</li> <li>Tokenize¹ each document and save the results in a new table</li> <li>Create a dictionary containing all unique words in the corpus</li> <li>Train an tfidf model with the tokenized documents</li> </ol> <p>¹Tokenization means taking a document text (string) as input and returning a list containing every word in the document (duplicates allowed). Words tend to be separated by spaces, special characters, numbers etc., the regex in my code has served quite well for this purpose. </p> <p>In my data pipeline, I identified the tokenize function as my bottleneck, the relevant part is provided in my MWE below:</p> <pre><code>import re import urllib.request import time url='https://raw.githubusercontent.com/mxw/grmr/master/src/finaltests/bible.txt' doc=urllib.request.urlopen(url).read().decode('utf-8') PAT_ALPHABETIC = re.compile(r'[^\W\d]+') def tokenize(text): matches=PAT_ALPHABETIC.finditer(text) for match in matches: yield match.group() def preprocessing(doc): tokens = [token for token in tokenize(doc)] return tokens start_time = time.time() preprocessing(doc) print("--- %s seconds ---" % (time.time() - start_time)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T22:50:25.067", "Id": "471091", "Score": "0", "body": "Is that a *vocabulary* of 10k distinct words per document (*not* mean, esp. with stemming), or a mere 10 k words per text file - say, about 100 k characters? I would not consider the latter *very big*, but `a large amount` again may amount to a considerable total." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T08:59:23.143", "Id": "471119", "Score": "0", "body": "It's the latter one. I'm processing roughly a million patent texts which tend to have 10-20k (non-distinct) words per text on average. Due to the technical nature of patents, the number of distinct words also gets very large when considering the whole corpus." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T10:12:55.087", "Id": "471123", "Score": "0", "body": "I'd expect insight into the overall problem more promising with more code context provided. Can you present, in your question (where information like *patent texts* would be placed advantageously), method and measurement results that let you `[identify] the tokenize function as [the] bottleneck`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T10:24:08.787", "Id": "471124", "Score": "0", "body": "Hip-shot: time `WHITE_DIGITS = re.compile(r'[\\W\\d]+')` `WHITE_DIGITS.split(doc)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T10:48:54.673", "Id": "471125", "Score": "0", "body": "Did not result in any runtime improvement but thanks for the suggestion" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T11:27:38.987", "Id": "471126", "Score": "2", "body": "Welcome to Code Review. Unfortunately, you may have misunderstood this site. A Minimum Working Example is something Stack Overflow loves (also known as MCVE). On Code Review however, we need to see the real deal. The actual code. So your question risks getting closed even though it's answered. Please keep this in mind for your next question (and no, please don't touch the code now an answer has come in). For future reference, please see our [FAQ on How to get the best value out of Code Review - Asking Questions](https://codereview.meta.stackexchange.com/q/2436/52915)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T13:11:08.723", "Id": "471129", "Score": "0", "body": "Also, how fast do you need this to be? On my machine this code runs in about 0.36 seconds. This would mean the script would run less than five days for one million of these. This may be OK if you need to do it only once. Although the real bottleneck of the script you showed us is getting the file in the first place, of course. This takes about 1.5 seconds on my machine." } ]
[ { "body": "<p>I would guess that you're never going to take another 50% off. You could consider pulling the problem down into C or Haskell or Awk or whatever and then binding that more tightly optimized implementation back up into python; IDK. </p>\n\n<p>As for more incremental improvements, it depends a bit how the thing is going to be used. </p>\n\n<p>You flagged the question for multi-threading. That certainly might help, but you'll have to figure out how to divy up the job. Maybe there are natural split-off points that can be identified without actually reading the subject data, in which case any parallelization system will probably work. Maybe you can figure out the size of the subject on disk, and open multiple readers against that file starting at evenly spaced offsets; in this case you'll need to figure out the fence-posting when you combine the results of each of the workers. </p>\n\n<p>I notice that the function <code>preprocessing</code> just wraps the iterable results up in a list. Is that necessary? If you can avoid ever actualizing the whole 10k-items list in memory that will likely help some.</p>\n\n<p>Similarly, you're reading the whole file (http payload) as a single string. Both file handles and HTTPResponse objects will let you read just a chunk at a time; this would let you handle the subject data like a lazy iterable (similar to the way you're yielding from <code>.finditer()</code>). Of course how much of an advantage this is for you will depend on the underlying implementation, and you'll have to be careful about fence-posting again. This may also be a good way to break off jobs for parallelization. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T16:02:08.637", "Id": "240148", "ParentId": "240145", "Score": "2" } }, { "body": "<p>Some small performance can be gained by directly yielding from the iterator instead of having a <code>for</code> loop do it, using the <code>yield from</code> keywords, and using <code>list()</code> instead of a list comprehension:</p>\n\n<pre><code>def tokenize2(text):\n yield from PAT_ALPHABETIC.finditer(text)\n\ndef preprocessing2(doc):\n return list(tokenize2(doc))\n</code></pre>\n\n<p>For the given example document this gives about a 15% speed-up:</p>\n\n<pre><code>In [15]: %timeit preprocessing(doc)\n335 ms ± 2.29 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\nIn [16]: %timeit preprocessing2(doc)\n287 ms ± 2.79 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n</code></pre>\n\n<p>Slightly faster yet is not even having the <code>preprocessing</code> function and directly returning all tokens (this avoids one function call and lets the <code>re</code> do its best):</p>\n\n<pre><code>def tokenize3(text):\n return PAT_ALPHABETIC.findall(text)\n</code></pre>\n\n<p>This is about 35% faster then the code in the OP: </p>\n\n<pre><code>In [21]: %timeit tokenize3(doc)\n217 ms ± 1.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n</code></pre>\n\n<p>Other than that, we can't really help you without seeing more of your script. You can probably parallelize this task by scanning multiple documents in parallel, and especially by making downloading and scanning asynchronous, so that you scan a document whenever it finishes downloading, but already download the next document(s) in the background.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T13:18:03.247", "Id": "240203", "ParentId": "240145", "Score": "2" } } ]
{ "AcceptedAnswerId": "240203", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T14:50:39.700", "Id": "240145", "Score": "1", "Tags": [ "python", "performance", "python-3.x", "regex" ], "Title": "Tokenizing a large document" }
240145
<p>I have written a SQL server stored procedure to generate "log" tables which store the old values of rows when a table is updated, and also record when rows are deleted ( and by who ). It's quite straight-forward, the log table has identical rows to the table being logged, plus a "Changed" column which records the date the data was changed. A trigger is used to copy the old value of the row to the log table.</p> <p>LogTable is the main procedure, function GetColumns computes a list of column names ( optionally with type declaration ), and Columns is a view that computes the column type declaration from system tables, Objects is a view of all database objects. The comment at the top of LogTable is to remind me to set up the "UpdatedBy" column in the table being logged before enabling logging - this is not required, but allows tracking of who did the update ( or created the row in the first place ).</p> <p>Handler is a table which generates stored procedures which handle http requests, setting the flag LogDelete enables the generation code which logs the deletion of a row.</p> <p>I don't have any specific questions for review. I am aware of the <a href="https://docs.microsoft.com/en-us/sql/relational-databases/track-changes/track-data-changes-sql-server?view=sql-server-ver15" rel="nofollow noreferrer">integrated feature for tracking changes</a>, but decided it was simpler and more transparent doing it this way, with changes easily visible in the log tables, and this approach is not dependent on the version of SQL server being used.</p> <pre><code> CREATE procedure perfect.[LogTable] @table int as /* To log which user made changes, before setting up logging for a table, add a field UpdatedBy int to the table to be logged. This should be set as an Auto field in the Add and Update handlers, set to @cu. */ declare @sql nvarchar(max), @table_schema nvarchar(128), @table_name nvarchar(128), @tname nvarchar(max), @lname nvarchar(max) select @table_schema = Sch, @table_name = Name from perfect.Objects where id = @table set @tname = quotename( @table_schema) + '.' + quotename(@table_name ) -- full name of table being logged set @lname = 'log.' + quotename( @table_schema + '_' + @table_name ) -- full name of log table -- Create log table that stores deleted row when a table if updated or deleted. select @sql = 'create table ' + @lname + '(Changed datetime,' + perfect.GetColumns( @table, 1 ) + ')' execute( @sql ) -- Create a clustered index for the log table. select @sql = 'create clustered index ' + quotename('CI_' + @table_schema + @table_name ) +' on ' + @lname + '(id,Changed)' execute( @sql ) -- Create trigger that saves the deleted rows when the table is updated or deleted. select @sql = 'create trigger ' + quotename(@table_schema) + '.' + quotename(@table_name + 'logtrigger' ) + ' on ' + @tname + ' for update, delete as insert into ' + @lname + '(Changed,' + perfect.GetColumns( @table, 0 ) + ') select getdate(),'+ perfect.GetColumns( @table, 0 ) + ' from deleted' execute( @sql ) -- Create table for logging deletes. select @sql = 'create table log.' + quotename(@table_schema + '_Del_' + @table_name) + '(id int,Deleted datetime,DeletedBy int)' execute( @sql ) -- Enable logging of deletes in Edit handlers. update perfect.Handler set LogDelete = 1 where Sch = @table_schema and TableName = @table_name and Kind = 4 CREATE function perfect.[GetColumns] ( @table int, @option int ) returns nvarchar(max) as begin declare @result nvarchar(max) declare c cursor local for select quotename(Name) + case when @option = 1 then ' ' + Type + Nullable else '' end from perfect.Columns where Table_id = @table order by Name declare @s nvarchar(200) open c while 1 = 1 begin fetch next from c into @s if @@fetch_status != 0 break select @result = case when @result is null then '' else @result + ',' end + @s end close c deallocate c return @result end CREATE view perfect.Columns as select O.object_id as Table_id, C.Column_name as Name, Data_type + case when Data_type IN ('char','nchar','varchar','nvarchar','binary','varbinary') then case when Character_maximum_length &gt; 0 then '(' + convert(varchar,Character_maximum_length) + ')' else '(max)' end when Data_type IN ('decimal','numeric') then '(' + convert(varchar,Numeric_precision) + ',' + convert(varchar,Numeric_scale) + ')' else '' end as Type, case when Is_nullable='no' then ' not null' else '' end as Nullable from sys.all_objects as O inner join sys.schemas as S on S.Schema_id = O.Schema_id inner join information_schema.Columns as C on C.Table_schema = S.Name and C.Table_name = O.Name where O.Type in ( 'U','V' ) -- Tables and Views CREATE view [perfect].[Objects] as select O.object_id as id, S.Name as Sch, O.Name, O.Type, convert(nvarchar(max),P.Value) as Description, O.schema_id from sys.all_objects as O inner join sys.schemas as S on S.schema_id = O.schema_id left join sys.extended_properties as P on P.major_id = O.object_id and P.Name = 'Description' where O.is_ms_shipped = 0 </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T16:44:29.803", "Id": "240149", "Score": "1", "Tags": [ "sql", "sql-server" ], "Title": "Code for tracking changes and deletions to tables" }
240149
<p>I'm a beginner and i just started with automate the boring stuff with python course and reached his first os lesson, so i decided to make a recursive directory size finder since apparently os.path.getsize doesn't get the size of folders. Need a way to improve my code or advice on coding tricks, to make it more efficient</p> <pre class="lang-py prettyprint-override"><code>import os class FileSizeFinder: def calculate_directory_size_in_bytes(self, directory: str, totalsize=0): for filename in tuple(os.listdir(directory)): current_directory = os.path.join(directory, filename) if os.path.isdir(current_directory): totalsize += FileSizeFinder.calculate_directory_size_in_bytes("self", current_directory) if not os.path.isfile(current_directory): continue totalsize += os.path.getsize(current_directory) return totalsize def get_file_size(self, directory: str, totalsize=0): total_size_in_bytes = FileSizeFinder.calculate_directory_size_in_bytes("self", directory) if total_size_in_bytes &gt; 1024000000: totalsize = "Size in GB: " + str(round(total_size_in_bytes / 1024000000, 3)) elif total_size_in_bytes &gt; 1024000: totalsize = "Size in MB: " + str(round(total_size_in_bytes/ 1024000, 3)) elif total_size_in_bytes &gt; 1024: totalsize = "Size in KB: " + str(round(total_size_in_bytes / 1024, 3)) return totalsize print(FileSizeFinder.get_file_size("self", r"E:\Utilities_and_Apps\Python")) </code></pre>
[]
[ { "body": "<h2>File sizes</h2>\n\n<p>1,048,576 bytes are one <code>MiB</code>. 1,000,000 bytes are one <code>MB</code>. 1,024,000 bytes are not anything at all. You should choose the first or second one; the first one goes up in factors of 1,024.</p>\n\n<h2>Bug</h2>\n\n<p>What happens when you pass <code>315</code> to <code>get_file_size</code>? <code>totalsize</code> will not be set.</p>\n\n<h2>Iteration and recursion</h2>\n\n<p>Have a read through this:</p>\n\n<p><a href=\"https://stackoverflow.com/a/1392549/313768\">https://stackoverflow.com/a/1392549/313768</a></p>\n\n<p>which has some great suggestions. Your recursive solution is not the end of the world, but the class implementation is problematic. You've made a class but have not instantiated it, and are passing the string <code>'self'</code> into the <code>self</code> parameter, which is not how this should work. At the absolute least, you should be instantiating <code>FileSizeFinder</code> and then calling the two methods on that instance. Better: define the methods to be <code>@staticmethod</code> so that <code>self</code> is not necessary. Much better: do not use a class at all, and simply have your two functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T13:54:50.840", "Id": "471135", "Score": "1", "body": "i've been looking for this thing called @staticmethod for so long, wish i knew it, yep i didn't go into dept with object oriented programming so i have no idea what self is for.." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T20:15:37.993", "Id": "240163", "ParentId": "240150", "Score": "3" } }, { "body": "<ol>\n<li><p>If there's no reason to make it a class, don't make it a class. (A good clue is that your class doesn't have any instance variables, and that both of its methods could be static without changing the way they work.)</p></li>\n<li><p>Both of your functions return the same information (formatted differently), but one calls it <code>file_size</code> and the other calls it <code>directory_size</code> even though it's the same number. In addition, neither has a type annotation for the return value. This all adds up to make it hard to figure out what each function does. Maybe it'd be better to just have one function that gets the size and a seperate one that formats it as a string?</p></li>\n<li><p>The <code>totalsize</code> parameter does not seem to serve any purpose as a parameter, and should be removed.</p></li>\n<li><p>There's no reason to convert <code>os.listdir</code> into a tuple; you can iterate over it as-is.</p></li>\n<li><p><code>current_directory</code> is not necessarily a directory, so this name is confusing.</p></li>\n<li><p>Your size formatting logic has an obvious gap in its <code>if...elif</code> chain. Adding an <code>else</code> case fixes that.</p></li>\n<li><p>This is a style thing, but I think f-strings are nicer looking than explicitly converting to <code>str</code> and using concatenation.</p></li>\n<li><p>Your GB/MB/KB definitions are both copy+pasted and wrong. Maybe this whole <code>if...elif</code> construction could be done more cleanly by turning the unit definitions into a table (where each unit size is defined exactly once) and iterating over the table?</p></li>\n<li><p>Your recursive function would actually be simpler if it accepted any arbitrary path. That way you wouldn't have to do as much logic inside the body of your iteration over the <code>os.listdir</code> results, and could actually just do it as a simple <code>sum</code> of recursive calls.</p></li>\n<li><p>It's easier to test your code if you write a <code>__main__</code> block that accepts a command line parameter!</p></li>\n</ol>\n\n<p>Here's my massaged version of your code (does basically the same thing, but it uses the units as I've defined them rather than your hybrid 1024 * 10^N units -- having them defined the way I did it here makes it very easy to change if you'd rather make them 2^10, 2^20, etc).</p>\n\n<pre><code>import os\nimport sys\n\ndef recursive_get_size(path: str) -&gt; int:\n \"\"\"Gets size in bytes of the given path, recursing into directories.\"\"\"\n if os.path.isfile(path):\n return os.path.getsize(path)\n if not os.path.isdir(path):\n return 0\n return sum(\n recursive_get_size(os.path.join(path, name))\n for name in os.listdir(path)\n )\n\ndef format_size(num_bytes: int) -&gt; str:\n \"\"\"Formats a size (given in bytes) into a human-readable string.\"\"\"\n for unit_name, unit_size in [\n (\"GB\", 10**9),\n (\"MB\", 10**6),\n (\"KB\", 10**3),\n ]:\n if num_bytes &gt; unit_size:\n return f\"Size in {unit_name}: {round(num_bytes / unit_size, 3)}\"\n else:\n return f\"Size in bytes: {num_bytes}\"\n\nif __name__ == '__main__':\n print(format_size(recursive_get_size(\n sys.argv[1] if len(sys.argv) &gt; 1 else r\"E:\\Utilities_and_Apps\\Python\"\n )))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T13:53:14.580", "Id": "471134", "Score": "1", "body": "yeah i just had this thought and tried to implement it with just the knowledge i've acquired, since you earn experience by doing mistakes and fixing them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T13:55:18.767", "Id": "471136", "Score": "1", "body": "yup, and getting code reviews is exactly the right thing to do to get ideas about better ways to do things! :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T23:34:51.860", "Id": "240175", "ParentId": "240150", "Score": "5" } }, { "body": "<p>Just a few remarks from me:</p>\n\n<ol>\n<li>Rather than <strong>hardcoding</strong> the path in your code it would be better to use a command line <strong>argument</strong>, then it can be used like an OS command such as <code>dir</code> or <code>du</code>. That is more user-friendly since your aim is automation.</li>\n<li>There is no <strong>exception handling</strong> in your code, so it will crash on permission error, which could easily happen, then you have to decide whether to skip or stop execution - but if you don't handle errors the figures are going to be incomplete, misleading and useless</li>\n<li>Overall the function can be implemented more efficiently using <code>os.scandir</code> (<a href=\"https://docs.python.org/3/library/os.html#os.scandir\" rel=\"nofollow noreferrer\">here's why</a>) instead of <code>listdir</code> (your choice)</li>\n<li>Let's mention <code>os.lstat</code> too, which does not follow symbolic links because you probably don't want to count them - I notice that you are on Windows though and probably didn't give thought to the portability of this code</li>\n<li>You could also have taken advantage of <a href=\"https://docs.python.org/3/library/os.html#os.walk\" rel=\"nofollow noreferrer\"><code>os.walk</code></a>.</li>\n<li>In fact, if you are only working on Windows and never develop on Linux machines, then you could have used Powershell and a one-liner could suffice. I would not have bothered with Python personally, not for this job.</li>\n</ol>\n\n<p>In a way this is reinventing the wheel (I just saw the tags now lol but it wasn't me) but there is education value nonetheless. However I would have made more research to find out how programmers have tackled this task before. And then, I would try to improve their code if possible or customize it. The point is to learn from others and not just guess everything and do it all from scratch.</p>\n\n<p>Unsurprisingly what you are trying to do has already been done countless times.\nI was going to quote the same SO post as Reinderien. So make sure you read all of it. Because even the accepted answer can be improved (as is often the case on SO). What is evident is that the task can be accomplished in a more straightforward way.</p>\n\n<p>What I would have done otherwise is read the manual page about os functions, even if it means skimming through, to have an overview of the functions available, then decide on the most adequate functions for the job. As you can see, the Python language is rich enough to provide different ways of doing things.</p>\n\n<p>Python can certainly help you automate the boring stuff, it's just that in this particular case the benefit is not that obvious, considering that your script does not have any options and therefore does less than the tools that already exist.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T02:28:18.450", "Id": "240179", "ParentId": "240150", "Score": "4" } } ]
{ "AcceptedAnswerId": "240175", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T17:20:53.230", "Id": "240150", "Score": "3", "Tags": [ "python", "python-3.x", "reinventing-the-wheel", "file-system" ], "Title": "An entire file size retriever using a recursive os function in python" }
240150
<h2>Project Overview:</h2> <p>See how many times numbers would repeat x times on a digital clock output. This particular code only counts from 12:00 to 11:59, so it's technically only half of a day, I could take the (output x 2) for a full day.</p> <h2>Functions:</h2> <p><strong>input_io()</strong>: Input the number of times you would like to see if a number repeats (for example 11:11 will have the number "1" repeated four times. 12:11 would have 3 repeated "1"s, etc.) </p> <p><strong>gen_times()</strong>: Generate a list of all the "digital clock" outputs starting from 12:00 to 11:59 - including leading zeros for minutes (e.g. 12:04 would need the zero before the "4").</p> <p><strong>count_repeat()</strong>: Test each "clock output" (from gen_times()) to see how many times the numbers 0-9 repeat in each one. If it is greater than the input time add one to the counter.</p> <h2>Questions:</h2> <ol> <li><p>In the code, you'll see that I return values from functions and immediately assign them to variables. I'm not sure the proper conventions of this in Python. Are there ways to pass-through variables from function to function - is it reasonable to assign variables outside of functions to function outputs?</p></li> <li><p>Is there a better way to run this program without all of the coercion? The main use case of the coercion is for the leading zeros when generating times.</p></li> </ol> <h2>Code:</h2> <pre><code>def input_io(): input_repeats = input("Please input the amount of times you'd like to see if numbers repeat") while True: try: input_repeats = int(input_repeats) break except: print("Please enter an integer.") input_repeats = input() return input_repeats input_repeats = input_io() def gen_times(): total_minutes = (24 * 60) / 2 print(f"Total Minutes {total_minutes}") times = ["0"] * int(total_minutes) hours = "12" minutes = "00" i = 0 while (i &lt; total_minutes): if(hours==13): hours=1 times[i] = str(hours)+str(minutes) #print(int(minutes)) if(minutes == "59"): minutes = "00" hours = int(hours) + 1 #ADDING "0" IN FRONT OF HOURS #if(int(hours) &gt;= 10): # hours = hours #else: # hours = "0"+str(hours) else: minutes = str(int(minutes)+1) if (int(minutes) &gt;= 10): minutes = minutes else: minutes = "0" + str(minutes) i += 1 return times times = gen_times() print(times) def count_repeat(): counter_repeat = 0 i=0 ii=0 iterationcounter = 0 while(i != len(times)): ii=0 while(ii &lt; 10): count = times[i].count(str(ii)) #iterationcounter+=1 if count &gt;= int(input_repeats): counter_repeat+=1 break ii+=1 i+=1 return counter_repeat counter_repeat = count_repeat() print(f"Number of Times w/ {input_repeats} repeats: {counter_repeat}") print(counter_repeat,"/",len(times)) percent_repeat = (counter_repeat/len(times)) print("{:.2%}".format(percent_repeat)) #print(iterationcounter) </code></pre>
[]
[ { "body": "<h2>Input loop</h2>\n\n<p>Your</p>\n\n<pre><code> print(\"Please enter an integer.\")\n</code></pre>\n\n<p>can probably be lumped into the <code>input</code> statement after it.</p>\n\n<h2>Time math</h2>\n\n<p>Usually doing your own should be avoided. As an example, this:</p>\n\n<pre><code>total_minutes = (24 * 60) / 2\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>from datetime import timedelta\n# ...\ntotal_minutes = timedelta(hours=12) / timedelta(minutes=1)\n</code></pre>\n\n<h2>General approach</h2>\n\n<p>Currently you're doing a lot of string manipulation, including a stringly-typed <code>hours</code> and <code>minutes</code> in <code>gen_times</code>. Your code would be simpler if, instead of maintaining and incrementing those strings, increment a single <code>datetime.time</code> instance. From there, to get individual digits, you could <a href=\"https://docs.python.org/3/library/datetime.html#datetime.time.strftime\" rel=\"nofollow noreferrer\"><code>strftime</code></a> it to a string and feed that to a <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>Counter</code></a>. The <code>strftime</code> format string in this case would be most useful as <code>'%I%M'</code>.</p>\n\n<h2>Variable names</h2>\n\n<p>Try to avoid names like <code>i</code> and <code>ii</code>. In particular, this:</p>\n\n<pre><code> while(ii &lt; 10):\n count = times[i].count(str(ii))\n #iterationcounter+=1\n if count &gt;= int(input_repeats):\n counter_repeat+=1\n break\n\n ii+=1\n</code></pre>\n\n<p>is better represented as</p>\n\n<pre><code>for digit in range(10):\n count = times[i].count(str(digit))\n if count &gt;= int(input_repeats):\n counter_repeat+=1\n break\n</code></pre>\n\n<p>Though that <code>times[i].count</code> should be replaced with the use of a <code>Counter</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T20:02:04.283", "Id": "240161", "ParentId": "240151", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T17:21:25.960", "Id": "240151", "Score": "2", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Find How Many Times Numbers Repeat on a Digital Clock" }
240151
<p>I have 2 variations of components that I wanted to create in React. They both use Radio buttons with the only difference is one adds an image to one side of it. </p> <p>The first method will use just one component but use conditional logic to display the appropriate HTML:</p> <pre><code> getImgDiv(iconFile) { return (&lt;div&gt;&lt;img src={iconFile} /&gt;&lt;/div&gt;); } render() { var radioId = this.props.radioGroup + this.props.value.replace(" ", ""); var iconFile = this.props.iconFile; var innerLabel = "label-inner no-img"; var imgDiv = ""; if (iconFile !== undefined &amp;&amp; iconFile !== null &amp;&amp; iconFile !== "") { iconFile = "/img/" + iconFile; innerLabel = "label-inner"; // add appropriate class when there is an image imgDiv = this.getImgDiv(iconFile); } return ( &lt;div className="option"&gt; &lt;Field name={this.props.radioGroup} component="input" type="radio" value={this.props.value} id={radioId} /&gt; &lt;label htmlFor={radioId} className="radio-buttons"&gt; &lt;div className={innerLabel}&gt; {imgDiv} &lt;div&gt;&lt;span&gt;{this.props.text}&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; &lt;/label&gt; &lt;/div&gt; ); } </code></pre> <p>The second method, I was thinking of just creating 2 slightly different React classes to handle each case... 1 called RadioBtn the other RadioBtnIcon with the img section added:</p> <pre><code>function RadioBtn({ radioGroup, value, text }) { var radioId = radioGroup + value.replace(" ", ""); return ( &lt;div className="option"&gt; &lt;Field name={radioGroup} component="input" type="radio" value={value} id={radioId} /&gt; &lt;label htmlFor={radioId} className="radio-buttons"&gt; &lt;div className="label-inner no-img"&gt; &lt;div&gt;&lt;span&gt;{text}&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; &lt;/label&gt; &lt;/div&gt; ); } </code></pre> <p>However, its bugging me that neither of these approaches seems particularly elegant... </p> <p>Any suggestions guys?</p> <p>Many Thanks,</p> <p>Phil.</p>
[]
[ { "body": "<p>You can take advantage of <a href=\"https://reactjs.org/docs/conditional-rendering.html\" rel=\"nofollow noreferrer\">conditional rendering</a> to concisely render the <code>iconFile</code> if it exists, and use the conditional operator to construct the outer class name. Using two separate classes for nearly identical functionality is pretty <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">WET</a>, I wouldn't recommend it.</p>\n\n<p>Because the <code>iconFile</code> variable actually contains a <em>string</em> (if it exists), not a <a href=\"https://developer.mozilla.org/en/docs/Web/API/File\" rel=\"nofollow noreferrer\"><code>File</code></a>, consider naming it something else, maybe <code>iconPath</code>:</p>\n\n<pre><code>&lt;label htmlFor={radioId} className=\"radio-buttons\"&gt;\n &lt;div className={\"label-inner\" + (iconPath ? \"\" : \" no-img\")}&gt;\n {iconPath &amp;&amp; &lt;div&gt;&lt;img src={\"/img/\" + iconPath} /&gt;&lt;/div&gt;}\n &lt;div&gt;&lt;span&gt;{text}&lt;/span&gt;&lt;/div&gt;\n &lt;/div&gt;\n&lt;/label&gt;\n</code></pre>\n\n<p>You currently reference properties of <code>this.props</code> a lot. Consider destructuring them all immediately instead.</p>\n\n<p>Since you're using ES6+ syntax, <a href=\"https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75\" rel=\"nofollow noreferrer\">always use <code>const</code></a>, never use <code>var</code>.</p>\n\n<p>It sounds like <code>Field</code> is using the <code>component</code> prop as a tag name. Because variable tag names in JSX need to be upper-case, and because <code>Component</code> could easily be mistaken for <code>React.Component</code>, consider using a different name, maybe <code>Tag</code>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const Field = ({ name, Tag, type, value, id }) =&gt; (\n &lt;Tag name={name} type={type} value={value} id={id} /&gt;\n);\nclass RadioImage extends React.Component {\n render() {\n const { radioGroup, value, iconPath, text } = this.props;\n const radioId = radioGroup + value.replace(\" \", \"\");\n return (\n &lt;div className=\"option\"&gt;\n &lt;Field\n name={radioGroup}\n Tag=\"input\"\n type=\"radio\"\n value={value}\n id={radioId}\n /&gt;\n &lt;label htmlFor={radioId} className=\"radio-buttons\"&gt;\n &lt;div className={\"label-inner\" + (iconPath ? \"\" : \" no-img\")}&gt;\n {iconPath &amp;&amp; &lt;div&gt;&lt;img src={\"/img/\" + iconPath} /&gt;&lt;/div&gt;}\n &lt;div&gt;&lt;span&gt;{text}&lt;/span&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;/label&gt;\n &lt;/div&gt;\n );\n }\n}\n\nReactDOM.render(\n // The Fragments below can be replaced with &lt;&gt; &lt;/&gt; with an up-to-date Babel\n // (Stack Snippets do not support it)\n &lt;React.Fragment&gt;\n &lt;RadioImage radioGroup=\"radioGroup\" value=\"value1\" text=\"text1\" /&gt;\n &lt;RadioImage radioGroup=\"radioGroup\" value=\"value2\" iconPath=\"iconPath\" text=\"text2 with icon\" /&gt;\n &lt;/React.Fragment&gt;\n ,\n document.getElementById('root')\n);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"root\"&gt;&lt;/div&gt;\n&lt;script src=\"https://unpkg.com/react@16/umd/react.production.min.js\"&gt;&lt;/script&gt;\n&lt;script src=\"https://unpkg.com/react-dom@16/umd/react-dom.production.min.js\"&gt;&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>You might consider avoiding IDs when possible - they <a href=\"https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables\">implicitly create global variables</a>, which aren't always the best idea when avoidable. You can move the <code>&lt;input&gt;</code> inside the <code>&lt;label&gt;</code> so that no <code>htmlFor={radioId}</code> is needed.</p>\n\n<p>You can make <code>RadioImage</code> a stateless functional component if you want, it doesn't look to have any need to be stateful:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const Field = ({ name, Tag, type, value, id }) =&gt; (\n &lt;Tag name={name} type={type} value={value} id={id} /&gt;\n);\nconst RadioImage = ({ radioGroup, value, iconPath, text }) =&gt; (\n &lt;div className=\"option\"&gt;\n &lt;label className=\"radio-buttons\"&gt;\n &lt;Field\n name={radioGroup}\n Tag=\"input\"\n type=\"radio\"\n value={value}\n /&gt;\n &lt;div className={\"label-inner\" + (iconPath ? \"\" : \" no-img\")}&gt;\n {iconPath &amp;&amp; &lt;div&gt;&lt;img src={\"/img/\" + iconPath} /&gt;&lt;/div&gt;}\n &lt;div&gt;&lt;span&gt;{text}&lt;/span&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;/label&gt;\n &lt;/div&gt;\n);\nReactDOM.render(\n // The Fragments below can be replaced with &lt;&gt; &lt;/&gt; with an up-to-date Babel\n // (Stack Snippets do not support it)\n &lt;React.Fragment&gt;\n &lt;RadioImage radioGroup=\"radioGroup\" value=\"value1\" text=\"text1\" /&gt;\n &lt;RadioImage radioGroup=\"radioGroup\" value=\"value2\" iconPath=\"iconPath\" text=\"text2 with icon\" /&gt;\n &lt;/React.Fragment&gt;\n ,\n document.getElementById('root')\n);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.option {\n border: 1px solid black;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"root\"&gt;&lt;/div&gt;\n&lt;script src=\"https://unpkg.com/react@16/umd/react.production.min.js\"&gt;&lt;/script&gt;\n&lt;script src=\"https://unpkg.com/react-dom@16/umd/react-dom.production.min.js\"&gt;&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T20:59:28.057", "Id": "240165", "ParentId": "240154", "Score": "1" } } ]
{ "AcceptedAnswerId": "240165", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T17:39:25.600", "Id": "240154", "Score": "2", "Tags": [ "javascript", "react.js" ], "Title": "React Component Reuse with 2 similar components" }
240154
<p>I have a typeahead widget to get the state or city's population according to what the user types</p> <p>Instead of issuing a GET request every time the user is done typing, the way this typeahead widget works is fetch data beforehand and store it in memory and every time user types, we are iterating through the data to retrieve the stuff that we need.</p> <p>The live demo is here: <a href="https://codesandbox.io/s/saveddatatypeahead-lcyfg?file=/src/index.js" rel="nofollow noreferrer">https://codesandbox.io/s/saveddatatypeahead-lcyfg?file=/src/index.js</a></p> <p>So the data is fetched like this</p> <pre class="lang-js prettyprint-override"><code> const data = []; fetch(endpoint) .then(res =&gt; res.json()) .then(result =&gt; { data.push(...result); }); </code></pre> <p>and we listen for the <code>input</code> event on the input field, the <code>timeId</code> is for debouncing the searching, we don't want to search too frequently</p> <pre class="lang-js prettyprint-override"><code>searchInput.addEventListener("input", e =&gt; { if (e.target.value.length &gt; 2) { if (timeId) { clearTimeout(timeId); } timeId = setTimeout(() =&gt; { displayMatches(e.target.value); }, 500); } }); </code></pre> <p>and the search is performed here</p> <pre class="lang-js prettyprint-override"><code>function findMatches(regex, data) { // the time complexity is // O(M x K) // M is the length of a city or state // K is the keyword to match // e.g. M - 'New York' K - 'yo' return data.filter( place =&gt; place.city.match(regex) || place.state.match(regex) ); } </code></pre> <p>Here the regex is constructed based on what the user typed <code>const regex = new RegExp(text, "ig");</code></p> <p>So for now it seems to me that the time complexity for the searching here is <code>O(N x M x K)</code> <code>N</code> is the number of entries in the <code>data</code> array, <code>M</code> is the average length of every city or state's name, and <code>K</code> is the keyword the user typed.</p> <p>So my question is, <strong>is there a way to make the search more efficient?</strong> For now I have done two things to improve the efficiency. </p> <p>1.if what the user types is less than 3 characters, we don't perform the search</p> <p>2.debounce the search and only fire it when the user is done typing</p> <p>Right the amount of data is not huge but I can see that it doesn't scale well with this naive implementation of search. Maybe building a trie can help? I am not sure.</p> <p>Also any other suggestions and critiques about this widget are highly welcomed</p>
[]
[ { "body": "<p>The way the regular expression engine works is, it iterates along every character in the input string, checking if a match to the pattern starts there. For example, searching for \"jose\" in \"san jose\" will result in the match being attempted at index 0, which immediately fails, and the bumpalong increments to index 1, which also immediately fails. This continues until index 4, at which point the <code>j</code> is matched successfully, so the pattern continues, matching <code>o</code>, <code>s</code>, <code>e</code>. When the pattern is just composed of ordinary characters, the length of the pattern doesn't have much of an effect, because on the vast majority of indicies, it'll immediately fail. Rarely, it'll have to iterate a few characters in the pattern before an index fails, eg searching for <code>san jo</code> against <code>San Francisco</code> at index 0, but this is uncommon and still only goes through part of the pattern. So, pattern length doesn't affect computational power required much; it isn't something to worry about.</p>\n\n<p>When turning user input into a regular expression, <a href=\"https://stackoverflow.com/q/3561493\">make sure to escape</a> the input text first, otherwise the constructed pattern's syntax could be invalid or not match what it should. (You could also make a whitelist of characters, and remove any character not on the whitelist from the input)</p>\n\n<p>But for the expensive operation you want to optimize, since it looks like you're just trying to find whether a substring exists in a larger string, a regular expression is overkill - use <code>String.prototype.includes</code> instead. Turn the input and data strings to lower case first, to preserve case-insensitive search - for the data, do this <em>once</em>, on pageload, not inside <code>findMatches</code>. Store the lower-cased results in another property of course, <code>lowerCity</code> and <code>lowerState</code>. There may occasionally have unusual characters like <code>San José</code>, so call <a href=\"https://stackoverflow.com/a/37511463\">String.prototype.normalize</a> on both the input and data, to get a string without accents and diacritics. (You need to use the regex later to construct the HTML, of course, but you don't need to use it when performing the expensive search to find the matching places)</p>\n\n<p>To further cut down on computations required, a possible approach is create an object indexed by characters <code>a</code> to <code>z</code>. Have each property value be an array containing the <code>place</code>s that contain that character. Then, when searching for a place, find the <a href=\"http://pi.math.cornell.edu/~mec/2003-2004/cryptography/subs/frequencies.html\" rel=\"nofollow noreferrer\">least common character</a> in the search string, then look up and search through that array on the object. For example, when searching for <code>\"Jose\"</code>, the least common character is J, so you'd look up the <code>j</code> property. Taking the cities listed on <a href=\"https://www.britannica.com/topic/list-of-cities-and-towns-in-the-United-States-2023068\" rel=\"nofollow noreferrer\">this page</a> as an example, this results in having to search through only 40 cities instead of 2000. (This approach requires a bit more memory, though)</p>\n\n<p>Here's a quick example of the algorithm, taking a few of the places from your gist, and displaying matches as you type:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const places=[{city:\"New York\",growth_from_2000_to_2013:\"4.8%\",latitude:40.7127837,longitude:-74.0059413,population:\"8405837\",rank:\"1\",state:\"New York\"},{city:\"Los Angeles\",growth_from_2000_to_2013:\"4.8%\",latitude:34.0522342,longitude:-118.2436849,population:\"3884307\",rank:\"2\",state:\"California\"},{city:\"Chicago\",growth_from_2000_to_2013:\"-6.1%\",latitude:41.8781136,longitude:-87.6297982,population:\"2718782\",rank:\"3\",state:\"Illinois\"},{city:\"Houston\",growth_from_2000_to_2013:\"11.0%\",latitude:29.7604267,longitude:-95.3698028,population:\"2195914\",rank:\"4\",state:\"Texas\"},{city:\"Philadelphia\",growth_from_2000_to_2013:\"2.6%\",latitude:39.9525839,longitude:-75.1652215,population:\"1553165\",rank:\"5\",state:\"Pennsylvania\"},{city:\"Phoenix\",growth_from_2000_to_2013:\"14.0%\",latitude:33.4483771,longitude:-112.0740373,population:\"1513367\",rank:\"6\",state:\"Arizona\"},{city:\"San Antonio\",growth_from_2000_to_2013:\"21.0%\",latitude:29.4241219,longitude:-98.49362819999999,population:\"1409019\",rank:\"7\",state:\"Texas\"}];\n\nconst placesByChar = {};\nfor (const place of places) {\n for (const char of new Set(place.city.toLowerCase() + place.state.toLowerCase())) {\n if (!placesByChar[char]) placesByChar[char] = [];\n placesByChar[char].push(place);\n place.cityLower = place.city.toLowerCase();\n place.stateLower = place.state.toLowerCase();\n }\n}\nconst charFrequencies = [['z',128],['j',188],['q',205],['x',315],['k',1257],['v',2019],['b',2715],['p',3316],['g',3693],['w',3819],['y',3853],['f',4200],['m',4761],['c',4943],['u',5246],['l',7253],['d',7874],['h',10795],['r',10977],['s',11450],['n',12666],['i',13318],['o',14003],['a',14810],['t',16587],['e',21912]]\n .map(([char]) =&gt; char);\nconst input = document.querySelector('input');\nconst results = document.querySelector('div');\ninput.addEventListener('input', () =&gt; {\n // validate, debounce, and:\n const lowerValue = input.value.toLowerCase();\n const char = charFrequencies.find(([char]) =&gt; lowerValue.includes(char));\n if (!char) return;\n results.textContent = '';\n placesByChar[char]\n .filter(place =&gt; place.cityLower.includes(lowerValue) || place.stateLower.includes(lowerValue))\n .forEach((place) =&gt; {\n results.textContent += place.city + ',';\n });\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input&gt;\n&lt;div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Your listener has a bug: if it runs when a <code>displayMatches</code> is currently being debounced, but the input length is 1 or 0, the outer <code>if</code> will not be entered, <em>but the timeout won't be cleared</em>. If you enter text, then clear it, the still-running <code>displayMatches(e.target.value);</code> will display <em>all</em> places. You should clear the timeout regardless - and since you have a reference to the input element already, you can use that instead of <code>e.target.value</code>:</p>\n\n<pre><code>let timeId;\nsearchInput.addEventListener(\"input\", e =&gt; {\n clearTimeout(timeId);\n const { value } = searchInput;\n if (value.length &lt; 3) {\n return;\n }\n timeId = setTimeout(() =&gt; {\n displayMatches(value);\n }, 500);\n});\n</code></pre>\n\n<p>Your <code>fetch</code> has no <code>catch</code>. If there are errors (gist deleted, site down, network offline), it would be more user-friendly to display them to the user, rather than having the app silently fail.</p>\n\n<p>You should usually be quite wary of concatenating data into a string that gets inserted as HTML, eg:</p>\n\n<pre><code>&lt;span class='type-ahead__result-city--hl'&gt;${text}&lt;/span&gt;\n</code></pre>\n\n<p>It might be safe with <em>this</em> dataset, but for others, it would allow for arbitrary code execution (and, for example, send the user's login information in their cookies to a malicious actor).</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const text = `&lt;img src onerror=\"alert('evil')\"&gt;`;\nconst html = `&lt;span class='type-ahead__result-city--hl'&gt;${text}&lt;/span&gt;`;\ndocument.body.innerHTML = html;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Either <a href=\"https://stackoverflow.com/q/6234773\">escape special characters first</a>, or set the text by assigning to the <code>textContent</code> of the element after it's been created.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T01:36:49.773", "Id": "471100", "Score": "0", "body": "Hi thanks for putting the effort to putting together such a constructive reply. After carefully reading your reply, I have a few questions to ask. First, I am aware of the existence of `includes` helper, but it only returns a boolean, so I cannot use it if I need to do the replacement with the matched chars. Also can you elaborate a bit further on your approach where you said we can store `a` to `z` as the keys in an object , why is that we need to find the least common character in the search string, then look up and search through that array on the object?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T03:06:35.070", "Id": "471101", "Score": "0", "body": "See edit. Of course you need the regex later to replace the HTML, but it's expensive overkill when just trying to find whether a string contains another, which is what's going on in the beginning. I added a live snippet to demonstrate the algorithm. The least common character will allow you to search through the fewest number of places for a match. (Could also examine the length of the arrays once they're constructed)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T22:30:32.740", "Id": "240171", "ParentId": "240155", "Score": "1" } } ]
{ "AcceptedAnswerId": "240171", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T17:46:47.953", "Id": "240155", "Score": "3", "Tags": [ "javascript" ], "Title": "How do I make the search in the typeahead widget more efficient" }
240155
<p>I built some code to update dates from a Dump file. I am commonly running into an "Exceeded maximum execution time" message. Otherwise the code works fine. It imports &amp; updates statuses for 16.5 thousand rows from a sheet that has 29 thousand rows.</p> <p>Can I make the code faster?</p> <pre class="lang-js prettyprint-override"><code>function update_main_master() { var xngSs = SpreadsheetApp.openById('XXXX'); var xngSh = xngSs.getSheetByName('XNG Clean Data'); var MasterSs = SpreadsheetApp.openById('YYY'); var MasterSh = MasterSs.getSheetByName('Master Sheet'); var MasterData = MasterSh.getDataRange().getValues(); var xngData = xngSh.getDataRange().getValues(); // clearFilter() if (MasterSh.getFilter() != null) { MasterSh.getFilter().remove(); } xngData.splice(0, 1); MasterData.splice(0, 1); var OrderNumberMasterSh = []; var PathNameMasterSh = []; for (var i = 0; i &lt; MasterData.length; i++) { OrderNumberMasterSh.push(MasterData[i][1]); PathNameMasterSh.push(MasterData[i][2]); } var i = 0; for (var x = 0; x &lt; xngData.length &amp;&amp; xngData[x][3] != undefined; x++) { var OrderNumber = xngData[x][3]; var OrderDate = xngData[x][2]; var PathName = xngData[x][4]; var CustomerName = xngData[x][5]; var MW_contractor = xngData[x][8]; var OrderStatus = xngData[x][9]; var OrderStage = xngData[x][10]; var ProjectID = xngData[x][14]; var OrderType = xngData[x][41]; var StageDate = xngData[x][11]; var InService = xngData[x][28]; var RejectedReason = xngData[x][31]; var District = xngData[x][15]; var LinkID = xngData[x][24]; var NewOrder = 'New Order'; if (MW_contractor == 'A' || MW_contractor == 'B' || MW_contractor == 'C') { if ( OrderType == 'New' || OrderType == 'Repeater' || OrderType == 'Visibility' ) { // if(OrderType == "New" || OrderType == 'Repeater') var index = OrderNumberMasterSh.indexOf(OrderNumber); if (index == -1) { MasterData.push([ OrderDate, OrderNumber, PathName, CustomerName, ProjectID, MW_contractor, OrderStatus, OrderStatus, OrderStage, OrderType, StageDate, InService, '', District, '', NewOrder, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', RejectedReason, '', '', '', '', '', '', '', '', '', '', ]); } else { MasterData[index][4] = ProjectID; MasterData[index][5] = MW_contractor; MasterData[index][7] = OrderStatus; MasterData[index][8] = OrderStage; MasterData[index][10] = StageDate; MasterData[index][11] = InService; if (MasterData[index][51] == '') { MasterData[index][51] = LinkID; } if ( OrderStatus == 'IN-PROCESS' || OrderStatus == 'CANCELLED' || OrderStatus == 'REJECTED' ) { MasterData[index][6] = OrderStatus; } if (OrderStatus == 'COMPLETED') { MasterData[index][6] = 'LIVE'; } if (OrderStatus == 'REJECTED' &amp;&amp; MasterData[index][48] == '') { MasterData[index][48] = RejectedReason; } } } } } var ContorlSS = SpreadsheetApp.openById('ZZZZ'); var ContorlSh = ContorlSS.getSheetByName('Setup'); ContorlSh.getRange('F6').setValue('Updated'); ContorlSh.getRange('G6').setValue(new Date()); MasterSh.getRange(2, 1, MasterData.length, MasterData[0].length).setValues( MasterData ); SpreadsheetApp.flush(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-23T15:08:06.077", "Id": "479770", "Score": "0", "body": "What runtime are you using? Have you tried using the other one?" } ]
[ { "body": "<p>According to <a href=\"https://tanaikech.github.io/2018/10/12/benchmark-reading-and-writing-spreadsheet-using-google-apps-script/\" rel=\"nofollow noreferrer\">a benchmark report by Tanaike</a></p>\n<blockquote>\n<p>Methods of Sheets API can reduce the process costs from those of Spreadsheet Service by about 19 %.</p>\n</blockquote>\n<p>But in the case of this script the impact of replacing the Google Sheets Basic Service by the Google Sheets Advanced Service will be marginal as the number of read / write tasks are minimal.</p>\n<p>If you are using the old new runtime (Mozilla Rhino), try the new one (Chrome V8)</p>\n<p>Also you could try look for more efficient JavaScript techniques to join two &quot;tables&quot;</p>\n<p>In any case it's very likely that the performance improvements will not be enough so you will have to find a way to do process your data by batches. Among other possibilities, you could add a &quot;timer&quot; to save the progress and stop the script before it fails then create a time drive trigger to call a new instance. Another possibility is to use client-side code to orchestrate parallel executions.</p>\n<p>Related</p>\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/q/101991/91556\">Transforming an array of arrays into an array with joins</a></li>\n<li><a href=\"https://codereview.stackexchange.com/q/175637/91556\">SQL-style join on arrays using ECMA6</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-23T15:05:01.133", "Id": "244385", "ParentId": "240156", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T18:01:30.087", "Id": "240156", "Score": "4", "Tags": [ "javascript", "performance", "google-apps-script", "google-sheets" ], "Title": "Google apps script Exceeded maximum execution time issue or 29k rows" }
240156
<h3>Design</h3> <p>A template class that will create a concrete instance of an interface class when given the name (as a string) of the concrete class.</p> <p>This design is often seen in code, so the purpose of this class is to reduce the boilerplate code needed to write a factory class. </p> <p>The template class will be used like this:</p> <pre><code>using MyFactory = factory&lt;MyInterfaceType, MyType_1, MyType_2, MyType_3&gt;; int main() { auto ptr = MyFactory::create("MyType_1"); ptr-&gt;doSomething(); } </code></pre> <p>There will be a static assert to check that all of the concrete types inherit from the interface type and the create method can accept an optional argument to describe the return type if no class matching the id is found.</p> <h2>Implementation</h2> <pre><code>template&lt;typename interface_type, typename... products&gt; struct factory { template&lt;typename Class&gt; struct LabledClass { std::string_view label = to_string&lt;Class&gt;(); Class data; }; using labled_classes = std::tuple&lt;LabledClass&lt;products&gt;...&gt;; static std::unique_ptr&lt;interface_type&gt; create(const std::string_view&amp; id, std::unique_ptr&lt;interface_type&gt; default_type = nullptr) { std::unique_ptr&lt;interface_type&gt; result = std::move(default_type); //checl all products inherit from interface_type std::apply([](auto&amp;&amp;... tuple_elem) { ((static_check&lt;decltype(tuple_elem.data)&gt;()), ...); }, labled_classes{} ); //if product matches id, return a new instance of that product std::apply([&amp;result, &amp;id](auto&amp;&amp;... tuple_elem) { (( tuple_elem.label == id ? result = std::make_unique&lt;decltype(tuple_elem.data)&gt;() : result ), ...); }, labled_classes{} ); return result; } private: template&lt;typename product&gt; static void static_check() { static_assert(std::is_base_of&lt;interface_type, product&gt;::value, "all products must inherit from interface_type"); } }; </code></pre> <p>This requires the function <code>to_string&lt;Class&gt;()</code> which does not yet exist in the c++ standard, but can be implemented on GCC or Clang like so:</p> <pre><code>template&lt;typename Class&gt; constexpr std::string_view to_string() { std::string_view str = __PRETTY_FUNCTION__; auto first = str.find("= "); std::string_view str2 = str.substr(first + 2); auto last = str2.find(";"); str2.remove_suffix(str2.length() - last); return str2; } </code></pre> <h2>Example use</h2> <pre><code>#include &lt;iostream&gt; #include "factory.h" struct Animal { virtual void makeNoise() const = 0; }; struct Dog : Animal { virtual void makeNoise() const override{ std::cout &lt;&lt; "Woof" &lt;&lt; std::endl; } }; struct Cat : Animal { virtual void makeNoise() const override{ std::cout &lt;&lt; "Meow" &lt;&lt; std::endl; } }; struct Duck : Animal { virtual void makeNoise() const override{ std::cout &lt;&lt; "Quack" &lt;&lt; std::endl; } }; struct NullAnimal : Animal { virtual void makeNoise() const override{ std::cout &lt;&lt; "?" &lt;&lt; std::endl; } }; using AnimalFactory = factory&lt;Animal, Dog, Cat, Duck&gt;; int main() { auto animal = AnimalFactory::create("Dog"); animal-&gt;makeNoise(); } </code></pre> <p>I have tested this with GCC 9.01 and it works</p>
[]
[ { "body": "<p>Seems pretty reasonable. I mean, I definitely wouldn't put this in production code because it relies on parsing a class name out of <code>__PRETTY_FUNCTION__</code>, and that's not necessarily guaranteed to keep working in future versions of GCC let alone Clang (and <code>__PRETTY_FUNCTION__</code> isn't even supported at all on MSVC; they have <code>__FUNC_SIG</code> instead).</p>\n\n<p>In fact, I just tested on Godbolt, and your <code>to_string&lt;T&gt;()</code> function doesn't work at all on Clang. Furthermore, even on GCC, it has trouble with corner cases like <code>A&lt;';'&gt;</code> — <a href=\"https://godbolt.org/z/UNVRQL\" rel=\"nofollow noreferrer\">https://godbolt.org/z/UNVRQL</a></p>\n\n<hr>\n\n<p>Nitpicks on your test code: The rule of thumb I follow is that every polymorphic method should have <em>exactly one of</em> <code>virtual</code>, <code>override</code>, or <code>final</code> (and really nothing should ever have <code>final</code>). So your repetition of <code>virtual</code> is just clutter, to me.</p>\n\n<p>Ditto your use of <code>std::endl</code> (which flushes) versus plain old <code>\"\\n\"</code> (which also flushes if you're outputting to a line-buffered stream such as <code>std::cout</code>). You could save some typing there.</p>\n\n<hr>\n\n<p>You misspell \"labeled\" in at least two places: <code>LabledClass</code> and <code>labled_classes</code>. These are implementation details, but it's still important to spell things right so that you can grep for them later.</p>\n\n<p>You pass <code>const std::string_view&amp; id</code> by reference. This is unidiomatic. <code>string_view</code> is already a trivially copyable type, the size of two pointers. It doesn't make sense to force one of those onto the stack just so you can take its address and pass it by reference. Pass <code>string_view</code> by value.</p>\n\n<hr>\n\n<pre><code> //checl all products inherit from interface_type\n std::apply([](auto&amp;&amp;... tuple_elem) {\n ((static_check&lt;decltype(tuple_elem.data)&gt;()), ...);\n }, labled_classes{} );\n</code></pre>\n\n<p>Typo: <code>checl</code> for <code>check</code>. And this is waaay more complicated than it needs to be. Just <code>static_assert</code> the thing you want to assert:</p>\n\n<pre><code>static_assert(std::is_base_of_v&lt;interface_type, products&gt; &amp;&amp; ...);\n</code></pre>\n\n<p>In fact, let's use the idiomatic <code>CamelCase</code> for template arguments, and keep them short:</p>\n\n<pre><code>template&lt;class Base, class... Ps&gt;\n[...]\n static_assert(std::is_base_of_v&lt;Base, Ps&gt; &amp;&amp; ...);\n</code></pre>\n\n<hr>\n\n<pre><code>std::apply([&amp;result, &amp;id](auto&amp;&amp;... tuple_elem) {\n (( tuple_elem.label == id ?\n result = std::make_unique&lt;decltype(tuple_elem.data)&gt;() :\n result ), ...);\n}, labled_classes{} );\n</code></pre>\n\n<p>This complexity is a little more irreducible, but still, doing it all with a <code>tuple</code> and <code>std::apply</code> seems like way more template instantiations than you really ought to have here. What's wrong with a good old-fashioned chain of <code>if</code>s?</p>\n\n<p>Also, nit: if you're capturing everything by reference, just write <code>[&amp;]</code>. It saves brain cells for the reader of your code.</p>\n\n<pre><code>int dummy[] = {\n ([&amp;]() { if (id == to_string&lt;Ps&gt;()) result = std::make_unique&lt;Ps&gt;(); }(), 0) ...\n};\n</code></pre>\n\n<p>We could even short-circuit as soon as we find the match. That's easy if we leave <code>result</code> null at first; then <code>result</code> will be null if and only if we should still be doing string comparisons.</p>\n\n<pre><code>static std::unique_ptr&lt;Base&gt;\ncreate(std::string_view id, std::unique_ptr&lt;Base&gt; default_type = nullptr)\n{\n static_assert(std::is_base_of_v&lt;Base, Ps&gt; &amp;&amp; ...);\n\n std::unique_ptr&lt;Base&gt; result = nullptr;\n int dummy[] = {\n ([&amp;]() {\n if (result == nullptr &amp;&amp; id == to_string&lt;Ps&gt;()) {\n result = std::make_unique&lt;Ps&gt;();\n }\n }(), 0) ...\n };\n if (result == nullptr) {\n result = std::move(default_type);\n }\n return result;\n}\n</code></pre>\n\n<p>At this point it's no longer clear why you need <code>struct factory</code> at all. So personally I'd get rid of it, and rename the now-free function <code>create</code> to <code>makeUniqueByName</code> or something.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T09:16:43.457", "Id": "471120", "Score": "0", "body": "“really nothing should ever have `final`” [is a *bad rule*](https://softwareengineering.stackexchange.com/a/92771/2366) (the link concerns `final` on classes but the same is true, to an even larger extent, for member functions)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T09:49:58.727", "Id": "471122", "Score": "0", "body": "@Quuxplusone Thanks! This is really helpful advice. I'm still learning fold expressions so that is why there was the convoluted use of tuples and `std::apply`.\nJust a note, I have applied your changes but `static_assert(std::is_base_of_v<Base, Ps> && ..., \"\");` does not compile. I instead need to use `static_assert((std::is_base_of_v<Base, Ps> && ...), \"\");`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T14:28:37.577", "Id": "471140", "Score": "0", "body": "@KonradRudolph: If \"final\" were the default and you had to type `heritable` to get a base class, then I'd say that \"really nothing should ever have `heritable`.\" I feel the same way about `const` local variables (although I was on the other side circa 2005). C++ definitely has bad defaults, but still, there's no point going out of your way just to _reiterate_ something that should be obvious by convention and/or to _remove_ freedom from the maintainer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T14:29:06.467", "Id": "471141", "Score": "0", "body": "@Blue7 re parens around the fold-expression: Oops, yes, you're right, the parens are needed grammatically." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T17:03:23.927", "Id": "471153", "Score": "0", "body": "@Quuxplusone *The whole point* of a type system is to remove freedoms from the maintainer. That’s a good thing. That said, I agree otherwise with your comment. In this spirit I rarely use `final` in C++ purely because I rarely use inheritance, and thus most (> 90%) of my classes are obviously not heritable. I only use it in cases where I work in an OOP hierarchy)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T06:08:53.117", "Id": "240186", "ParentId": "240157", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T18:01:46.373", "Id": "240157", "Score": "6", "Tags": [ "c++", "template", "c++17", "factory-method", "gcc" ], "Title": "C++ Template to implement the Factory Pattern" }
240157
<p>I am implementing fundamental data structures in C# while trying to learn techniques in the language to make my code cleaner, more concise while using good programming practices.</p> <p>I have implemented both algorithms, DFS and BFS, to find the bridges in a graph. The code is properly working (as far as I've tested).</p> <p>Important notes:</p> <ul> <li><p>I've tried a simpler and more intuitive approach of the solution, I know the computational complexity of my solution is <span class="math-container">\$O(E*(V+E))\$</span>, while others methods resolve this exercise with <span class="math-container">\$O(V+E)\$</span> complexity.</p> <ul> <li><p>The method consists of:</p> <ol> <li>For every edge (u, v), do the following: <ol> <li>Remove (u, v) from graph</li> <li>See if the graph remains connected (We can either use BFS or DFS)</li> </ol></li> </ol></li> <li><p>The solution is designed to fit this function call:</p> <pre><code>List&lt;Tuple&lt;int, int&gt;&gt; FindBridges(int numOfNodes, int numOfEdges, List&lt;Tuple&lt;int, int&gt;&gt; edges) { //function body } </code></pre></li> <li><p>I've used string type for Node's id to be able to name them with any kind of data type and then convert them to string (ints,strings,chars...)</p></li> </ul></li> </ul> <p>I'd appreciate feedback of any kind: ways to improve implementations (using this method), coding style, any refactor suggestions.</p> <pre><code>class UndirectedGraph { public class Node { public string Id { get; } public List&lt;string&gt; Adjs { get; set; } public Node(string nodeId) { Id = nodeId; Adjs = new List&lt;string&gt;(); } public Node(Node node) { Id = node.Id; Adjs = node.Adjs.ConvertAll(x =&gt; x); } public override string ToString() { string value = string.Format("Node id:{0} -&gt; (", Id); foreach (string adj in Adjs) { value = value + adj + ","; } value += ")"; return value; } } public int NumOfNodes { get; private set; } public Node[] AdjacencyList { get; } private List&lt;Tuple&lt;string, string&gt;&gt; Edges = new List&lt;Tuple&lt;string, string&gt;&gt;(); public UndirectedGraph(int numOfNodes) { NumOfNodes = numOfNodes; AdjacencyList = new Node[numOfNodes]; for (int i = 0; i &lt; numOfNodes; i++) { AdjacencyList[i] = new Node((i+1).ToString()); } } public UndirectedGraph(UndirectedGraph originalGraph) { NumOfNodes = originalGraph.NumOfNodes; AdjacencyList = originalGraph.AdjacencyList.Select(a =&gt; new Node(a)).ToArray(); Edges = originalGraph.Edges.ConvertAll(x =&gt; Tuple.Create(x.Item1,x.Item2)); } public int FindNodeIndex(string nodeId) { for (int i = 0; i &lt; AdjacencyList.Length; i++) { if (AdjacencyList[i].Id == nodeId) return i; } return -1; } public Node FindNode(string nodeId) { for (int i = 0; i &lt; AdjacencyList.Length; i++) { if (AdjacencyList[i].Id == nodeId) return AdjacencyList[i]; } return null; } public void AddEdge(string a, string b) { Tuple&lt;string, string&gt; edge = Tuple.Create(a, b); Node aNode = FindNode(edge.Item1); Node bNode = FindNode(edge.Item2); // Avoid trying to create edges on non existing nodes if (!AdjacencyList.Contains(aNode) || !AdjacencyList.Contains(bNode)) throw new Exception("The edge couldn't be created because one of the nodes is not part of the graph"); // To avoid paralel connections if (Edges.Contains(edge) || Edges.Contains(Tuple.Create(b, a))) return; aNode.Adjs.Add(edge.Item2); bNode.Adjs.Add(edge.Item1); Edges.Add(edge); } public void AddEdge(Tuple&lt;string,string&gt; edge) { Node aNode = FindNode(edge.Item1); Node bNode = FindNode(edge.Item2); // Avoid trying to create edges on non existing nodes if (!AdjacencyList.Contains(aNode) || !AdjacencyList.Contains(bNode)) throw new Exception("The edge couldn't be created because one of the nodes is not part of the graph"); // To avoid paralel connections if (Edges.Contains(edge) || Edges.Contains(Tuple.Create(edge.Item2, edge.Item1))) return; aNode.Adjs.Add(edge.Item2); bNode.Adjs.Add(edge.Item1); Edges.Add(edge); } public void DeleteEdge(Tuple&lt;string, string&gt; edge) { if (!Edges.Contains(edge)) return; Node aNode = FindNode(edge.Item1); Node bNode = FindNode(edge.Item2); aNode.Adjs.Remove(edge.Item2); bNode.Adjs.Remove(edge.Item1); Edges.Remove(edge); } public override string ToString() { List&lt;string&gt; nodesString = new List&lt;string&gt;(); foreach (Node node in AdjacencyList) { nodesString.Add(node.ToString()); } string message = string.Join('\n', nodesString); message += '\n'; return message; } public List&lt;string&gt; DFS(string startingNode_id = null) { // Set up starting node Node currentNode; if (startingNode_id == null) currentNode = AdjacencyList[0]; else currentNode = FindNode(startingNode_id); // -------------------- // Initialize for first iteration Stack&lt;string&gt; stack = new Stack&lt;string&gt;(NumOfNodes); List&lt;string&gt; nodesVisited = new List&lt;string&gt;(); nodesVisited.Add(currentNode.Id); // -------------------- // Iteration of DFS while (nodesVisited.Count &lt; NumOfNodes) { int toNode_index = IndexOfFirstNotVisited(currentNode.Adjs, nodesVisited); if (toNode_index &gt;= 0) { stack.Push(currentNode.Id); currentNode = FindNode(currentNode.Adjs[toNode_index]); } else if (stack.Count &gt; 0) { currentNode = FindNode(stack.Pop()); } else { break; } if (!nodesVisited.Contains(currentNode.Id)) nodesVisited.Add(currentNode.Id); } return nodesVisited; } public List&lt;string&gt; BFS(string startingNode_id = null) { // Set up starting node Node currentNode; if (startingNode_id == null) currentNode = AdjacencyList[0]; else currentNode = FindNode(startingNode_id); // -------------------- // Initialize for first iteration List&lt;string&gt; nodesVisited = new List&lt;string&gt;(); List&lt;string&gt; queue = new List&lt;string&gt;(); nodesVisited.Add(currentNode.Id); queue.Add(currentNode.Id); // -------------------- // Iterations of BFS while (nodesVisited.Count &lt; NumOfNodes &amp;&amp; queue.Count &gt; 0) { currentNode = FindNode(queue[0]); queue.RemoveAt(0); for (int i = 0; i &lt; currentNode.Adjs.Count; i++) { string nodeVisited = currentNode.Adjs[i]; if (!nodesVisited.Contains(nodeVisited)) { nodesVisited.Add(nodeVisited); queue.Add(nodeVisited); } } } return nodesVisited; } private int IndexOfFirstNotVisited(List&lt;string&gt; adjs, List&lt;string&gt; nodesVisited) { for (int i = 0; i &lt; adjs.Count; i++) { if (!nodesVisited.Contains(adjs[i])) { return i; } } return -1; } } </code></pre> <p>And the main used for testing purposes and initialization of the graph:</p> <pre><code> class Program { static void Main(string[] args) { List&lt;Tuple&lt;int, int&gt;&gt; edges1 = new List&lt;Tuple&lt;int, int&gt;&gt;() { Tuple.Create(1,2), Tuple.Create(1,3), Tuple.Create(2,3), Tuple.Create(4,3), Tuple.Create(4,5), Tuple.Create(4,6), Tuple.Create(5,6), Tuple.Create(5,7), Tuple.Create(6,7), Tuple.Create(8,7), Tuple.Create(8,9), Tuple.Create(8,10), Tuple.Create(9,10), }; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); List&lt;Tuple&lt;int, int&gt;&gt; bridges = FindBridges(10, edges1.Count, edges1); bridges.ForEach(Console.WriteLine); stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds); } private static List&lt;Tuple&lt;int, int&gt;&gt; FindBridges(int numOfNodes, int numOfEdges, List&lt;Tuple&lt;int, int&gt;&gt; edges) { UndirectedGraph graph = new UndirectedGraph(numOfNodes); List&lt;Tuple&lt;int, int&gt;&gt; bridges = new List&lt;Tuple&lt;int, int&gt;&gt;(); foreach (var edge in edges) { graph.AddEdge(Tuple.Create(edge.Item1.ToString(), edge.Item2.ToString())); } foreach (var edge in edges) { UndirectedGraph newGraph = new UndirectedGraph(graph); newGraph.DeleteEdge(Tuple.Create(edge.Item1.ToString(), edge.Item2.ToString())); if (newGraph.BFS().Count &lt; numOfNodes) bridges.Add(edge); } return bridges; } } </code></pre>
[]
[ { "body": "<p>The code is understandable, perhaps the naming used in some fields is quite hard to recognize for others who are seeing this code for first time.</p>\n\n<p>Example <code>Adjs</code> (AdjacentVertices) is not intuitive, you are used to see this code and understand why you'd put everything on its place but other person who comes will spend more time getting familiar with it. Another example is <code>Node</code> (I think you mean Vertex) perhaps it is due the difference I perceive between Node (for trees) and Vertex (for general graphs, naturally including trees), technical vocabulary is also relevant.</p>\n\n<p>Your <code>UndirectedGraph</code> class is an <code>UndirectedAdjacencyList</code> i think it is important to mention due the different Graph models that there are.</p>\n\n<h3>With the code.</h3>\n\n<p>You will want to dynamically add edges and vertices in your graph. An alternative would be:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> public List&lt;Node&gt; AdjacencyList { get; } //where Node is means Vertex\n</code></pre>\n\n<p>In addition, I think it would be better to handle Edges as a list rather than an array.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> //instead of \n //private List&lt;Tuple&lt;string, string&gt;&gt; Edges = new List&lt;Tuple&lt;string, string&gt;&gt;();\n private List&lt;Edge&gt; Edges = new List&lt;Edge&gt;();\n</code></pre>\n\n<p>At last I propose you the following Idea which may make easier to manage both Vertices and Edges</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> private SortedDictionary&lt;Vertex, List&lt;Edge&gt;&gt; AdjacencyList;\n</code></pre>\n\n<p>So that there will not be any repeated Vertex in your graph.</p>\n\n<p>Thanks for reading my answer, Hope it helps</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T09:57:14.233", "Id": "471219", "Score": "0", "body": "Thanks for the feedback mate... Appreciate it :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T22:03:14.510", "Id": "240170", "ParentId": "240159", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T18:07:33.147", "Id": "240159", "Score": "2", "Tags": [ "c#", "algorithm", "graph" ], "Title": "Finding bridges in an Undirected Graph implementation in C#" }
240159
<p>Firstly, take in account is my first question here in CodeReview. Any purpose misuderstanding will be highly appreciated if orientaded.</p> <p>Scenario: I want to answer randomly a pojo (json with two fields) to Angular using a WebFlux restservice. I can succesfully answer an integer but I got stuck while trying retruning a model. On top of that I am using Server Sent Events but I don't think it is relevant to this question.</p> <p>Successfully done with an Integer:</p> <pre><code>@GetMapping(value = "/randomNumbers", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux&lt;ServerSentEvent&lt;Integer&gt;&gt; randomNumbers() { return Flux.interval(Duration.ofSeconds(1)).map(seq -&gt; Tuples.of(seq, ThreadLocalRandom.current().nextInt())) .map(data -&gt; ServerSentEvent.&lt;Integer&gt;builder().event("random").id(Long.toString(data.getT1())) .data(data.getT2()).build()); } </code></pre> <p>Completely stuck trying to follow same approach to answer a status model:</p> <pre><code> @GetMapping(value = "/randomStatus", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux&lt;ServerSentEvent&lt;Status&gt;&gt; randomStatus() { ArrayList&lt;String&gt; statusList = new ArrayList&lt;String&gt;(); statusList.add("Iniciado"); statusList.add("Recusado"); statusList.add("Sucesso"); // for (int i = 0; i &lt; 100; i++) { // int x = ThreadLocalRandom.current().nextInt(0, statusList.size()); // System.out.println(statusList.get(x)); // } </code></pre> <p>//the next line it is not working but I pasted to show where I am stuck. Let's say I can't create a new Status object return Flux.interval(Duration.ofSeconds(1)) .map(seq -> Tuples.of(seq, ThreadLocalRandom.current().nextInt())) .map(data -> ServerSentEvent.builder().event("random").data(new Status(Long.toString(data.getT1()), ThreadLocalRandom.current().nextInt(0, statusList.size() ) .data(data.getT2()).build()))); }</p> <pre><code>} </code></pre> <p>In case it is relevant, here is Status model:</p> <pre><code>import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document public class Status { @Id private String id; private String status; ... getters/setters/contructor hidden for simplicity </code></pre> <p>Imports in case it is relevants are:</p> <pre><code>import java.time.Duration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.codec.ServerSentEvent; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import com.reactive.fluxdemo.domain.Status; import com.reactive.fluxdemo.domain.Transfer; import com.reactive.fluxdemo.repository.StatusRepository; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.util.function.Tuples; import java.util.ArrayList; import java.util.concurrent.ThreadLocalRandom; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T21:18:11.733", "Id": "471081", "Score": "3", "body": "Hello, this question is off-topic, since the code is not working as intended; I suggest that you read the [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic) `Code Review aims to help improve working code. If you are trying to figure out why your program crashes or produces a wrong result, ask on Stack Overflow instead. Code Review is also not the place to ask for implementing new features.`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T22:22:10.780", "Id": "471086", "Score": "1", "body": "Sorry, I will take this in account next time." } ]
[ { "body": "<p>I think I didn't write my question folloing the expectations of this forum. BTW, here is the solution for future readers. </p>\n\n<p>I wonder if this is the best way to achive it since I am creating a new instance (new Status) each time before the flux is closed. I would appreciated if someone can comment on bellow code.</p>\n\n<p>Honestly I still stumble on Lambda skill. Hope it can be usefull for future readers.</p>\n\n<pre><code>@GetMapping(value = \"/randomStatus\", produces = MediaType.TEXT_EVENT_STREAM_VALUE)\npublic Flux&lt;ServerSentEvent&lt;Status&gt;&gt; randomStatus() {\n\n ArrayList&lt;String&gt; statusList = new ArrayList&lt;String&gt;();\n statusList.add(\"Iniciado\");\n statusList.add(\"Recusado\");\n statusList.add(\"Sucesso\");\n\n return Flux.interval(Duration.ofSeconds(1))\n .map(seq -&gt; Tuples.of(seq, ThreadLocalRandom.current().nextInt()))\n .map(data -&gt; ServerSentEvent.&lt;Status&gt;builder().data(\n new Status(Long.toString(data.getT1()),statusList.get(ThreadLocalRandom.current().nextInt(0, statusList.size() ))\n ))\n .build());\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T22:41:58.237", "Id": "240172", "ParentId": "240162", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T20:06:30.440", "Id": "240162", "Score": "-2", "Tags": [ "java", "spring", "lambda", "reactive-programming" ], "Title": "How generate a random pojo value using reactor.core.publisher.Flux and reactor.util.function.Tuples" }
240162
<h2>Setup</h2> <p>The following code implements the algorithm described in <a href="https://link.springer.com/article/10.1007/BF02180147" rel="noreferrer">this</a> and <a href="https://www.sciencedirect.com/science/article/pii/037843719500039A?via%3Dihub" rel="noreferrer">this paper</a>. The first paper describes how the evolution of a fish population can be simulated, while the second paper introdues the phenomenon of 'fishing' into the simulation. The end goal of both papers is to show that one can have a stable fish population, introduce "responsible" fishing such that the total number of fish in the population decreases, but remains stable. The last step is then to add "irresponsible" fishing and to show that small changes in the fishing rate (fished fish per year) can have drastical results on the amount of fish that survive. </p> <hr> <h2>Code</h2> <p>The code is a reimplementation int Kotlin of C++ code I wrote some time ago. I picked up Kotlin just recently and I was struggeling with how inheritance worked here and how exactly to deal with static variables. It works as intended.</p> <p>The code consists of three classes <code>genome</code>, <code>animal</code> and <code>population</code> (as well as a derivied class) and the <code>main</code> function that actually performs the simulation (<a href="https://imgur.com/pen8meY" rel="noreferrer">this plot</a> summerizes the results). </p> <h3>genome.kt</h3> <pre><code>package penna import java.util.* typealias age_t = Int class Genome{ /* Genome Class for the Penna simulation. * The genome class has two private members: * 1) 'genome_size_' is of type 'age_t' and static. It represents the length of the * genome and therefore later the maximum age of the animal in question. * 'agt_t' is set to 'int' since it needs to be bigger than 0 and an * element of the whole numbers. * 2) The actual genome is represented by a bitset called 'genome_' of length * 'genome_size_'. */ private var genes = BitSet(genome_size) init { genes.set(0, genome_size, false) } /* PRE: 'this' needs to be a valid Genome instance. * POST: switch exactly 'mutation_rate_' many instances of * of the child's genome_. */ fun mutate(){ val indices: MutableList&lt;Int&gt; = (0..genome_size).toMutableList() indices.shuffle() for(k in 0..mutation_rate_){ genes.flip(indices[k]) } } /* PRE: 'this' is a valid genome instance and 'age' is smaller or equal to genome_size * POST: Counts all the "bad genes" in genome_ up to the 'age'-th entry. * A gene is bad if the entry in the BitSet is set to 'true'. */ fun countBad(age: age_t): Int { return genes.get(0, age).cardinality() } companion object{ var genome_size: Int = 64 fun setMutationRate(age: age_t) { mutation_rate_ = age } private var mutation_rate_: age_t = 0 } } </code></pre> <h3>animal.kt</h3> <pre><code>package penna import kotlin.random.Random.Default.nextDouble class Animal(){ /* Animal class for the Penna simulation. * The Animal class has several private members: * 1) 'mutation_rate_', 'reproduction_age_' and 'threshold_' are all parameters * that stay constant for all animals of a population. * The respective values can all be retrieved and set with the corresponding * get and set functions. * 2) 'age_' represents the current age of the animal. By default construction it is set to 0. * 3) 'genome_' is a Genome class instance in which we will save the genome of an animal. * When constructed all genes are set to be good (aka false). * 4) 'pregnant_' is a variable of type bool and tells you if the animal is currently pregnant. * The status of each animal can be retrieved via the member function isPregnant(). */ // Default constructor private var age = 0 private var genome: Genome = Genome() private var pregnant: Boolean = false constructor(mum_genes: Genome): this(){ age = 0 genome = mum_genes pregnant = false } fun isPregnant(): Boolean { return pregnant } fun age(): Int { return age } /* PRE: 'this' is a valid animal instance. * POST: Returns true if the animal is dead, otherwise false. * An animal is dead if: * 1) age_ &gt; max_age * 2) count_bad(age_) &gt; threshold_ */ fun isDead(): Boolean { return age &gt; max_age || genome.countBad(age) &gt; threshold } /* PRE: 'mother' is pregnant. * POST: The following things are done in this order: * 1) set the mothers pregnancy to false. * 2) create an Animal instance with the mothers genome_ * 3) 'mutate' the child's genome. */ fun giveBirth(): Animal { assert(pregnant) pregnant = false val childGenome = genome childGenome.mutate() return Animal(childGenome) } /* PRE: 'this' has to be a valid Animal instance * POST: Grow the animal by one year: * 1) age_++ * 2) set pregnant_ to true with probability_to_get_pregnant_. */ fun grow() { assert(!this.isDead()) age++ if (age &gt; reproductionAge &amp;&amp; !pregnant){ if(nextDouble(0.0,1.0) &lt;= probabilityToGetPregnant){ pregnant = true } } } companion object{ private var probabilityToGetPregnant: Double = 0.0 private var reproductionAge: age_t = 0 // Age at which Animals start reproduction private var threshold: age_t = 0 // More than this many mutations kills the Animal var max_age: age_t = Genome.genome_size fun setReproductionAge(num: age_t){ reproductionAge = num } fun setThreshold(num: age_t){ threshold = num } fun setProbabilityToGetPregnant(num: Double){ probabilityToGetPregnant = num } } } </code></pre> <h3>population.kt</h3> <pre><code>package penna import kotlin.random.Random.Default.nextDouble open class Population(private var nMax: Int, nZero: Int) { /* Class to simulate a population of Animal objects. * nMax: The upper limit of the population size * nZero: The starting number of the population */ protected var population: MutableList&lt;Animal&gt; = ArrayList() init { for(k in 0 until nZero){ population.add(Animal()) } } fun size(): Int { return population.size } /* PRE: --- * POST: Performs one step in the simulation: * 1) Age all animals by calling Animal::grow() * 2) Remove all animals that: * 2.1) are dead ( by using Animal::isDead() ) * 2.2) if there are more than nMax many Animals in the population * 2.3) regardless of the above, kills an animal with probability population.size()/nMax * 3) Generate offspring by calling Animal::give_birth on the pregnant Animals in population and * appending it to population. */ open fun step() { // Age all animals population.forEach { it.grow() } // Remove dead ones population.removeIf{ this.size() / nMax.toDouble() &gt;= 1.0 || nextDouble(0.0,1.0) &lt; this.size() / nMax.toDouble() || it.isDead() } // Generate offspring val parents: MutableList&lt;Animal&gt; = population.filter { it.isPregnant() }.toMutableList() val babies : MutableList&lt;Animal&gt; = ArrayList() for(animal in parents){ babies.add(animal.giveBirth()) } population.addAll(babies) } } class FishingPopulation(nMax: Int, nZero: Int, fishingProb: Double, fishingAge: Int) : Population(nMax, nZero) { /* Derived class of Population to realize the Fishing aspect of the Discussion. * fishingProb: is the probability with which one fish will die due to fishing * fishingAge: the age at which a fish can die due to fishing */ private var fishProb: Double = 0.0 private var fishAge: Int = 0 init { fishProb = fishingProb fishAge = fishingAge } // Change the two Parameters on the fly when necessary fun changeFishing(fishingProb: Double, fishingAge: Int){ fishProb = fishingProb fishAge = fishingAge } /* Essentially the same function as Population::step(). We only perform the fishing in addition by removing * fish with the specified probability. */ override fun step() { super.step() super.population.removeIf { it.age() &gt; fishAge &amp;&amp; nextDouble(0.0,1.0) &lt; fishProb } } } </code></pre> <h3>main.kt</h3> <pre><code>package penna import java.io.File fun main(){ // Set the parameters for the simulation. Genome.genome_size = 64 // Determines the maximal age of the Animal Genome.setMutationRate(2) // How many mutations per year can happen in the worst case Animal.setReproductionAge(6) // Age at which Animals start reproduction Animal.setThreshold(8) // More than this many mutations kills the Animal Animal.setProbabilityToGetPregnant(1.0) // Animal generate offspring every year val fish = FishingPopulation(10000, 1000, 0.0, 0) val popSizes: MutableList&lt;Int&gt; = ArrayList() for(generation in 0 until 5000){ popSizes.add(fish.size()) fish.step() if(generation == 500) { fish.changeFishing(0.19, 8) } if(generation == 3500){ fish.changeFishing(0.22,0) } } File("data.txt").writeText(popSizes.toString()) } </code></pre> <p>As I said above, I'm a complete beginner when it comes to Kotlin and I have never coded in Java either, so it's very well possible that I approached the problem here completely worng... Any feedback is recommended. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T20:42:43.227", "Id": "471079", "Score": "1", "body": "Does your code already work like you want it to?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T20:44:06.377", "Id": "471080", "Score": "1", "body": "@Phrancis It does, the results are the same I get from the c++ version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T21:21:42.203", "Id": "471082", "Score": "0", "body": "If there is a way how I can improve the question, please let me know." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T22:54:21.963", "Id": "471092", "Score": "3", "body": "I reworded the title a bit to make it more clear, and added some tags. Hope you get some good answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T22:56:09.943", "Id": "471093", "Score": "0", "body": "@Phrancis Thank you very much for the help!" } ]
[ { "body": "<p>remark: I focused on syntax//features, not on the program itself.</p>\n\n<h1>shuffled</h1>\n\n<p>I'm taking the explanatory route<br>\n<strong>also</strong> </p>\n\n<pre><code>val indices: MutableList&lt;Int&gt; = (0..genome_size).toMutableList()\nindices.shuffle()\n</code></pre>\n\n<p>This function can be rewritten with <code>also</code>:</p>\n\n<pre><code>val indices = (0..genome_size).toMutableList()\n .also{ it.shuffle() }\n</code></pre>\n\n<p>The object on which an extension-function is called is called <strong>receiver</strong>.<br>\n<code>also</code> allows you to provide a lambda in which you can access the receiver using <code>it</code>.<br>\n<code>also</code> returns the receiver itself.</p>\n\n<p><strong>apply</strong><br>\nThe next step from also is <code>apply</code>:<br>\n<code>apply</code> is the same as <code>also</code>, but you use <code>this</code> to refer to the receiver.<br>\nThis means the code can be rewritten as:</p>\n\n<pre><code>val indices = (0..genome_size).toMutableList()\n .apply { this.shuffle() }\n</code></pre>\n\n<p>and because you can skip <code>this</code> to refer to something, you can use:</p>\n\n<pre><code>val indices = (0..genome_size).toMutableList()\n .apply { shuffle() }\n</code></pre>\n\n<p>Why did I tell you this?<br>\nThere is already a function that does <code>.toMutableList().apply { shuffle() }</code>, named <code>shuffled</code>.\nTherefor, you can rewrite this function with: </p>\n\n<pre><code>val indices: List&lt;Int&gt; = (0..genome_size).shuffled()\n</code></pre>\n\n<h1>oneliner function</h1>\n\n<p>You can simplify functions which start with return:</p>\n\n<pre><code>fun countBad(age: age_t): Int {\n return genes.get(0, age).cardinality()\n}\n</code></pre>\n\n<p>This can be simplified to:</p>\n\n<pre><code>fun countBad(age: age_t): Int = genes.get(0, age).cardinality()\n//or to \nfun countBad(age: age_t) = genes.get(0, age).cardinality()\n</code></pre>\n\n<h1>constructors</h1>\n\n<p>In kotlin, constructors can define properties and default constructor parameters.</p>\n\n<pre><code>class FishingPopulation(\n nMax: Int, \n nZero: Int, \n fishingProb: Double, \n fishingAge: Int\n) : Population(nMax, nZero) {\n private var fishProb: Double = 0.0\n private var fishAge: Int = 0\n\n init {\n fishProb = fishingProb\n fishAge = fishingAge\n }\n}\n</code></pre>\n\n<p>can be rewritten to:</p>\n\n<pre><code>class FishingPopulation(\n nMax: Int, \n nZero: Int, \n private var fishProb: Double = 0.0, \n private var fishAge: Int = 0\n) : Population(nMax, nZero)\n</code></pre>\n\n<p>There is one small difference between this code and the previous code:<br>\n<code>fishProb</code> and <code>fishAge</code> now have default-params, which means that they don't have to be specified during construction:</p>\n\n<p><code>FishingPopulation(1, 2)</code> is now the same as <code>FishingPopulation(1, 2, 0, 0)</code><br>\nAlso <code>FishingPopulation(1, 2, fishAge = 1)</code> is the same as <code>FishingPopulation(1, 2, 0, 1)</code></p>\n\n<h1>List</h1>\n\n<h2>MutableList vs ArrayList</h2>\n\n<p>In your code you use the following:</p>\n\n<pre><code>protected var population: MutableList&lt;Animal&gt; = ArrayList()\n</code></pre>\n\n<p>This is perfectly fine, if it <strong>must</strong> be an ArrayList.<br>\nIf this is not required, you could better create the list by it's interface: </p>\n\n<pre><code>protected var population: MutableList&lt;Animal&gt; = mutableListOf()\n//or\nprotected var population = mutableListOf&lt;Animal&gt;()\n</code></pre>\n\n<h2>List vs MutableList</h2>\n\n<p><code>List</code> doesn't allow mutation whereas <code>MutableList</code> does.<br>\nWhen you have code which requires that you mutate a particular list for example if the list is being observed actively for changes, then you need MutableList.<br>\nIn every other case it's probably enough to have a normal List. </p>\n\n<p>For example, the code where you create your parents (inside population) doesn't mutate at all, so copying it to a <code>MutableList</code> is unnecesary.</p>\n\n<pre><code>val parents: MutableList&lt;Animal&gt; = \n population.filter { it.isPregnant() }\n .toMutableList()\n</code></pre>\n\n<h1>transformation-operations</h1>\n\n<p>The code</p>\n\n<pre><code>val parents: MutableList&lt;Animal&gt; = population\n .filter { it.isPregnant() }\nval babies : MutableList&lt;Animal&gt; = ArrayList()\nfor(animal in parents){\n babies.add(animal.giveBirth())\n}\n</code></pre>\n\n<p>can be simplified using map:</p>\n\n<pre><code>val babies = population\n .filter { it.isPregnant() }\n .map{ it.giveBirth() }\n</code></pre>\n\n<p>You add the babies afterwards to a bigger list.<br>\nUsing mapTo, you can add it to the bigger list immediately:</p>\n\n<pre><code>val babies = population\n .filter { it.isPregnant() }\n .mapTo(population){ it.giveBirth() }\n</code></pre>\n\n<p>Both access Population, but it will work because transformation-operations will work with a pattern:</p>\n\n<ol>\n<li>create a new collection</li>\n<li>process the items and add to the collection when needed.</li>\n<li>return the new collection.</li>\n</ol>\n\n<p>Therefor, after the filter-function, population is not accessed anymore.<br>\nThis also means that it isn't very performant...\nWhen you don't want to create a new list every time, you should use <a href=\"https://kotlinlang.org/docs/reference/sequences.html\" rel=\"nofollow noreferrer\">sequences</a>.</p>\n\n<p>see <a href=\"https://kotlinlang.org/docs/tutorials/koans.html\" rel=\"nofollow noreferrer\">Kotlin Koans</a> if you want to learn more about filter, map, zip, window, etc.</p>\n\n<h1>small remarks</h1>\n\n<ul>\n<li><code>nextDouble(0.0,1.0)</code> is the same as <code>nextDouble(1.0)</code></li>\n<li><code>removeIf</code> is from Java. use <code>removeAll</code> instead</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T11:07:50.713", "Id": "240998", "ParentId": "240164", "Score": "3" } } ]
{ "AcceptedAnswerId": "240998", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T20:26:58.340", "Id": "240164", "Score": "6", "Tags": [ "random", "simulation", "kotlin" ], "Title": "Dangers of increasing fishing on a fish population simulation" }
240164
<p>I'm trying to take advantage of <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer">NumPy broadcasting</a> and backend array computations to significantly speed up this function. Unfortunately, it doesn't scale so well so I'm hoping to greatly improve the performance of this. Right now the code isn't properly utilizing broadcasting for the computations. </p> <p><strong>Is there a way where I can do operations on the matrix instead of individually calculating pairwise associations?</strong> </p> <pre><code># ============================================================================== # Imports # ============================================================================== # Built-ins import os, sys, time, multiprocessing # 3rd party import numpy as np import pandas as pd # Python def _biweight_midcorrelation(a, b): a_median = np.median(a) b_median = np.median(b) # Median absolute deviation a_mad = np.median(np.abs(a - a_median)) b_mad = np.median(np.abs(b - b_median)) u = (a - a_median) / (9 * a_mad) v = (b - b_median) / (9 * b_mad) w_a = np.square(1 - np.square(u)) * ((1 - np.abs(u)) &gt; 0) w_b = np.square(1 - np.square(v)) * ((1 - np.abs(v)) &gt; 0) a_item = (a - a_median) * w_a b_item = (b - b_median) * w_b return (a_item * b_item).sum() / ( np.sqrt(np.square(a_item).sum()) * np.sqrt(np.square(b_item).sum())) def biweight_midcorrelation(X): return X.corr(method=_biweight_midcorrelation) # # OLD IMPLEMENTATION # def biweight_midcorrelation(X): # median = X.median() # mad = (X - median).abs().median() # U = (X - median) / (9 * mad) # adjacency = np.square(1 - np.square(U)) * ((1 - U.abs()) &gt; 0) # estimator = (X - median) * adjacency # bicor_matrix = np.empty((X.shape[1], X.shape[1]), dtype=float) # for i, ac in enumerate(estimator): # for j, bc in enumerate(estimator): # a = estimator[ac] # b = estimator[bc] # c = (a * b).sum() / ( # np.sqrt(np.square(a).sum()) * np.sqrt(np.square(b).sum())) # bicor_matrix[i, j] = c # bicor_matrix[j, i] = c # return pd.DataFrame(bicor_matrix, index=X.columns, columns=X.columns) # X.shape = (150,4) X = pd.DataFrame({'sepal_length': {'iris_0': 5.1, 'iris_1': 4.9, 'iris_2': 4.7, 'iris_3': 4.6, 'iris_4': 5.0, 'iris_5': 5.4, 'iris_6': 4.6, 'iris_7': 5.0, 'iris_8': 4.4, 'iris_9': 4.9, 'iris_10': 5.4, 'iris_11': 4.8, 'iris_12': 4.8, 'iris_13': 4.3, 'iris_14': 5.8, 'iris_15': 5.7, 'iris_16': 5.4, 'iris_17': 5.1, 'iris_18': 5.7, 'iris_19': 5.1, 'iris_20': 5.4, 'iris_21': 5.1, 'iris_22': 4.6, 'iris_23': 5.1, 'iris_24': 4.8, 'iris_25': 5.0, 'iris_26': 5.0, 'iris_27': 5.2, 'iris_28': 5.2, 'iris_29': 4.7, 'iris_30': 4.8, 'iris_31': 5.4, 'iris_32': 5.2, 'iris_33': 5.5, 'iris_34': 4.9, 'iris_35': 5.0, 'iris_36': 5.5, 'iris_37': 4.9, 'iris_38': 4.4, 'iris_39': 5.1, 'iris_40': 5.0, 'iris_41': 4.5, 'iris_42': 4.4, 'iris_43': 5.0, 'iris_44': 5.1, 'iris_45': 4.8, 'iris_46': 5.1, 'iris_47': 4.6, 'iris_48': 5.3, 'iris_49': 5.0, 'iris_50': 7.0, 'iris_51': 6.4, 'iris_52': 6.9, 'iris_53': 5.5, 'iris_54': 6.5, 'iris_55': 5.7, 'iris_56': 6.3, 'iris_57': 4.9, 'iris_58': 6.6, 'iris_59': 5.2, 'iris_60': 5.0, 'iris_61': 5.9, 'iris_62': 6.0, 'iris_63': 6.1, 'iris_64': 5.6, 'iris_65': 6.7, 'iris_66': 5.6, 'iris_67': 5.8, 'iris_68': 6.2, 'iris_69': 5.6, 'iris_70': 5.9, 'iris_71': 6.1, 'iris_72': 6.3, 'iris_73': 6.1, 'iris_74': 6.4, 'iris_75': 6.6, 'iris_76': 6.8, 'iris_77': 6.7, 'iris_78': 6.0, 'iris_79': 5.7, 'iris_80': 5.5, 'iris_81': 5.5, 'iris_82': 5.8, 'iris_83': 6.0, 'iris_84': 5.4, 'iris_85': 6.0, 'iris_86': 6.7, 'iris_87': 6.3, 'iris_88': 5.6, 'iris_89': 5.5, 'iris_90': 5.5, 'iris_91': 6.1, 'iris_92': 5.8, 'iris_93': 5.0, 'iris_94': 5.6, 'iris_95': 5.7, 'iris_96': 5.7, 'iris_97': 6.2, 'iris_98': 5.1, 'iris_99': 5.7, 'iris_100': 6.3, 'iris_101': 5.8, 'iris_102': 7.1, 'iris_103': 6.3, 'iris_104': 6.5, 'iris_105': 7.6, 'iris_106': 4.9, 'iris_107': 7.3, 'iris_108': 6.7, 'iris_109': 7.2, 'iris_110': 6.5, 'iris_111': 6.4, 'iris_112': 6.8, 'iris_113': 5.7, 'iris_114': 5.8, 'iris_115': 6.4, 'iris_116': 6.5, 'iris_117': 7.7, 'iris_118': 7.7, 'iris_119': 6.0, 'iris_120': 6.9, 'iris_121': 5.6, 'iris_122': 7.7, 'iris_123': 6.3, 'iris_124': 6.7, 'iris_125': 7.2, 'iris_126': 6.2, 'iris_127': 6.1, 'iris_128': 6.4, 'iris_129': 7.2, 'iris_130': 7.4, 'iris_131': 7.9, 'iris_132': 6.4, 'iris_133': 6.3, 'iris_134': 6.1, 'iris_135': 7.7, 'iris_136': 6.3, 'iris_137': 6.4, 'iris_138': 6.0, 'iris_139': 6.9, 'iris_140': 6.7, 'iris_141': 6.9, 'iris_142': 5.8, 'iris_143': 6.8, 'iris_144': 6.7, 'iris_145': 6.7, 'iris_146': 6.3, 'iris_147': 6.5, 'iris_148': 6.2, 'iris_149': 5.9}, 'sepal_width': {'iris_0': 3.5, 'iris_1': 3.0, 'iris_2': 3.2, 'iris_3': 3.1, 'iris_4': 3.6, 'iris_5': 3.9, 'iris_6': 3.4, 'iris_7': 3.4, 'iris_8': 2.9, 'iris_9': 3.1, 'iris_10': 3.7, 'iris_11': 3.4, 'iris_12': 3.0, 'iris_13': 3.0, 'iris_14': 4.0, 'iris_15': 4.4, 'iris_16': 3.9, 'iris_17': 3.5, 'iris_18': 3.8, 'iris_19': 3.8, 'iris_20': 3.4, 'iris_21': 3.7, 'iris_22': 3.6, 'iris_23': 3.3, 'iris_24': 3.4, 'iris_25': 3.0, 'iris_26': 3.4, 'iris_27': 3.5, 'iris_28': 3.4, 'iris_29': 3.2, 'iris_30': 3.1, 'iris_31': 3.4, 'iris_32': 4.1, 'iris_33': 4.2, 'iris_34': 3.1, 'iris_35': 3.2, 'iris_36': 3.5, 'iris_37': 3.6, 'iris_38': 3.0, 'iris_39': 3.4, 'iris_40': 3.5, 'iris_41': 2.3, 'iris_42': 3.2, 'iris_43': 3.5, 'iris_44': 3.8, 'iris_45': 3.0, 'iris_46': 3.8, 'iris_47': 3.2, 'iris_48': 3.7, 'iris_49': 3.3, 'iris_50': 3.2, 'iris_51': 3.2, 'iris_52': 3.1, 'iris_53': 2.3, 'iris_54': 2.8, 'iris_55': 2.8, 'iris_56': 3.3, 'iris_57': 2.4, 'iris_58': 2.9, 'iris_59': 2.7, 'iris_60': 2.0, 'iris_61': 3.0, 'iris_62': 2.2, 'iris_63': 2.9, 'iris_64': 2.9, 'iris_65': 3.1, 'iris_66': 3.0, 'iris_67': 2.7, 'iris_68': 2.2, 'iris_69': 2.5, 'iris_70': 3.2, 'iris_71': 2.8, 'iris_72': 2.5, 'iris_73': 2.8, 'iris_74': 2.9, 'iris_75': 3.0, 'iris_76': 2.8, 'iris_77': 3.0, 'iris_78': 2.9, 'iris_79': 2.6, 'iris_80': 2.4, 'iris_81': 2.4, 'iris_82': 2.7, 'iris_83': 2.7, 'iris_84': 3.0, 'iris_85': 3.4, 'iris_86': 3.1, 'iris_87': 2.3, 'iris_88': 3.0, 'iris_89': 2.5, 'iris_90': 2.6, 'iris_91': 3.0, 'iris_92': 2.6, 'iris_93': 2.3, 'iris_94': 2.7, 'iris_95': 3.0, 'iris_96': 2.9, 'iris_97': 2.9, 'iris_98': 2.5, 'iris_99': 2.8, 'iris_100': 3.3, 'iris_101': 2.7, 'iris_102': 3.0, 'iris_103': 2.9, 'iris_104': 3.0, 'iris_105': 3.0, 'iris_106': 2.5, 'iris_107': 2.9, 'iris_108': 2.5, 'iris_109': 3.6, 'iris_110': 3.2, 'iris_111': 2.7, 'iris_112': 3.0, 'iris_113': 2.5, 'iris_114': 2.8, 'iris_115': 3.2, 'iris_116': 3.0, 'iris_117': 3.8, 'iris_118': 2.6, 'iris_119': 2.2, 'iris_120': 3.2, 'iris_121': 2.8, 'iris_122': 2.8, 'iris_123': 2.7, 'iris_124': 3.3, 'iris_125': 3.2, 'iris_126': 2.8, 'iris_127': 3.0, 'iris_128': 2.8, 'iris_129': 3.0, 'iris_130': 2.8, 'iris_131': 3.8, 'iris_132': 2.8, 'iris_133': 2.8, 'iris_134': 2.6, 'iris_135': 3.0, 'iris_136': 3.4, 'iris_137': 3.1, 'iris_138': 3.0, 'iris_139': 3.1, 'iris_140': 3.1, 'iris_141': 3.1, 'iris_142': 2.7, 'iris_143': 3.2, 'iris_144': 3.3, 'iris_145': 3.0, 'iris_146': 2.5, 'iris_147': 3.0, 'iris_148': 3.4, 'iris_149': 3.0}, 'petal_length': {'iris_0': 1.4, 'iris_1': 1.4, 'iris_2': 1.3, 'iris_3': 1.5, 'iris_4': 1.4, 'iris_5': 1.7, 'iris_6': 1.4, 'iris_7': 1.5, 'iris_8': 1.4, 'iris_9': 1.5, 'iris_10': 1.5, 'iris_11': 1.6, 'iris_12': 1.4, 'iris_13': 1.1, 'iris_14': 1.2, 'iris_15': 1.5, 'iris_16': 1.3, 'iris_17': 1.4, 'iris_18': 1.7, 'iris_19': 1.5, 'iris_20': 1.7, 'iris_21': 1.5, 'iris_22': 1.0, 'iris_23': 1.7, 'iris_24': 1.9, 'iris_25': 1.6, 'iris_26': 1.6, 'iris_27': 1.5, 'iris_28': 1.4, 'iris_29': 1.6, 'iris_30': 1.6, 'iris_31': 1.5, 'iris_32': 1.5, 'iris_33': 1.4, 'iris_34': 1.5, 'iris_35': 1.2, 'iris_36': 1.3, 'iris_37': 1.4, 'iris_38': 1.3, 'iris_39': 1.5, 'iris_40': 1.3, 'iris_41': 1.3, 'iris_42': 1.3, 'iris_43': 1.6, 'iris_44': 1.9, 'iris_45': 1.4, 'iris_46': 1.6, 'iris_47': 1.4, 'iris_48': 1.5, 'iris_49': 1.4, 'iris_50': 4.7, 'iris_51': 4.5, 'iris_52': 4.9, 'iris_53': 4.0, 'iris_54': 4.6, 'iris_55': 4.5, 'iris_56': 4.7, 'iris_57': 3.3, 'iris_58': 4.6, 'iris_59': 3.9, 'iris_60': 3.5, 'iris_61': 4.2, 'iris_62': 4.0, 'iris_63': 4.7, 'iris_64': 3.6, 'iris_65': 4.4, 'iris_66': 4.5, 'iris_67': 4.1, 'iris_68': 4.5, 'iris_69': 3.9, 'iris_70': 4.8, 'iris_71': 4.0, 'iris_72': 4.9, 'iris_73': 4.7, 'iris_74': 4.3, 'iris_75': 4.4, 'iris_76': 4.8, 'iris_77': 5.0, 'iris_78': 4.5, 'iris_79': 3.5, 'iris_80': 3.8, 'iris_81': 3.7, 'iris_82': 3.9, 'iris_83': 5.1, 'iris_84': 4.5, 'iris_85': 4.5, 'iris_86': 4.7, 'iris_87': 4.4, 'iris_88': 4.1, 'iris_89': 4.0, 'iris_90': 4.4, 'iris_91': 4.6, 'iris_92': 4.0, 'iris_93': 3.3, 'iris_94': 4.2, 'iris_95': 4.2, 'iris_96': 4.2, 'iris_97': 4.3, 'iris_98': 3.0, 'iris_99': 4.1, 'iris_100': 6.0, 'iris_101': 5.1, 'iris_102': 5.9, 'iris_103': 5.6, 'iris_104': 5.8, 'iris_105': 6.6, 'iris_106': 4.5, 'iris_107': 6.3, 'iris_108': 5.8, 'iris_109': 6.1, 'iris_110': 5.1, 'iris_111': 5.3, 'iris_112': 5.5, 'iris_113': 5.0, 'iris_114': 5.1, 'iris_115': 5.3, 'iris_116': 5.5, 'iris_117': 6.7, 'iris_118': 6.9, 'iris_119': 5.0, 'iris_120': 5.7, 'iris_121': 4.9, 'iris_122': 6.7, 'iris_123': 4.9, 'iris_124': 5.7, 'iris_125': 6.0, 'iris_126': 4.8, 'iris_127': 4.9, 'iris_128': 5.6, 'iris_129': 5.8, 'iris_130': 6.1, 'iris_131': 6.4, 'iris_132': 5.6, 'iris_133': 5.1, 'iris_134': 5.6, 'iris_135': 6.1, 'iris_136': 5.6, 'iris_137': 5.5, 'iris_138': 4.8, 'iris_139': 5.4, 'iris_140': 5.6, 'iris_141': 5.1, 'iris_142': 5.1, 'iris_143': 5.9, 'iris_144': 5.7, 'iris_145': 5.2, 'iris_146': 5.0, 'iris_147': 5.2, 'iris_148': 5.4, 'iris_149': 5.1}, 'petal_width': {'iris_0': 0.2, 'iris_1': 0.2, 'iris_2': 0.2, 'iris_3': 0.2, 'iris_4': 0.2, 'iris_5': 0.4, 'iris_6': 0.3, 'iris_7': 0.2, 'iris_8': 0.2, 'iris_9': 0.1, 'iris_10': 0.2, 'iris_11': 0.2, 'iris_12': 0.1, 'iris_13': 0.1, 'iris_14': 0.2, 'iris_15': 0.4, 'iris_16': 0.4, 'iris_17': 0.3, 'iris_18': 0.3, 'iris_19': 0.3, 'iris_20': 0.2, 'iris_21': 0.4, 'iris_22': 0.2, 'iris_23': 0.5, 'iris_24': 0.2, 'iris_25': 0.2, 'iris_26': 0.4, 'iris_27': 0.2, 'iris_28': 0.2, 'iris_29': 0.2, 'iris_30': 0.2, 'iris_31': 0.4, 'iris_32': 0.1, 'iris_33': 0.2, 'iris_34': 0.2, 'iris_35': 0.2, 'iris_36': 0.2, 'iris_37': 0.1, 'iris_38': 0.2, 'iris_39': 0.2, 'iris_40': 0.3, 'iris_41': 0.3, 'iris_42': 0.2, 'iris_43': 0.6, 'iris_44': 0.4, 'iris_45': 0.3, 'iris_46': 0.2, 'iris_47': 0.2, 'iris_48': 0.2, 'iris_49': 0.2, 'iris_50': 1.4, 'iris_51': 1.5, 'iris_52': 1.5, 'iris_53': 1.3, 'iris_54': 1.5, 'iris_55': 1.3, 'iris_56': 1.6, 'iris_57': 1.0, 'iris_58': 1.3, 'iris_59': 1.4, 'iris_60': 1.0, 'iris_61': 1.5, 'iris_62': 1.0, 'iris_63': 1.4, 'iris_64': 1.3, 'iris_65': 1.4, 'iris_66': 1.5, 'iris_67': 1.0, 'iris_68': 1.5, 'iris_69': 1.1, 'iris_70': 1.8, 'iris_71': 1.3, 'iris_72': 1.5, 'iris_73': 1.2, 'iris_74': 1.3, 'iris_75': 1.4, 'iris_76': 1.4, 'iris_77': 1.7, 'iris_78': 1.5, 'iris_79': 1.0, 'iris_80': 1.1, 'iris_81': 1.0, 'iris_82': 1.2, 'iris_83': 1.6, 'iris_84': 1.5, 'iris_85': 1.6, 'iris_86': 1.5, 'iris_87': 1.3, 'iris_88': 1.3, 'iris_89': 1.3, 'iris_90': 1.2, 'iris_91': 1.4, 'iris_92': 1.2, 'iris_93': 1.0, 'iris_94': 1.3, 'iris_95': 1.2, 'iris_96': 1.3, 'iris_97': 1.3, 'iris_98': 1.1, 'iris_99': 1.3, 'iris_100': 2.5, 'iris_101': 1.9, 'iris_102': 2.1, 'iris_103': 1.8, 'iris_104': 2.2, 'iris_105': 2.1, 'iris_106': 1.7, 'iris_107': 1.8, 'iris_108': 1.8, 'iris_109': 2.5, 'iris_110': 2.0, 'iris_111': 1.9, 'iris_112': 2.1, 'iris_113': 2.0, 'iris_114': 2.4, 'iris_115': 2.3, 'iris_116': 1.8, 'iris_117': 2.2, 'iris_118': 2.3, 'iris_119': 1.5, 'iris_120': 2.3, 'iris_121': 2.0, 'iris_122': 2.0, 'iris_123': 1.8, 'iris_124': 2.1, 'iris_125': 1.8, 'iris_126': 1.8, 'iris_127': 1.8, 'iris_128': 2.1, 'iris_129': 1.6, 'iris_130': 1.9, 'iris_131': 2.0, 'iris_132': 2.2, 'iris_133': 1.5, 'iris_134': 1.4, 'iris_135': 2.3, 'iris_136': 2.4, 'iris_137': 1.8, 'iris_138': 1.8, 'iris_139': 2.1, 'iris_140': 2.4, 'iris_141': 2.3, 'iris_142': 1.9, 'iris_143': 2.3, 'iris_144': 2.5, 'iris_145': 2.3, 'iris_146': 1.9, 'iris_147': 2.0, 'iris_148': 2.3, 'iris_149': 1.8}}) # Python computation df_bicor = biweight_midcorrelation(X) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T21:10:33.910", "Id": "240167", "Score": "1", "Tags": [ "python", "array", "numpy", "matrix" ], "Title": "How to optimize code to take advantage of NumPy broadcasting when calculating pairwise correlation?" }
240167
<p>I quite like <code>purrr::partial()</code>, which allows us to easily create partial functions. However, the partial function loses its remaining arguments from its signature (replaced with <code>...</code>):</p> <pre class="lang-r prettyprint-override"><code>f &lt;- function(x, y) { print(x) print(y) return(invisible()) } ff &lt;- purrr::partial(f, y = 1) ff(2) #&gt; [1] 2 #&gt; [1] 1 ff #&gt; &lt;partialised&gt; #&gt; function (...) #&gt; f(y = 1, ...) </code></pre> <p>So when developing and trying to remember the positions or names of the remaining arguments for the partial function, we're forced to check the original function instead. So I decided to create my own version which keeps the arguments:</p> <pre class="lang-r prettyprint-override"><code>partialize &lt;- function(.f, ...) { dots &lt;- c(...) dotsNames &lt;- names(dots) symbols &lt;- rlang::syms(dotsNames) new.f &lt;- .f args &lt;- rlang::fn_fmls(new.f) args[names(dots)] &lt;- NULL rlang::fn_fmls(new.f) &lt;- args rlang::fn_body(new.f) &lt;- rlang::expr({ !!!mapply(rlang::call2, symbols, dots, MoreArgs = list(.fn = "&lt;-")) !!rlang::fn_body(new.f) }) return(new.f) } </code></pre> <p>This function performs basically like <code>purrr::partial</code>, but keeps argument names.</p> <pre class="lang-r prettyprint-override"><code>f &lt;- function(a, b, d) { print(paste(a, b, d)) } x &lt;- partialize(f, a = 1, d = 3) x #&gt; function (b) #&gt; { #&gt; a &lt;- 1 #&gt; d &lt;- 3 #&gt; { #&gt; print(paste(a, b, d)) #&gt; } #&gt; } x(2) #&gt; [1] "1 2 3" </code></pre> <p>Note how inspecting <code>x</code> shows its remaining argument <code>b</code>.</p> <p>This method is different from <code>purrr::partial</code> in that arguments are eagerly evaluated. It also doesn't have a <a href="https://github.com/tidyverse/purrr/issues/656" rel="nofollow noreferrer">bug</a> found in how <code>purrr::partial</code> handles invisible returns (though I'm sure you all will find plenty of others!).</p> <pre class="lang-r prettyprint-override"><code>z &lt;- 1 purrrf &lt;- purrr::partial(f, d = z) myf &lt;- partialize(f, d = z) purrrf(1, 2) #&gt; [1] "1 2 1" #&gt; [1] "1 2 1" myf(1, 2) #&gt; [1] "1 2 1" z &lt;- 2 purrrf(1, 2) #&gt; [1] "1 2 2" #&gt; [1] "1 2 2" myf(1, 2) #&gt; [1] "1 2 1" # kept z = 1 purrrf #&gt; &lt;partialised&gt; #&gt; function (...) #&gt; f(d = z, ...) myf #&gt; function (a, b) #&gt; { #&gt; d &lt;- 1 #&gt; { #&gt; print(paste(a, b, d)) #&gt; } #&gt; } #&gt; &lt;bytecode: 0x000000000806f8d8&gt; </code></pre> <p>A big drawback I've found with <code>partialize</code> is that it doesn't work with generic functions (i.e. those whose body is merely <code>UseMethod(...)</code>) with default values for their arguments. Since it sets the arguments as variables in its own environment instead of calling the original function with the arguments as actual arguments, the <code>UseMethod(...)</code> call doesn't catch the arguments.</p> <pre class="lang-r prettyprint-override"><code>partialize(mean, na.rm = TRUE) function (x, ...) { na.rm &lt;- TRUE { UseMethod("mean") } } </code></pre> <p>As always, happy for any and all comments on the code, and if anyone can figure out how to allow for lazy evaluation (so as to keep in line with <code>purrr::partial</code>), that'd be great.</p> <hr> <p>To be clear: <code>partialize</code> is a function to be included in an in-house utility package, and is therefore somewhat generic. The function <code>f</code> above is merely a placeholder demonstrating <code>partialize</code>'s functionality, but the question here is essentially about how <code>partialize</code> itself has been written, whether it can be improved (by adding lazy evaluation or any other way you see fit) and if it has any drawbacks I haven't realized versus <code>purrr::partial</code>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T21:26:01.893", "Id": "240169", "Score": "4", "Tags": [ "r" ], "Title": "purrr::partial() but keeping function signature" }
240169
<h2> Description </h2> <p>I wanted to understand how integers can be written and stored inside variables without the use of Serial.parseInt(). I couldn't find any code examples about this. Perhaps this is the right way to do it, although it doesn't detect and block letters and special characters. Please leave some feedback on ways to improve it. Thanks in advance! :)</p> <pre><code>void setup() { Serial.begin(9600); // Opens serial port, sets data rate to 9600 bps Serial.println(F("Serial port opened!")); } void loop() { byte received; static byte counter = 0; static uint32_t number = 0; // Store value from 0 to 4294967295 while (Serial.available()) // Read data in serial receive buffer { received = Serial.read(); // Store received byte if (received != 10) // Terminate if newline char detected { if (counter != 0) // Put number in its correct position (base-10 system) { number *= 10; number += (received - '0'); } else { number = (received - '0'); } counter++; } else { Serial.println(number); // Print value inside number and reset counter = 0; } } } </code></pre>
[]
[ { "body": "<h2>Character literals</h2>\n\n<p>While this is technically correct:</p>\n\n<pre><code>if (received != 10) // Terminate if newline char detected\n</code></pre>\n\n<p>you're better off writing</p>\n\n<pre><code>if (received != '\\n')\n</code></pre>\n\n<p>Much of embedded electronics assumes ASCII encoding, and this is no exception, but you're still better off using the symbol instead of the code.</p>\n\n<h2>IO management</h2>\n\n<p>You loop while serial I/O is available:</p>\n\n<pre><code>while (Serial.available())\n</code></pre>\n\n<p>But what if there is a pause in the availability of bytes in the middle of your integer? Your code will not do the right thing. Instead:</p>\n\n<pre><code>uint32_t number = 0;\nwhile (true) {\n int received = Serial.read();\n if (received == -1) continue;\n if (received == '\\n') break;\n // ...\n}\nSerial.println(number);\n</code></pre>\n\n<ul>\n<li>Do not use <code>static</code> for <code>number</code></li>\n<li>Don't need a <code>counter</code></li>\n<li>Keep looping if no data are available</li>\n<li>Ensure that one execution of <code>loop</code> maps to one full output integer</li>\n</ul>\n\n<h2>Condition in loop</h2>\n\n<p>If you are using the ATmega328P, it has a dedicated <code>MUL</code> instruction that only takes two cycles. It's more complex and expensive to have your <code>if (counter != 0)</code> than it is to simply unconditionally multiply-and-add.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T20:57:33.850", "Id": "471418", "Score": "1", "body": "Re: \"Do not use static for number\nDon't need a counter\" ==> OP looks like `loop()` is a service function, not always called when data first arrives, but as it arrives. OP's approach is OK in that case. A non-global alternative would pass in the state data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T21:43:38.437", "Id": "471425", "Score": "1", "body": "Minor: to be _technically correct_, `'\\n'` is an _integer constant_, not a _character literal_. C does define _string literals_ and _compound literals_, but no other _literals_. Perhaps you are thinking of another language?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:00:55.920", "Id": "471503", "Score": "1", "body": "Re. statics - it's a common micro-optimization in embedded code to make a function non-reentrant by switching local variables to `static`; and technically `loop` is a \"service\" function that's called by the Arduino firmware and does not need to be re-entrant. However, such an optimization is premature, and statics are a bad idea to invoke unless thoroughly justified." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:01:19.350", "Id": "471504", "Score": "1", "body": "Also, there is no correlation between the arrival of data and the timing of a `loop` call." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:05:34.517", "Id": "471505", "Score": "1", "body": "Also also, to be _technically correct_ (the best type of correct), this is not C, nor is it even C++ - it's \"Wiring\", which is a dialect of C++." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:12:06.263", "Id": "471508", "Score": "1", "body": "@chux Finally - many, many sources (take your pick, but https://en.wikipedia.org/wiki/Character_literal or https://en.cppreference.com/w/cpp/language/character_literal come to mind) explicitly describe character literals in C++; and certainly C++ has more of a character literal than (say) Python, which only has length-one strings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:58:10.037", "Id": "471519", "Score": "1", "body": "As the post was originally tagged C, implying the OP wanted a C review, the source I used was the C spec. There is nothing about OP code that would not compile in C. As to if the code review was to be based on another language, best to ask OP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T16:03:50.553", "Id": "471521", "Score": "1", "body": "_There is nothing about OP code that would not compile in C_ - well, `Serial` is a class. So not nothing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T16:05:34.367", "Id": "471523", "Score": "1", "body": "In C, a `struct` can have members that are functions pointers and look just like `Serial.begin(9600);`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T16:08:25.690", "Id": "471524", "Score": "1", "body": "Sure, but \"look just like\" is a theoretical, and this is a concrete reference to something that's in the Wiring library, which is definitely not using a `struct`. It doesn't matter if this \"can be\" C code when it is certainly C++ code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T18:01:50.770", "Id": "471675", "Score": "0", "body": "As a beginner this all looks like Chinese to me! I tried to stick to C as much as possible as my knowledge about C++ is even less. Would it be possible to execute a function if data arrived in the 'Serial' buffer (without using a loop)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T18:38:21.670", "Id": "471678", "Score": "1", "body": "Let us continue this discussion in chat - https://chat.stackexchange.com/rooms/info/106684" } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T13:59:36.413", "Id": "240206", "ParentId": "240173", "Score": "3" } }, { "body": "<p>For more robust code to detect non-numeric input, overflow and start-up phasing, consider a <a href=\"https://stackoverflow.com/questions/1647631/c-state-machine-design/1647679#1647679\">state machine</a>.</p>\n\n<pre><code>typedef struct {\n int counter; // &lt;0:indeterminate, 0:spacing, &gt;0:digits; \n uint32_t number;\n} loop_state;\n\n// Quietly drop data in 3 cases:\n// 1) Overflow\n// 2) Non-numeric\n// 3) When state is indeterminate\nvoid loop(loop_state *state) {\n while (Serial.available()) {\n byte received = Serial.read(); // Store received byte\n if (received &gt;= '0' || received &lt;= '9') { // or isdigit((unsigned char) received)\n if (state-&gt;counter &gt;= 0) {\n state-&gt;counter++;\n unsigned digit = received - '0';\n if (state-&gt;number &gt;= UINT32_MAX / 10\n &amp;&amp; (state-&gt;number &gt; UINT32_MAX / 10 || digit &gt; UINT32_MAX % 10)) {\n // overflow\n state-&gt;counter = -1;\n continue;\n }\n state-&gt;number = state-&gt;number * 10 + digit;\n }\n } else if (isspace((unsigned char) received)) {\n if (state-&gt;counter == 1) {\n Serial.println(state-&gt;number);\n }\n state-&gt;number = 0;\n state-&gt;counter = 0;\n } else {\n state-&gt;number = 0;\n state-&gt;counter = -1;\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T21:25:52.210", "Id": "240361", "ParentId": "240173", "Score": "2" } } ]
{ "AcceptedAnswerId": "240206", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T23:17:05.277", "Id": "240173", "Score": "2", "Tags": [ "c++", "beginner", "integer", "serialization", "arduino" ], "Title": "Reading and Storing Integer from Serial Monitor" }
240173
<p>A couple of days ago a user in chat asked us to spend more time in the queues. Kick starting my desire to get notifications for new items in the queues.<br> Reviewing the queues has been something I've wanted to do for a long time now. But I've never built a habit to check daily, and so I've wanted to use <a href="https://codereview.stackexchange.com/users/31562/simon-forsberg">Simon Forsberg's</a> <a href="https://codereview.stackexchange.com/q/97268">Desktop Notifications for flags and queue items</a> user script for a while now. The only problem is that it doesn't work for me, and given the design changes SE has recently made, it's only more broken.</p> <p>Originally I planned to fix Simon's user script, however my pre-ES 2015 JavaScript skills are not great. And so I could barely understand Simon's code never mind fix the issues I was having.</p> <p>To use the script:</p> <ol> <li>Install it like you would any other user script.</li> <li>Navigate to <a href="https://codereview.stackexchange.com/review">Code Review's review page</a>.</li> <li>If you haven't enabled notifications it should prompt you to allow them.<br> If it does not prompt you then you can enable them by pressing the options button to the left hand side of the URL.</li> <li>Reload the page.</li> </ol> <p>I feel my code doesn't really follow YAGNI as I have implemented a lot of classes. And currently <code>Notifications</code> is fairly redundant. I think this is acceptable as later on when I've not read the user script for a while all the helpful names and short docstrings should point me in the right direction. Knowing what <code>Review.title()</code> means is, to me, far easier than understanding what <code>foo.children[1].children[0].children[0].innerText</code> is.</p> <p>The code is also as close to pure JS as I could reasonably get. This means anyone with any compliant browser and any userscript plugin should be able to run the code. Meaning there's no accidental Greasemonkey/Tampermonkey/Violentmonkey incompatibilities.</p> <p>I think I've followed JavaScript's conventions, however I've not written any in a short while.<br> Any and all reviews are welcome.</p> <pre><code>// ==UserScript== // @name Review Notifications // @namespace Violentmonkey Scripts // @match *://*.stackexchange.com/review // @grant none // @version 1.0 // @author Peilonrayz // @description Get notifications for new review items. // ==/UserScript== // Enum of push states const Status = Object.freeze({ NOT_IMPLEMENTED: 1, DENIED: 2, GRANTED: 3, DEFAULT: 4, UNKNOWN: 5, }); function pushStatus(status) { // Convert from a string into the enum's value if (status === undefined) { return Status.NOT_IMPLEMENTED; } if (status === "denied") { return Status.DENIED; } if (status === "granted") { return Status.GRANTED; } if (status === "default") { return Status.DEFAULT; } return Status.UNKNOWN; } class PushNotification { // A small wrapper to Notification to expose the observer interface static async enable() { // Enable notifications if possible // // This returns the current state regardless if notifications are enabled. // This returns if enabled and errors if it is not possible. // This allows simple and clean usage with await or `then`. let status = pushStatus(Notification.permission); // Prompt user to allow us to push notifications if (status === Status.DEFAULT) { status = pushStatus(await Notification.requestPermission()); } if (status === Status.GRANTED) { return status; } throw status; } notify(notification) { // Push a notification to the system new Notification(notification.title, notification); } } class Notifications { // Holds a collections of observers that we can push notifications to. // // This is here as I may want to implement additional observers. // For example alerting if push notifications are unavailable is an option. // This allows easy additions without having to change more than just the // creation of objects. constructor() { this.clients = []; } add(client) { // Add an observer to the subject this.clients.push(client); } notify(notification) { // Notify all observers for (const observer of this.clients) { observer.notify(notification); } } } class Review { // Interface to the underlying review information constructor(object) { this.object = object; } static* findAll() { // Get all reviews on the current page. for (let review of $("#content")[0].children[1].children[0].children) { if (!review.className.contains("grid")) { continue; } yield new Review(review); } } amount() { // Get the current amount of reviews. return +this.object.children[0].children[0].innerText; } title() { // Get the queue's title return this.object.children[1].children[0].children[0].innerText; } } function split_once(value, sep) { // Helper function to only split by a seperator once. // // This is not the same as `"abc def ghi".split(" ", 2)` as that would // result in ["abc", "def"] rather than ["abc", "def ghi"] let index = value.indexOf(sep); if (index === -1) { return [value, ""]; } return [value.slice(0, index), value.slice(index + sep.length)] } class Cookies { // A map like interface to the cookies. constructor() { this.cookies = new Map(); this.update(); } update() { // Update the internal map from the cookies on the page. // // This is useful when other code on the page changes the cookies but // not through this object. this.cookies = new Map(document.cookie.split(';').map(c =&gt; split_once(c.trim(), "="))); } get(key) { // Get the value of the cookie by its name return this.cookies.get(key); } set(key, value) { // Set a cookie to the provided value this.cookies.set(key, value); document.cookie = key + "=" + value; } } function findReviews(notifications) { // Find and notify the user about new reviews. // // 1. This is provided a fully initialized Notifications object. // 2. Initialize a Cookies object to allow comparisions with the previous // page load. This is important as otherwise the code would // continuously notify users of all active reviews. // 3. For each review on the page: // 1. Verify if there are new reviews - comparing with the cookie. // 2. Notify the user if there is a new review. // 3. Update the cookie to the new value. // 4. Reload the page. let cookies = new Cookies(); for (let review of Review.findAll()) { let prev = cookies.get(review.title()); let prevAmount = prev === undefined ? 0 : +prev; console.log(review.title(), prevAmount, "-&gt;", review.amount(), prevAmount &lt; review.amount()); if (prevAmount &lt; review.amount()) { notifications.notify({ "title": review.amount() + " reviews in " + review.title(), "icon": "https://cdn.sstatic.net/Sites/codereview/img/apple-touch-icon.png?v=0a72875519a4", }) } cookies.set(review.title(), review.amount()); } setTimeout(function(){ window.location.reload(); }, 60 * 1000); } function main() { // Build notifications and find reviews. const notifications = new Notifications(); PushNotification.enable().then( () =&gt; { notifications.add(new PushNotification()); findReviews(notifications); }, (status) =&gt; console.log("Can't notify status code", status), ); } main() </code></pre>
[]
[ { "body": "<p>I don't see much benefit to the enum. The <code>Notification.permission</code> string (or the return value of <code>requestPermission()</code>) is already pretty clear: <code>'denied'</code>, <code>'granted'</code>, or <code>'default'</code>. The specification <a href=\"https://notifications.spec.whatwg.org/#api\" rel=\"noreferrer\">requires</a> that it be one of those, if <code>window.Notification</code> exists. Passing around a number instead of a more intuitive string seems a bit odd.</p>\n\n<p>In Javascript, at least in my opinion, classes are generally useful when you want to <a href=\"https://codereview.stackexchange.com/a/239951\">bundle state data with methods</a>. If you're not using instance properties, consider using plain functions (or an object of functions, if you have multiple related ones) instead; the intent of the code will be clearer, and it'll look a bit simpler.</p>\n\n<p><code>.then(success, fail)</code> is generally <a href=\"https://stackoverflow.com/q/24662289\">considered an antipattern for promises</a>. Unless you <em>deliberately want</em> the somewhat odd control flow it results in, it would be better to use <code>.then</code> followed by <code>.catch</code>, so that your <code>catch</code> can catch errors that may occur in the <code>.then</code>.</p>\n\n<p>But <a href=\"https://mattwarren.org/2016/12/20/Why-Exceptions-should-be-Exceptional/\" rel=\"noreferrer\">exceptions should be exceptional</a>. They require unwinding the whole call stack and, when you're working with a self-contained script, generally don't provide any control flow benefits. Rather than throwing, it might be preferable to just check the permission result, and if it's not <code>'granted'</code>, log an error and exit.</p>\n\n<pre><code>const canNotify = async () =&gt; {\n if (Notification.permission === 'default') {\n await Notification.requestPermission()\n }\n const { permission } = Notification;\n if (permission !== 'granted') {\n console.error(`Notifications not permitted. Permission status: ${permission}`);\n return;\n }\n return true;\n};\nconst makeNotification = (notification) =&gt; {\n new Notification(notification.title, notification);\n};\nasync function main() {\n if (!canNotify()) {\n return;\n }\n const notifications = new Notifications();\n notifications.add(makeNotification);\n findReviews(notifications);\n}\n\nmain()\n</code></pre>\n\n<p>I'm unsure about the usefulness of the <code>Notifications</code> class. It makes sense if you're expecting to add multiple separate observers, but it sounds like you may only want to notify the user <em>once</em>, using the most preferred method available (whether that's a <code>Notification</code>, an <code>alert</code>, a <code>SpeechSynthesisUtterance</code> or sound, etc). In such a case, rather than having a <code>Notifications</code> and an array of observers, consider making a function that looks at permissions/userscript settings and returns a function that calls the right method.</p>\n\n<pre><code>const makeNotifier = async () =&gt; {\n if (canNotify()) {\n return notification =&gt; new Notification(notification.title, notification);\n } else if (preferAlerts) {\n return notification =&gt; alert(notification.title);\n }\n // etc\n};\nconst notifier = await makeNotifier();\n// pass around notifier\n</code></pre>\n\n<p>Cookies are meant for saving settings associated with a user which get sent to the server with every request. Here, since you're just trying to persist data across pageloads, it would be more appropriate to use <a href=\"https://developer.mozilla.org/en/docs/Web/API/Window/localStorage\" rel=\"noreferrer\"><code>localStorage</code></a>, which doesn't get sent to the server, is much easier to interface with, and has a much larger storage limit.</p>\n\n<p>Remember to <a href=\"https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75\" rel=\"noreferrer\">always use <code>const</code> whenever possible</a>. When you use <code>let</code>, you're sending the message to other readers of the code: \"I may reassign this variable in the future, so watch out, don't take its current value for granted!\" Code is generally easier to read when you don't have to worry about reassignment.</p>\n\n<p>Rather than calling <code>review.title()</code> and <code>review.amount()</code> multiple times, you can store their values into variables (which can make things clearer when you want to distinguish the current values from the previous values).</p>\n\n<pre><code>function findReviews(notifications) {\n // Find and notify the user about new reviews.\n //\n // 1. This is provided a fully initialized Notifications object.\n // 2. Take data from localStorage to allow comparisions with the previous\n // page load. This is important as otherwise the code would\n // continuously notify users of all active reviews.\n // 3. For each review on the page:\n // 1. Verify if there are new reviews - comparing with the stored value.\n // 2. Notify the user if there is a new review.\n // 3. Update the cookie to the new value.\n // 4. Save the new review counts in localStorage\n // 5. Reload the page.\n const storedReviewCounts = JSON.parse(localStorage.reviewNotifications || '{}');\n for (const review of Review.findAll()) {\n const prevAmount = storedReviewCounts[review.title()] || 0;\n const reviewQueueName = review.title();\n const currentAmount = review.amount();\n console.log(reviewQueueName, prevAmount, \"-&gt;\", currentAmount, prevAmount &lt; currentAmount);\n if (prevAmount &lt; currentAmount) {\n notifications.notify({\n \"title\": currentAmount + \" reviews in \" + reviewQueueName,\n \"icon\": \"https://cdn.sstatic.net/Sites/codereview/img/apple-touch-icon.png?v=0a72875519a4\",\n })\n }\n storedReviewCounts[reviewQueueName] = currentAmount;\n }\n localStorage.reviewNotifications = JSON.stringify(storedReviewCounts);\n setTimeout(function () { window.location.reload(); }, 60 * 1000);\n}\n</code></pre>\n\n<p>In your <code>Review</code> class, rather than using hard-to-read chained <code>.children</code>, you can use <code>querySelector</code> to select the right descendant - or, use a selector to select a child, then navigate upwards to an ancestor with <code>.closest</code>. Look at the elements you want to target in your browser tools, and figure out a <a href=\"https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors\" rel=\"noreferrer\">CSS selector</a> which can target it. Using the <code>.closest</code> route, you can get to an anchor like <code>&lt;a href=\"/review/close\"&gt;Close Votes&lt;/a&gt;</code> easily, at which point it's probably easier to just extract the information directly and put it into an object than to navigate to a parent <code>object</code> and later search through it to find the child again.</p>\n\n<p>The selector</p>\n\n<pre><code>#content .fs-subheading [href^=\"/review/\"]\n</code></pre>\n\n<p>will select elements:</p>\n\n<ul>\n<li>inside the element with the <code>content</code></li>\n<li>inside an element with a class name of <code>fs-subheading</code></li>\n<li>which have an <code>href</code> attribute which starts with <code>/review/</code></li>\n</ul>\n\n<p>From here, you can get the queue name. Then navigate to the whole right cell container, so you can get to the left cell, so you can get to the review count inside the left cell.</p>\n\n<pre><code>function getReviews() {\n return [...$('#content .fs-subheading [href^=\"/review/\"]')].map((reviewAnchor) =&gt; {\n const reviewQueueName = reviewAnchor.textContent;\n const rightCell = reviewAnchor.closest('.grid');\n const leftCell = rightCell.previousElementSibling;\n const count = Number(leftCell.querySelector('[title]').title.replace(/,/g, ''));\n return { reviewQueueName, count };\n });\n}\n</code></pre>\n\n<p>This'll return an array of objects with a <code>reviewQueueName</code> and <code>count</code> properties.</p>\n\n<p>It's probably not an issue for most users now that the bug has been fixed, but I habitually put <code>window</code> before <code>setTimeout</code> to avoid a <a href=\"https://stackoverflow.com/a/56484395\">bug certain versions of Chrome had</a> when running userscripts with <code>setTimeout</code>.</p>\n\n<p>Putting all these ideas together, and you get:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>throw new Error('Using Stack Snippet to hide large amount of repeated code. This is not runnable.');\n\nfunction getReviews() {\n return [...$('#content .fs-subheading [href^=\"/review/\"]')].map((reviewAnchor) =&gt; {\n const reviewQueueName = reviewAnchor.textContent;\n const rightCell = reviewAnchor.closest('.grid');\n const leftCell = rightCell.previousElementSibling;\n const count = Number(leftCell.querySelector('[title]').title.replace(/,/g, ''));\n return { reviewQueueName, count };\n });\n}\n\nfunction notifyOnNewReviews(notifier) {\n // Find and notify the user about new reviews.\n //\n // 1. This is provided a notifier function.\n // 2. Take data from localStorage to allow comparisions with the previous\n // page load. This is important as otherwise the code would\n // continuously notify users of all active reviews.\n // 3. For each review on the page:\n // 1. Verify if there are new reviews - comparing with the stored value.\n // 2. Notify the user if there is a new review.\n // 3. Update the localStorage object to the new value.\n // 4. Save the new review counts in localStorage\n // 5. Reload the page.\n const storedReviewCounts = JSON.parse(localStorage.reviewNotifications || '{}');\n for (const review of getReviews()) {\n const { reviewQueueName, count: currentAmount } = review;\n const prevAmount = storedReviewCounts[reviewQueueName] || 0;\n console.log(reviewQueueName, prevAmount, \"-&gt;\", currentAmount, prevAmount &lt; currentAmount);\n if (prevAmount &lt; currentAmount) {\n notifier({\n title: currentAmount + \" reviews in \" + reviewQueueName,\n icon: \"https://cdn.sstatic.net/Sites/codereview/img/apple-touch-icon.png?v=0a72875519a4\",\n })\n }\n storedReviewCounts[reviewQueueName] = currentAmount;\n }\n localStorage.reviewNotifications = JSON.stringify(storedReviewCounts);\n window.setTimeout(function () { window.location.reload(); }, 60 * 1000);\n}\n\nasync function canNotify() {\n if (Notification.permission === 'default') {\n await Notification.requestPermission();\n }\n const { permission } = Notification;\n if (permission !== 'granted') {\n console.error(`Notifications not permitted. Permission status: ${permission}`);\n return;\n }\n return true;\n}\n\nasync function makeNotifier () {\n const preferAlerts = true; // or whatever logic you want\n if (await canNotify()) {\n return notification =&gt; new Notification(notification.title, notification);\n } else if (preferAlerts) {\n return notification =&gt; alert(notification.title);\n }\n // etc\n}\n\nasync function main() {\n const notifier = await makeNotifier();\n notifyOnNewReviews(notifier);\n}\nmain();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Works on Stack Overflow. It <em>probably</em> works here as well, but since I can't review yet, I'm not 100% sure.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T03:16:35.820", "Id": "471103", "Score": "0", "body": "1. Yeah, I can see that.\n2. What class are you talking about?\n3. Not all instances of an anti-pattern are bad.\n4. Exceptions are exceptional is a cargo cult lie.\n3 + 4. IMO together, here, they complement.\n5. No, I want to add inbox notification as a second backend.\n6. Thank you.\n7. Ah yes.\n8. Disagree, `review.title()` vs `currentTitle` are the same.\n9. Interesting, thanks will look into.\n`setTimeout`. What a weird bug.\n11. I originally tested on SO 'cause they get more review items.\n -- Thank you for the review, albeit lots comes down to philosophical differences." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T03:33:23.410", "Id": "471104", "Score": "0", "body": "2. The class I was referring to there was the `PushNotification` - it doesn't use any instance properties. 8. Yep, the retrieved text is always the same, which means that there's no need to retrieve the text over and over again. You can if you like, but I don't think it's elegant (and it [can be expensive](https://www.phpied.com/dom-access-optimization/), it's good to minimize DOM access)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T02:41:26.310", "Id": "240180", "ParentId": "240176", "Score": "12" } }, { "body": "<h2>Usability</h2>\n\n<p>I ran the script on <a href=\"https://stackoverflow.com/review\">the SO review dashboard</a> to see how it would perform with various numbers. The biggest thing I noticed was that it didn't properly handle numbers greater than 999 since those are formatted in <em><code>x.y</code></em><code>k</code> format. To properly handle those you may have to look for such a format and strip off any multipliers.</p>\n\n<p><a href=\"https://i.stack.imgur.com/QuYpI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QuYpI.png\" alt=\"SO screenshot with NaN\"></a> </p>\n\n<h2>Review</h2>\n\n<p>In addition to the points already addressed by CertainPerformance, I noticed a couple other things that could be simplfied:</p>\n\n<blockquote>\n<pre><code>setTimeout(function(){ window.location.reload(); }, 60 * 1000);\n</code></pre>\n</blockquote>\n\n<p>There isn't any need to wrap the reload call in an anonymous/lambda function/closure, since it is a function:</p>\n\n<pre><code>setTimeout(window.location.reload, 60 * 1000);\n</code></pre>\n\n<p>If you had a need to set the <code>this</code> context for such a call, then use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind\" rel=\"nofollow noreferrer\"><code>Function.bind()</code></a></p>\n\n<hr>\n\n<p>When using an arrow function expression with a single parameter - e.g. </p>\n\n<blockquote>\n<pre><code>(status) =&gt; console.log(\"Can't notify status code\", status),\n</code></pre>\n</blockquote>\n\n<p>The parameters don't need to be wrapped in parentheses:</p>\n\n<pre><code>status =&gt; console.log(\"Can't notify status code\", status),\n</code></pre>\n\n<hr>\n\n<p>It is wise to use <code>const</code> for all variables until you determine that re-assignment is necessary- then use <code>let</code>. This helps avoid accidental re-assignment. </p>\n\n<p>For example, in <code>split_once()</code> there is an assignment for <code>index</code>:</p>\n\n<blockquote>\n<pre><code>let index = value.indexOf(sep);\n</code></pre>\n</blockquote>\n\n<p>But that value never gets re-assigned within the function.</p>\n\n<p>There are also three variables in <code>findReviews()</code> that don't appear to be re-assigned that can be declared with <code>const</code> - i.e. <code>cookies</code>, <code>prev</code> and <code>prevAmount</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T13:56:27.780", "Id": "240278", "ParentId": "240176", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T23:40:17.220", "Id": "240176", "Score": "9", "Tags": [ "javascript", "ecmascript-6", "promise", "stackexchange", "userscript" ], "Title": "Stack Exchange rev​iew queue notifications" }
240176
<p>I am writing a code that takes two numbers N and M and finds the greatest result of A mod M for all the numbers of A in the range 1,2,3,...,N-1,N. </p> <p>1 ≤ N,M ≤ 10^9</p> <p>My code is:</p> <pre><code>public static void main(String[] args) throws IOException { long n=readLong(), m=readLong(), a=Integer.MIN_VALUE; for(int i=1; i&lt;=n; i++){ a=Math.max(i%m, a); } System.out.println(a); } </code></pre> <p>My code works for small ranges like in the test case below:</p> <p>Input`</p> <pre><code>10 5 </code></pre> <p>Output</p> <pre><code>4 </code></pre> <p>However, it is still not efficient enough (TLE). Is there any way to make looping through all the numbers faster?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T00:14:08.897", "Id": "471097", "Score": "2", "body": "Isn't that just `min(N, M-1)`?" } ]
[ { "body": "<p>You don't need to loop. Lets look at what <span class=\"math-container\">\\$0 \\le i \\le 10\\$</span> and <span class=\"math-container\">\\$i\\ \\%\\ 5\\$</span> results in.</p>\n\n<p><span class=\"math-container\">$$\n\\begin{array}{l|l l l l l}\ni &amp; 0 &amp; 1 &amp; 2 &amp; 3 &amp; 4 &amp; 5 &amp; 6 &amp; 7 &amp; 8 &amp; 9 &amp; 10\\\\\ni\\ \\%\\ 5 &amp; 0 &amp; 1 &amp; 2 &amp; 3 &amp; 4 &amp; 0 &amp; 1 &amp; 2 &amp; 3 &amp; 4 &amp; 0\\\\\n\\end{array}\n$$</span></p>\n\n<p>From here we can see that if <span class=\"math-container\">\\$n \\ge m\\$</span> the answer is <span class=\"math-container\">\\$m - 1\\$</span>. If this is not the case then the answer is <span class=\"math-container\">\\$n\\$</span>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T00:15:21.563", "Id": "240178", "ParentId": "240177", "Score": "5" } } ]
{ "AcceptedAnswerId": "240178", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-08T23:53:41.143", "Id": "240177", "Score": "-2", "Tags": [ "java" ], "Title": "Efficient way to find the greatest result of A mod M in a range of numbers" }
240177
<p>Python script that can downloads public and private profiles images and videos, like Gallery with photos or videos. It saves the data in the folder.</p> <p>How it works:</p> <ul> <li><p>Log in in instragram using selenium and navigate to the profile</p></li> <li><p>Checking the availability of Instagram profile if it's private or existing</p></li> <li><p>Creates a folder with the name of your choice</p></li> <li><p>Gathering urls from images and videos</p></li> <li><p>Using threads and multiprocessing improving the execution speed</p></li> </ul> <p>My code:</p> <pre><code>from pathlib import Path import requests import time from selenium import webdriver from selenium.common.exceptions import NoSuchElementException, TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from multiprocessing.dummy import Pool import urllib.parse from concurrent.futures import ThreadPoolExecutor from typing import * import argparse class PrivateException(Exception): pass class InstagramPV: def __init__(self, username: str, password: str, folder: Path, profile_name: str): """ :param username: Username or E-mail for Log-in in Instagram :param password: Password for Log-in in Instagram :param folder: Folder name that will save the posts :param profile_name: The profile name that will search """ self.username = username self.password = password self.folder = folder self.http_base = requests.Session() self.profile_name = profile_name self.links: List[str] = [] self.pictures: List[str] = [] self.videos: List[str] = [] self.url: str = 'https://www.instagram.com/{name}/' self.posts: int = 0 self.MAX_WORKERS: int = 8 self.N_PROCESSES: int = 8 self.driver = webdriver.Chrome() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.http_base.close() self.driver.close() def check_availability(self) -&gt; None: """ Checking Status code, Taking number of posts, Privacy and followed by viewer Raise Error if the Profile is private and not following by viewer :return: None """ search = self.http_base.get(self.url.format(name=self.profile_name), params={'__a': 1}) search.raise_for_status() load_and_check = search.json() self.posts = load_and_check.get('graphql').get('user').get('edge_owner_to_timeline_media').get('count') privacy = load_and_check.get('graphql').get('user').get('is_private') followed_by_viewer = load_and_check.get('graphql').get('user').get('followed_by_viewer') if privacy and not followed_by_viewer: raise PrivateException('[!] Account is private') def create_folder(self) -&gt; None: """Create the folder name""" self.folder.mkdir(exist_ok=True) def login(self) -&gt; None: """Login To Instagram""" self.driver.get('https://www.instagram.com/accounts/login') WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'form'))) self.driver.find_element_by_name('username').send_keys(self.username) self.driver.find_element_by_name('password').send_keys(self.password) submit = self.driver.find_element_by_tag_name('form') submit.submit() """Check For Invalid Credentials""" try: var_error = WebDriverWait(self.driver, 4).until(EC.presence_of_element_located((By.CLASS_NAME, 'eiCW-'))) raise ValueError(var_error.text) except TimeoutException: pass try: """Close Notifications""" notifications = WebDriverWait(self.driver, 20).until( EC.presence_of_element_located((By.XPATH, '//button[text()="Not Now"]'))) notifications.click() except NoSuchElementException: pass """Taking cookies""" cookies = { cookie['name']: cookie['value'] for cookie in self.driver.get_cookies() } self.http_base.cookies.update(cookies) """Check for availability""" self.check_availability() self.driver.get(self.url.format(name=self.profile_name)) self.scroll_down() def posts_urls(self) -&gt; None: """Taking the URLs from posts and appending in self.links""" elements = self.driver.find_elements_by_xpath('//a[@href]') for elem in elements: urls = elem.get_attribute('href') if 'p' in urls.split('/'): if urls not in self.links: self.links.append(urls) def scroll_down(self) -&gt; None: """Scrolling down the page and taking the URLs""" last_height = self.driver.execute_script('return document.body.scrollHeight') while True: self.driver.execute_script('window.scrollTo(0, document.body.scrollHeight);') time.sleep(1) self.posts_urls() time.sleep(1) new_height = self.driver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height self.submit_links() def submit_links(self) -&gt; None: """Gathering Images and Videos and pass to function &lt;fetch_url&gt; Using ThreadPoolExecutor""" self.create_folder() print('[!] Ready for video - images'.title()) print(f'[*] extracting {len(self.links)} posts , please wait...'.title()) new_links = (urllib.parse.urljoin(link, '?__a=1') for link in self.links) with ThreadPoolExecutor(max_workers=self.MAX_WORKERS) as executor: for link in new_links: executor.submit(self.fetch_url, link) def get_fields(self, nodes: Dict, *keys) -&gt; Any: """ :param nodes: The json data from the link using only the first two keys 'graphql' and 'shortcode_media' :param keys: Keys that will be add to the nodes and will have the results of 'type' or 'URL' :return: The value of the key &lt;fields&gt; """ fields = nodes['graphql']['shortcode_media'] for key in keys: fields = fields[key] return fields def fetch_url(self, url: str) -&gt; None: """ This function extracts images and videos :param url: Taking the url :return None """ logging_page_id = self.http_base.get(url.split()[0]).json() if self.get_fields(logging_page_id, '__typename') == 'GraphImage': image_url = self.get_fields(logging_page_id, 'display_url') self.pictures.append(image_url) elif self.get_fields(logging_page_id, '__typename') == 'GraphVideo': video_url = self.get_fields(logging_page_id, 'video_url') self.videos.append(video_url) elif self.get_fields(logging_page_id, '__typename') == 'GraphSidecar': for sidecar in self.get_fields(logging_page_id, 'edge_sidecar_to_children', 'edges'): if sidecar['node']['__typename'] == 'GraphImage': image_url = sidecar['node']['display_url'] self.pictures.append(image_url) else: video_url = sidecar['node']['video_url'] self.videos.append(video_url) else: print(f'Warning {url}: has unknown type of {self.get_fields(logging_page_id,"__typename")}') def download_video(self, new_videos: Tuple[int, str]) -&gt; None: """ Saving the video content :param new_videos: Tuple[int,str] :return: None """ number, link = new_videos with open(self.folder / f'Video{number}.mp4', 'wb') as f: content_of_video = self.http_base.get(link).content f.write(content_of_video) def images_download(self, new_pictures: Tuple[int, str]) -&gt; None: """ Saving the picture content :param new_pictures: Tuple[int, str] :return: None """ number, link = new_pictures with open(self.folder / f'Image{number}.jpg', 'wb') as f: content_of_picture = self.http_base.get(link).content f.write(content_of_picture) def downloading_video_images(self) -&gt; None: """Using multiprocessing for Saving Images and Videos""" print('[*] ready for saving images and videos!'.title()) picture_data = enumerate(self.pictures) video_data = enumerate(self.videos) pool = Pool(self.N_PROCESSES) pool.map(self.images_download, picture_data) pool.map(self.download_video, video_data) print('[+] Done') def main(): parser = argparse.ArgumentParser() parser.add_argument('-U', '--username', help='Username or your email of your account', action='store', required=True) parser.add_argument('-P', '--password', help='Password of your account', action='store', required=True) parser.add_argument('-F', '--filename', help='Filename for storing data', action='store', required=True) parser.add_argument('-T', '--target', help='Profile name to search', action='store', required=True) args = parser.parse_args() with InstagramPV(args.username, args.password, Path(args.filename), args.target) as pv: pv.login() pv.downloading_video_images() if __name__ == '__main__': main() </code></pre> <p>Usage: <code>myfile.py -U myemail@hotmail.com -P mypassword -F Mynamefile -T stackoverjoke</code></p> <p>Changes:</p> <p>1) Changed the function of <code>scroll_down</code></p> <p>2) Added <code>get_fields</code></p> <p>My previous comparative review tag:<a href="https://codereview.stackexchange.com/questions/239940/instagram-scraping-posts-using-selenium">Instagram Scraping Posts Using Selenium</a></p>
[]
[ { "body": "<h2>Class constants</h2>\n\n<p>These:</p>\n\n<pre><code> self.MAX_WORKERS: int = 8\n self.N_PROCESSES: int = 8\n</code></pre>\n\n<p>should not be set as instance members; they should be static members, which is done by setting them in the class outside of function scope; i.e.</p>\n\n<pre><code>class InstagramPV:\n MAX_WORKERS: int = 8\n N_PROCESSES: int = 8\n</code></pre>\n\n<h2>Nested <code>if</code></h2>\n\n<pre><code> if 'p' in urls.split('/'):\n if urls not in self.links:\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>if urls not in self.links and 'p' in urls.split('/'):\n</code></pre>\n\n<h2>Direct import</h2>\n\n<p><code>urllib.parse.urljoin</code> could use a <code>from urllib.parse import urljoin</code>.</p>\n\n<h2>URL passing</h2>\n\n<p>You pass this into <code>submit</code> - <code>urllib.parse.urljoin(link, '?__a=1')</code> - and then fetch <code>url.split()[0]</code>. Why call <code>split</code> at all? Does the original string actually have spaces in it? If so, that should be taken care of before it's passed into <code>submit</code>. Also, don't call <code>urljoin</code> for a query parameter - instead, pass that QP into <code>get</code>'s <code>params</code> argument.</p>\n\n<h2>Streamed downloads</h2>\n\n<p>Regarding this:</p>\n\n<pre><code> with open(self.folder / f'Image{number}.jpg', 'wb') as f:\n content_of_picture = self.http_base.get(link).content\n f.write(content_of_picture)\n</code></pre>\n\n<p>The problem with using <code>content</code> is that it loads everything into memory before being able to write it to a file. Instead, pass <code>stream=True</code> to <code>get</code>, and then pass <code>response.raw</code> to <code>shutil.copyfileobj</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:34:41.667", "Id": "471512", "Score": "0", "body": "May i post my new question or i have to do more changes? Thanks for everything!!! I really mean it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:35:58.143", "Id": "471513", "Score": "1", "body": "You're welcome! Go for it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T16:28:13.607", "Id": "471526", "Score": "0", "body": "my new [question](https://codereview.stackexchange.com/questions/240401/scraping-instagram-download-posts-photos-videos)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T03:37:34.893", "Id": "240183", "ParentId": "240182", "Score": "1" } } ]
{ "AcceptedAnswerId": "240183", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T03:07:52.577", "Id": "240182", "Score": "2", "Tags": [ "python", "python-3.x", "web-scraping", "selenium", "instagram" ], "Title": "Download pictures (or videos) from Instagram using Selenium" }
240182
<p>I've just finished one of my first projects with a GUI using PyQt5 and I recreated Mastermind, the board game.</p> <p>The game is played by inputting 4 numbers and getting a return of how many of the numbers are in the code but in the wrong spot and how many numbers are correct (a random 4 digit combo between 0 and 9 inclusive is used). The GUI has 5 user interactives including 4 spinbox inputs limited 0-9 and a submit button. </p> <p>The results are shown below the submit button as well as saved in a history box which contains the guess number, the guess, and the result of the guess (how many correct or in the wrong place). The player has 15 guesses. If the code is found the player wins, if not they lose.</p> <p>This was a great project to practice list comprehension as there are many numbered variables and tests. Initially, the code was 450 lines long due to bad variable management and inefficient tests, I have been able to get it down to 120!</p> <p>Thanks for any feedback. I'm sure it will all be useful as I don't know much!</p> <pre><code>from PyQt5 import QtCore, QtGui, QtWidgets import random class Ui_MainWindow(object): def __init__(self): self.guessnum = -1 self.submit_clicks = 0 self.ans = random.sample(range(0, 10), 4) print(self.ans) def setupUi(self, MainWindow): MainWindow.resize(766, 603) self.centralwidget = QtWidgets.QWidget(MainWindow) self.Title = QtWidgets.QLabel(self.centralwidget) self.Title.setGeometry(QtCore.QRect(260, 20, 251, 81)) font = QtGui.QFont() font.setFamily("MS UI Gothic") font.setPointSize(28) self.Title.setFont(font) self.groupBox = QtWidgets.QGroupBox(self.centralwidget) self.groupBox.setGeometry(QtCore.QRect(50, 130, 291, 345)) self.Guess_label = [QtWidgets.QLabel(self.groupBox) for num in range(15)] for x in self.Guess_label: i = 30 + (21 * self.Guess_label.index(x)) x.setGeometry(QtCore.QRect(20, i, 55, 16)) self.Guessinpt = [QtWidgets.QLabel(self.groupBox) for num in range(15)] for x in self.Guessinpt: i = 30 + (21 * self.Guessinpt.index(x)) x.setGeometry(QtCore.QRect(100, i, 61, 16)) self.Results_guess = [QtWidgets.QLabel(self.groupBox) for num in range(15)] for x in self.Results_guess: i = 30 + (21 * self.Results_guess.index(x)) x.setGeometry(QtCore.QRect(190, i, 55, 16)) self.input = [QtWidgets.QSpinBox(self.centralwidget) for num in range(4)] for x in self.input: i = 380 + (90 * self.input.index(x)) x.setGeometry(QtCore.QRect(i, 250, 71, 41)) for x in self.input: x.setMaximum(10) self.Result_Output = QtWidgets.QLabel(self.centralwidget) self.Result_Output.setGeometry(QtCore.QRect(420, 430, 131, 51)) self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(450, 330, 201, 51)) self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(370, 130, 391, 41)) font = QtGui.QFont() font.setPointSize(12) self.label.setFont(font) self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(390, 170, 341, 21)) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 766, 26)) MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) MainWindow.setStatusBar(self.statusbar) self.actionNew_Game = QtWidgets.QAction(MainWindow) self.pushButton.clicked.connect(self.Test_Input) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.Title.setText(_translate("MainWindow", "Mastermind!")) self.groupBox.setTitle(_translate("MainWindow", "Guess History")) for x in self.Guess_label: x.setText((_translate('MainWindow', 'Guess ' + str(self.Guess_label.index(x) + 1)))) self.Result_Output.setText(_translate("MainWindow", "Result")) self.pushButton.setText(_translate("MainWindow", "Submit!")) self.label.setText(_translate("MainWindow", "A random 4 digit code has been created! ")) self.label_2.setText(_translate("MainWindow", "Put 4 numbers in the boxes bellow and read the result!! ")) self.actionNew_Game.setText(_translate("MainWindow", "New Game")) self.actionNew_Game.setStatusTip(_translate("MainWindow", "Start a new game?")) self.actionNew_Game.setShortcut(_translate("MainWindow", "Ctrl+N")) def Test_Input(self): self.numcorrect = 0 self.poscorrect = 0 self.user_input = [int(self.input[0].value()), int(self.input[1].value()), int(self.input[2].value()), int(self.input[3].value())] for x in self.input: if int(x.value()) == self.ans[self.input.index(x)]: self.poscorrect += 1 elif int(x.value()) in self.ans and x not in self.input: self.numcorrect += 1 self.guessnum += 1 self.Result_Output.setText( str(self.numcorrect) + ' Numbers are in the code but in the wrong place!' + '\n' + str (self.poscorrect) + ' Numbers are correct!') self.Result_Output.adjustSize() if self.guessnum == 14: self.Title.setText('You Lose!') self.Result_Output.setText('You Lose') if self.poscorrect == 4: self.Result_Output.setText('You Win') self.Title.setText('You Win') self.Results_guess[self.guessnum].setText(str(self.numcorrect) + ' #|' + str(self.poscorrect) + ' Pos') self.Results_guess[self.guessnum].adjustSize() self.Guessinpt[self.guessnum].setText(str(self.user_input)) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) </code></pre>
[]
[ { "body": "<h2>Don't inherit from object</h2>\n\n<p>Have a read through <a href=\"https://stackoverflow.com/questions/4015417/python-class-inherits-object\">https://stackoverflow.com/questions/4015417/python-class-inherits-object</a> . I dearly hope that you're in Python 3, in which case - just <code>class UiMainWindow:</code>.</p>\n\n<h2>Namespaces</h2>\n\n<p>At a guess, you added a <code>Ui_</code> prefix to your class to maybe plan other UI classes or functions to also take that prefix? If so, the nicer way to do this is make a submodule of your program called <code>ui</code>, then refer to your class via <code>ui.MainWindow</code>.</p>\n\n<h2>Names</h2>\n\n<p>Use lower_snake_case for your member variables and functions, i.e.</p>\n\n<ul>\n<li><code>setup_ui</code></li>\n<li><code>self.title</code></li>\n<li><code>self.group_box</code></li>\n<li><code>self.guess_label</code></li>\n</ul>\n\n<p>etc.</p>\n\n<h2>Separation of concerns</h2>\n\n<p>Your <code>MainWindow</code> isn't just rendering a main window. It's also running the business logic for the entire application. You should tease these two apart - the window class should only be doing display, rendering and control interactions, and a separate game class should track stuff like</p>\n\n<pre><code> self.guessnum = -1\n self.ans = random.sample(range(0, 10), 4)\n</code></pre>\n\n<p>and</p>\n\n<pre><code>def Test_Input(self):\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T13:38:15.843", "Id": "240205", "ParentId": "240185", "Score": "0" } }, { "body": "<p><strong>Never</strong>, <strong>NEVER</strong> edit the files created with pyuic, \nuse them as modules instead. Read more on using Designer <a href=\"https://www.riverbankcomputing.com/static/Docs/PyQt5/designer.html\" rel=\"nofollow noreferrer\">https://www.riverbankcomputing.com/static/Docs/PyQt5/designer.html</a> .</p>\n\n<p>You do 5 <code>for</code> loops, although all this is done in a single loop.</p>\n\n<p>You have a problem with the names of variables and methods, do not give them names with a capital letter.</p>\n\n<pre><code>import sys\nimport random\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.resize(766, 603)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.Title = QtWidgets.QLabel(self.centralwidget)\n self.Title.setGeometry(QtCore.QRect(260, 20, 251, 81))\n font = QtGui.QFont()\n font.setFamily(\"MS UI Gothic\")\n font.setPointSize(28)\n self.Title.setFont(font)\n self.groupBox = QtWidgets.QGroupBox(self.centralwidget)\n self.groupBox.setGeometry(QtCore.QRect(50, 130, 291, 345))\n self.Result_Output = QtWidgets.QLabel(self.centralwidget)\n self.Result_Output.setGeometry(QtCore.QRect(420, 430, 131, 51))\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(450, 330, 201, 51))\n self.label = QtWidgets.QLabel(self.centralwidget)\n self.label.setGeometry(QtCore.QRect(370, 130, 391, 41))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.label.setFont(font)\n self.label_2 = QtWidgets.QLabel(self.centralwidget)\n self.label_2.setGeometry(QtCore.QRect(390, 170, 341, 21))\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 766, 26))\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n MainWindow.setStatusBar(self.statusbar)\n self.actionNew_Game = QtWidgets.QAction(MainWindow)\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n self.Title.setText(_translate(\"MainWindow\", \"Mastermind!\"))\n self.groupBox.setTitle(_translate(\"MainWindow\", \"Guess History\"))\n self.Result_Output.setText(_translate(\"MainWindow\", \"Result\"))\n self.pushButton.setText(_translate(\"MainWindow\", \"Submit!\"))\n self.label.setText(_translate(\"MainWindow\", \"A random 4 digit code has been created! \"))\n self.label_2.setText(_translate(\"MainWindow\", \"Put 4 numbers in the boxes bellow and read the result!! \"))\n self.actionNew_Game.setText(_translate(\"MainWindow\", \"New Game\"))\n self.actionNew_Game.setStatusTip(_translate(\"MainWindow\", \"Start a new game?\"))\n self.actionNew_Game.setShortcut(_translate(\"MainWindow\", \"Ctrl+N\"))\n\n\nclass MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):\n def __init__(self, parent=None):\n super(MainWindow, self).__init__(parent)\n self.setupUi(self) \n self.pushButton.clicked.connect(self.test_Input)\n\n self.guessnum = -1\n self.submit_clicks = 0\n self.ans = random.sample(range(0, 10), 4)\n print(self.ans)\n\n self.guessinpt, self.results_guess, self.input = [], [], [] # +++\n for num in range(15): # +++\n QtWidgets.QLabel(\n f'Guess {num+1: &gt;2}', \n self.groupBox,\n geometry=QtCore.QRect(20, 30 + (21 * int(f'{num}')), 55, 16) \n )\n self.guessinpt.append(\n QtWidgets.QLabel(\n self.groupBox,\n geometry=QtCore.QRect(100, 30 + (21 * int(f'{num}')), 61, 16)\n )\n )\n self.results_guess.append(\n QtWidgets.QLabel(\n self.groupBox,\n geometry=QtCore.QRect(190, 30 + (21 * int(f'{num}')), 55, 16)\n )\n ) \n if num &lt; 4:\n self.input.append(\n QtWidgets.QSpinBox(\n self.centralwidget,\n geometry=QtCore.QRect(380 + (90 * int(f'{num}')), 250, 71, 41),\n maximum=9 # 9 !!! \n )\n ) \n\n def test_Input(self):\n self.numcorrect = 0\n self.poscorrect = 0\n self.user_input = [\n int(self.input[0].value()), \n int(self.input[1].value()), \n int(self.input[2].value()),\n int(self.input[3].value())\n ]\n for x in self.input:\n if int(x.value()) == self.ans[self.input.index(x)]:\n self.poscorrect += 1\n elif int(x.value()) in self.ans and x not in self.input:\n self.numcorrect += 1\n\n self.guessnum += 1\n self.Result_Output.setText(\n str(self.numcorrect) + ' Numbers are in the code but in the wrong place!' + '\\n' + str\n (self.poscorrect) + ' Numbers are correct!')\n self.Result_Output.adjustSize()\n\n if self.guessnum &gt;= 15: # 14\n self.Title.setText('You Lose!')\n self.Result_Output.setText('You Lose')\n return # +++\n\n if self.poscorrect == 4:\n self.Result_Output.setText('You Win')\n self.Title.setText('You Win')\n\n self.results_guess[self.guessnum].setText(str(self.numcorrect) + ' #|' + str(self.poscorrect) + ' Pos')\n self.results_guess[self.guessnum].adjustSize()\n self.guessinpt[self.guessnum].setText(str(self.user_input))\n\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n app.setFont(QtGui.QFont(\"Times\", 8, QtGui.QFont.Bold))\n window = MainWindow()\n window.show()\n sys.exit(app.exec_())\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/KCUyj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KCUyj.png\" alt=\"enter image description here\"></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T18:34:50.517", "Id": "240220", "ParentId": "240185", "Score": "0" } } ]
{ "AcceptedAnswerId": "240220", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T04:49:08.090", "Id": "240185", "Score": "3", "Tags": [ "python", "beginner", "pyqt" ], "Title": "Mastermind game" }
240185
<p>I wondering if anyone could give me feedback on whether or not this is a secure way to implement AES/RSA hybrid encryption and signatures in python 3 with the PyCryptodome module.</p> <p>All of the encoding and to/from hex format is just there because that's the format I intend to transfer it in.</p> <pre><code>"""Hybrid AES/RSA encryption, integrity, and repudiation proof of concept. Requires the PyCryptodome module but is imported as Crypto""" from hashlib import sha512 from Crypto.Cipher import PKCS1_OAEP from Crypto.Cipher import AES from Crypto.PublicKey import RSA from Crypto.Random import get_random_bytes def generate_keys(): """ Generates the rsa key pair and returns them. In actual usage private key is exported to .pem secured with a passphrase""" while True: privatekey = RSA.generate(2048) publickey = privatekey.publickey() return privatekey, publickey def encrypt_msg(msg_body, publickey, privatekey): """Generates the session key, then creates the nonce and cipher. encrypts the message body with AES 256. encrypts the session key with RSA 2048 returns the cipher text, tag, nonce, and the encrypted session key in hex format Hashes clear text message and creates signature""" session_key = get_random_bytes(32) aes_cipher = AES.new(session_key, AES.MODE_EAX) nonce = aes_cipher.nonce aes_cipher_text, tag = aes_cipher.encrypt_and_digest(msg_body) rsa_cipher = PKCS1_OAEP.new(publickey) enc_session_key = rsa_cipher.encrypt(session_key) msg_hash = int.from_bytes(sha512(msg_body).digest(), byteorder='big') signature = pow(msg_hash, privatekey.d, privatekey.n) return aes_cipher_text.hex(), tag.hex(), nonce.hex(), enc_session_key.hex(), signature def decrypt_msg(aes_cipher_text, tag, nonce, enc_session_key, privatekey, publickey, signature): """encrypted session key is encoded and returned from hex Uses private key to decrypt the session key nonce is encoded and returned from hex cipher is created with supplied key, and nonce cipher text is decrypted tag is encoded and returned from hex message is checked for authenticity clear text is returned and authenticity status is returned hashes clear text and compares to signature """ decrypt = PKCS1_OAEP.new(privatekey) session_key = decrypt.decrypt(enc_session_key.encode().fromhex(enc_session_key)) aes_cipher = AES.new(session_key, AES.MODE_EAX, nonce=nonce.encode().fromhex(nonce)) clear_text = aes_cipher.decrypt(aes_cipher_text.encode().fromhex(aes_cipher_text)) try: aes_cipher.verify(tag.encode().fromhex(tag)) authentic = True except ValueError: authentic = False msg_hash = int.from_bytes(sha512(clear_text).digest(), byteorder='big') hashfromsignature = pow(signature, publickey.e, publickey.n) if msg_hash == hashfromsignature: valid = True else: valid = False return clear_text, authentic, valid TEST_MSG = b'this is a short test message.' # Generates and assigns public and private keys # Person A's key pair PRIVATE_KEY, PUBLIC_KEY = generate_keys() # Person B's key pair PRIVATE_KEY_1, PUBLIC_KEY_1 = generate_keys() # Encrypts the message, and creates the tag, nonce and encrypted session key # Note same key pair is used only for testing purposes in implementation # both sides will have own key pairs msg_aes_cipher_text, msg_tag, msg_nonce, encrypted_session_key, signature = encrypt_msg(TEST_MSG, PUBLIC_KEY_1, PRIVATE_KEY) # Decrypts the message with the supplied data and check for authenticity msg_clear_text, authentic_status, valid = decrypt_msg(msg_aes_cipher_text, msg_tag, msg_nonce, encrypted_session_key, PRIVATE_KEY_1, PUBLIC_KEY, signature) if valid: print('Valid signature.') else: print('Invalid signature!') if msg_tag: print('Valid tag.') else: print('Invalid tag.') print(msg_clear_text) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T21:56:30.227", "Id": "471174", "Score": "1", "body": "Please do not update the code in questions to include feedback from answers. This breaks the question and answer nature of the site and makes the answers confusing. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T21:57:56.277", "Id": "471175", "Score": "0", "body": "@greybeard Don't edit code in questions, any and all feedback should go in answers." } ]
[ { "body": "<p>While this question is an off-topic programming question on Crypto.SE, I doubt whether it'll get a better answer on StackOverflow or Code Review.</p>\n\n<p>The part worries me is this: </p>\n\n<pre><code>...\n msg_hash = int.from_bytes(sha512(clear_text).digest(), byteorder='big')\n hashfromsignature = pow(signature, publickey.e, publickey.n)\n if msg_hash == hashfromsignature:\n valid = True\n\n else:\n valid = False\n...\n</code></pre>\n\n<p>You seem to be verifying unpadded textbook RSA signature. You should change this part to using RSA-PSS signature scheme - it's a newer RSA signature scheme in PKCS#1 ver2. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T21:47:24.157", "Id": "471172", "Score": "0", "body": "Updated the signature scheme to PSS based on your recommendations." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T03:18:16.110", "Id": "240191", "ParentId": "240190", "Score": "4" } }, { "body": "<p>Just something for clarify the code</p>\n\n<pre><code>if msg_hash == hashfromsignature:\n valid = True\n\nelse:\n valid = False\n</code></pre>\n\n<p>On an easy statement</p>\n\n<pre><code>valid = msg_hash == hashfromsignature\n</code></pre>\n\n<p>Also this while is not looping, not sure if you want to use a yield here</p>\n\n<pre><code>def generate_keys():\n while True:\n privatekey = RSA.generate(2048)\n publickey = privatekey.publickey()\n\n return privatekey, publickey\n</code></pre>\n\n<p>Could be rewrite as</p>\n\n<pre><code>def generate_keys():\n privatekey = RSA.generate(2048)\n publickey = privatekey.publickey()\n\n return privatekey, publickey\n</code></pre>\n\n<p>Not sure of your intention here with the while but I suspect that you wanted to use a generator function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T12:20:33.443", "Id": "471128", "Score": "0", "body": "The while statement wasn't supposed to be there for this bit of code, in the full project there is a check that works with that while, however I just forgot to remove it when posting this code snippet." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T09:25:17.863", "Id": "240193", "ParentId": "240190", "Score": "2" } } ]
{ "AcceptedAnswerId": "240191", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T02:43:53.973", "Id": "240190", "Score": "1", "Tags": [ "python", "python-3.x", "cryptography", "aes" ], "Title": "Securely implementing AES/RSA hybrid crypto with PyCryptodome" }
240190
<p>Not really an issue I am stuck on (the code works) but I just really don't like some code I wrote, if you're bored in lockdown maybe you might like to help.</p> <p>Context: I am import some data from a spreadsheet, it contains data about retail stores (grocery stores). As the data comes in from the spreadsheet, each row is stored as a StoreData object. Each store has upto five tills (point of sale devices) and I want the StoreData class to be able to return an array of information about each till. Here is the class showing the code relevant to the tills (the class is much bigger).</p> <p>How can I clean up the function getTills()?</p> <pre class="lang-php prettyprint-override"><code> class StoreData { private $spreadsheetData; private $tillModel; private $tillVersion; private $tillOneName; private $tillOneIpAddress; private $tillTwoName; private $tillTwoIpAddress; private $tillThreeName; private $tillThreeIpAddress; private $tillFourName; private $tillFourIpAddress; private $tillFiveName; private $tillFiveIpAddress; public function __construct($spreadsheetData, String $storeStatus) { $this-&gt;spreadsheetData = $spreadsheetData; $this-&gt;setStoreProperties(); } private function setStoreProperties() { $this-&gt;tillModel = $this-&gt;spreadsheetData[17]; $this-&gt;tillVersion = $this-&gt;spreadsheetData[7]; $this-&gt;tillOneName = $this-&gt;spreadsheetData[40]; $this-&gt;tillOneIpAddress = $this-&gt;spreadsheetData[41]; $this-&gt;tillTwoName = $this-&gt;spreadsheetData[42]; $this-&gt;tillTwoIpAddress = $this-&gt;spreadsheetData[43]; $this-&gt;tillThreeName = $this-&gt;spreadsheetData[44]; $this-&gt;tillThreeIpAddress = $this-&gt;spreadsheetData[45]; $this-&gt;tillFourName = $this-&gt;spreadsheetData[46]; $this-&gt;tillFourIpAddress = $this-&gt;spreadsheetData[47]; $this-&gt;tillFiveName = $this-&gt;spreadsheetData[48]; $this-&gt;tillFiveIpAddress = $this-&gt;spreadsheetData[49]; } public function getTills() { $tillList = []; if ($this-&gt;tillOneName !== null) { $tillList[] = [ 'model' =&gt; $this-&gt;tillModel, 'name' =&gt; $this-&gt;tillOneName, 'ip_address' =&gt; $this-&gt;tillOneIpAddress, 'version' =&gt; $this-&gt;tillVersion, ]; } if ($this-&gt;tillTwoName !== null) { $tillList[] = [ 'model' =&gt; $this-&gt;tillModel, 'name' =&gt; $this-&gt;tillTwoName, 'ip_address' =&gt; $this-&gt;tillTwoIpAddress, 'version' =&gt; $this-&gt;tillVersion, ]; } if ($this-&gt;tillThreeName !== null) { $tillList[] = [ 'model' =&gt; $this-&gt;tillModel, 'name' =&gt; $this-&gt;tillThreeName, 'ip_address' =&gt; $this-&gt;tillThreeIpAddress, 'version' =&gt; $this-&gt;tillVersion, ]; } if ($this-&gt;tillFourName !== null) { $tillList[] = [ 'model' =&gt; $this-&gt;tillModel, 'name' =&gt; $this-&gt;tillFourName, 'ip_address' =&gt; $this-&gt;tillFourIpAddress, 'version' =&gt; $this-&gt;tillVersion, ]; } if ($this-&gt;tillFiveName !== null) { $tillList[] = [ 'model' =&gt; $this-&gt;tillModel, 'name' =&gt; $this-&gt;tillFiveName, 'ip_address' =&gt; $this-&gt;tillFiveIpAddress, 'version' =&gt; $this-&gt;tillVersion, ]; } return $tillList; } } </code></pre> <p>For info, this is used to populate an eloquent model on a controller:</p> <pre class="lang-php prettyprint-override"><code> foreach($storeData-&gt;getTills() as $till) { $store-&gt;tills()-&gt;create($till); } </code></pre>
[]
[ { "body": "<p>You might want to create a service that accepts the spreadsheet data as method argument instead.</p>\n\n<p>And maybe the columns could be configured to make it more flexible.</p>\n\n<p>Also no need to do 5 times the same again, instead use a loop.</p>\n\n<pre><code>class SpreadsheetTillsConverter\n{\n private int $modelColumn;\n private int $versionColumn;\n\n /** @var array&lt;int, int&gt; Map nameColumn =&gt; ipAddressColumn */\n private array $columns;\n\n public function __construct(int $modelColumn, int $versionColumn, array $columns)\n {\n $this-&gt;modelColumn = $modelColumn;\n $this-&gt;versionColumn = $versionColumn;\n $this-&gt;columns = $columns;\n }\n\n public function getTills(array $data): array\n {\n if (!isset($data[$this-&gt;modelColumn])) {\n throw new \\InvalidArgumentException('Model column not found.');\n }\n $model = $data[$this-&gt;modelColumn];\n\n if (!isset($data[$this-&gt;versionColumn])) {\n throw new \\InvalidArgumentException('Version column not found.');\n }\n $version = $data[$this-&gt;versionColumn];\n\n $result = [];\n foreach ($this-&gt;columns as $nameColumn =&gt; $ipAddressColumn) {\n if (isset($data[$nameColumn], $data[$ipAddressColumn])) {\n $result[] = [\n 'model' =&gt; $model,\n 'name' =&gt; $data[$nameColumn],\n 'ip_address' =&gt; $data[$ipAddressColumn],\n 'version' =&gt; $version,\n ];\n }\n }\n return $result;\n }\n}\n\n$converter = new SpreadsheetTillsConverter(17, 7, [\n 40 =&gt; 41,\n 42 =&gt; 43,\n 44 =&gt; 45,\n 46 =&gt; 47,\n 48 =&gt; 49\n]);\n\n$tills = $converter-&gt;getTills($spreadsheetData);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T10:06:41.800", "Id": "240195", "ParentId": "240192", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T09:07:22.010", "Id": "240192", "Score": "1", "Tags": [ "php", "laravel" ], "Title": "Importing data from spreadsheet" }
240192
<p>For my first solo React exercise project I decided to recreate a quote machine from the example that uses vanilla JS/jQuery. I also used a mix of Bootstrap/plain CSS. I got it to look how I wanted and do what I wanted, but I am not sure if my code follows best practices. All feedback is much appreciated, as I am still quite new to web development.</p> <p>I also included a link to GitHub repository, where I listed some more specific questions in the README and a React code with a commented out parts which I tried, if you are willing to help out some more:</p> <p><a href="https://github.com/Ogatron3000/Random-Quote-Machine" rel="nofollow noreferrer">https://github.com/Ogatron3000/Random-Quote-Machine</a></p> <p>React:</p> <pre><code>React, { Component } from 'react'; import axios from "axios"; class App extends Component { state = { quotes: [], quote: {}, animation: "jackInTheBox", colors: ["primary", "success", "warning", "danger", "info", "dark"], color: "primary" } // get quotes componentDidMount() { axios.get("https://gist.githubusercontent.com/shreyasminocha/7d5dedafc1fe158f82563c1223855177/raw/325d51aca7165b2498971afcff9bed286a52dc0e/quotes.json") .then(res =&gt; { this.setState({ quotes: res.data, quote: res.data[0] }) }) } // new quote handleClick = () =&gt; { this.setState({ quote: this.state.quotes[Math.floor(Math.random()*102)], animation: "animated jackInTheBox", color: this.state.colors[Math.floor(Math.random()*6)] }) } render() { // assign random quote const quote = this.state.quotes.length ? (this.state.quote.quote) : ("Wait o"); // assign author const author = this.state.quotes.length ? (this.state.quote.author) : (""); // tweet link const tweet = "https://twitter.com/intent/tweet?hashtags=quotes&amp;related=freecodecamp&amp;text=" + '"' + quote + '" ' + author; // tumblr link const tumblr = "https://www.tumblr.com/widgets/share/tool?posttype=quote&amp;tags=quotes,freecodecamp&amp;caption=" + author + "&amp;content=" + quote + "&amp;canonicalUrl=https%3A%2F%2Fwww.tumblr.com%2Fbuttons&amp;shareSource=tumblr_share_button"; return ( &lt;div className={"App animted fadeIn bg-" + this.state.color}&gt; &lt;div id="quote-box" className="card"&gt; &lt;p id="text" className={"text-center " + this.state.animation + " text-" + this.state.color} key={Math.random()}&gt; {quote} &lt;/p&gt; &lt;p id="author" className={"text " + this.state.animation + " text-" + this.state.color} key={Math.random() + 1}&gt; - {author} &lt;/p&gt; &lt;div id="buttons"&gt; &lt;a id="tweet-quote" className="button-link" href={tweet} target="_blank"&gt; &lt;button className={"btn btn-" + this.state.color}&gt; &lt;span className="fa fa-twitter"&gt;&lt;/span&gt; &lt;/button&gt; &lt;/a&gt; &lt;a id="tumblr-quote" className="button-link" href={tumblr} target="_blank"&gt; &lt;button className={"btn btn-" + this.state.color}&gt; &lt;span className="fa fa-tumblr"&gt;&lt;/span&gt; &lt;/button&gt; &lt;/a&gt; &lt;button id="new-quote" className={"btn btn-" + this.state.color} onClick={this.handleClick}&gt; New Quote &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ); } } export default App; </code></pre> <p>CSS:</p> <pre><code>body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; } .App { height: 100vh; width: 100vw; transition: background 0.4s linear; display: flex; align-items: center; justify-content: center; overflow: hidden; } #quote-box{ padding: 40px; width: 500px; min-width: 500px; } #text{ width: 100%; font-size: 32px; margin-bottom: 0; } #author{ display: flex; justify-content: end; margin-bottom: 30px; } #buttons{ display: grid; grid-template-columns: repeat(12, 1fr); grid-gap: 10px; } #new-quote{ grid-column: 3 / 13; justify-self: end; } .button-link button{ width: 40px; } .btn{ transition: background 0.4s linear; border: none; color: white; } .btn:focus{ box-shadow: none !important; outline-style: none !important; color:white !important; } .btn:hover{ color: white; } </code></pre> <p>Thank you for your time!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T10:03:01.870", "Id": "240194", "Score": "1", "Tags": [ "javascript", "css", "react.js", "twitter-bootstrap" ], "Title": "Random Quote Machine with React and Bootstrap" }
240194
<p>I have implemented binary exponentiation. Is this good?</p> <pre class="lang-py prettyprint-override"><code>def quad_pow(base, exponent, modul): alpha = (bin(exponent).replace('0b', ''))[::-1] a = 1 b = base for i in range(0, len(alpha)): if int(alpha[i]) == 1: a = (a * b) % modul b = (b*b) % modul return a </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T14:36:32.730", "Id": "471142", "Score": "0", "body": "Are you trying to \"reinvent-the-wheel\"? If not, the most efficient way is [`pow(base, exponent, modul)`](https://docs.python.org/3.8/library/functions.html?highlight=pow#pow) (Python 3.x)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T14:58:29.360", "Id": "471145", "Score": "0", "body": "No, I am not. I am aware that there are those functions, but programming doesn't mean that you use those default finished things. I was interested in how to programm this mathematical algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T15:01:25.147", "Id": "471146", "Score": "1", "body": "\"Reinventing the wheel\" is a perfectly sound practice; especially when trying to learn programming, or understanding algorithms. We even have a tag for that." } ]
[ { "body": "<p>The string manipulation is avoidable, by working with bits of the exponent directly:</p>\n\n<pre><code>def quad_pow(base, exponent, modul): \n a = 1\n b = base\n\n while exponent:\n if exponent &amp; 1:\n a = (a * b) % modul\n b = (b * b) % modul\n exponent &gt;&gt;= 1\n return a\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T12:06:03.130", "Id": "240197", "ParentId": "240196", "Score": "3" } }, { "body": "<p>One set of parenthesis are unneeded in this expression:</p>\n\n<pre><code>alpha = (bin(exponent).replace('0b', ''))[::-1]\n</code></pre>\n\n<p>You could write this as:</p>\n\n<pre><code>alpha = bin(exponent).replace('0b', '')[::-1]\n</code></pre>\n\n<hr>\n\n<p>Using <code>[::-1]</code> to reverse the string is nice, but using <code>replace('0b', '')</code> to remove the <code>\"0b\"</code> from the start first is unnecessary. Using the <code>end</code> field of <code>[start:end:step]</code> would work ... you want to end just before the first character:</p>\n\n<pre><code>alpha = bin(exponent)[:1:-1]\n</code></pre>\n\n<hr>\n\n<p>Conversion from a string (<code>\"0\"</code> and <code>\"1\"</code>) to an integer (<code>0</code> and <code>1</code>) is unnecessary when you are just comparing the result to the integer <code>1</code>. So instead of:</p>\n\n<pre><code> if int(alpha[i]) == 1:\n</code></pre>\n\n<p>you could write:</p>\n\n<pre><code> if alpha[i] == \"1\":\n</code></pre>\n\n<hr>\n\n<p>When you loop over a string, character by character (or any ordered container element by element), using:</p>\n\n<pre><code>for i in range(0, len(alpha)):\n if alpha[i] == \"1\":\n ...\n ...\n</code></pre>\n\n<p>is an anti-pattern in Python. You should loop directly over the container:</p>\n\n<pre><code>for character in alpha:\n if character == \"1\":\n ...\n ...\n</code></pre>\n\n<p>If you need the element and the index, you should use <code>enumerate</code>:</p>\n\n<pre><code>for i, character in enumerate(alpha):\n ...\n</code></pre>\n\n<p>but that is not necessary here.</p>\n\n<hr>\n\n<p>Updated code, with type hints and an example <code>\"\"\"docstring\"\"\"</code>:</p>\n\n<pre><code>def quad_pow(base: int, exponent: int, modul: int) -&gt; int:\n \"\"\"\n Efficiently compute (base ^ exponent) % modul\n\n Parameters:\n base: The value to raise to the exponent\n exponent: The exponent to raise the base to\n modul: The modulus to compute the resulting value in\n\n Returns:\n The base raised to the exponent, modulo the given modulus\n \"\"\"\n\n alpha = bin(exponent)[:1:-1]\n a = 1\n b = base\n\n for character in alpha:\n if character == \"1\":\n a = (a * b) % modul\n b = (b * b) % modul\n\n return a\n</code></pre>\n\n<hr>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> Note:</p>\n\n<p>Binary operators should have a space on either side, so <code>(b*b)</code> should be written <code>(b * b)</code>.</p>\n\n<hr>\n\n<p>See also <a href=\"https://codereview.stackexchange.com/a/240197/100620\">harold's answer</a> for avoiding the conversion of the exponent to a string.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T15:27:29.930", "Id": "240210", "ParentId": "240196", "Score": "3" } } ]
{ "AcceptedAnswerId": "240210", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T11:15:45.307", "Id": "240196", "Score": "1", "Tags": [ "python", "reinventing-the-wheel", "mathematics" ], "Title": "Binary exponentation with modulo" }
240196
<p>I have programmed the extended euclidean algorithm. Is this a good approach?</p> <pre><code>def ext_ggT(a, b): x,y, u,v = 0,1, 1,0 while a != 0: q, r = b//a, b%a m, n = x-u*q, y-v*q b,a, x,y, u,v = a,r, u,v, m,n gcd = b return gcd, x, y </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T14:15:10.387", "Id": "471138", "Score": "7", "body": "Close voters, just because you don't know what the [extended Euclidean algorithm](https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm) is doesn't mean that the question is unclear. I don't close C questions because I don't know C and it's 'unclear' to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T15:46:22.873", "Id": "471148", "Score": "0", "body": "`Is this a good approach?` approach to what exactly? Or do you want opinions if you coded it well, advice how to code it better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T20:36:38.563", "Id": "471163", "Score": "0", "body": "I guess advice... There are always more efficient ways of doing it, so I wanted some feedback. I have a book for computer science in which I found the theory of the algorithm and with it I programmed this function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T02:05:15.893", "Id": "471183", "Score": "1", "body": "For what it's worth, as a number theorist, I found this a very clear transcription in code of how I would think of the problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T06:09:01.027", "Id": "471190", "Score": "0", "body": "Looks good to me. I would add a comment explaining the return value and the Bezout identity." } ]
[ { "body": "<p>Give your variables meaningful names reflecting their role in the algorithm.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T00:22:59.473", "Id": "471178", "Score": "6", "body": "In the context of mathematics it can be hard to find meaningful variable names" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T04:28:21.013", "Id": "471186", "Score": "2", "body": "I can only think of good names for quotient and remainder. Nothing else really makes anything clearer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T10:09:52.773", "Id": "471220", "Score": "1", "body": "@northerner It's hard to find meaningful names in computer programming too. Just seems like a cop out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T10:12:16.047", "Id": "471221", "Score": "2", "body": "@Peilonrayz you seriously seem to miss the point" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T10:13:40.657", "Id": "471222", "Score": "0", "body": "@northerner I understand, anyone that has a different view to you is what incapable of hitting the point?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T10:15:05.193", "Id": "471223", "Score": "1", "body": "@Peilonrayz you don't backup your assertion at all. Take the Euclidean Algorithm for instance. It takes two arguments, commonly called `a` and `b`. Please tell me a better name for them?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T10:15:43.407", "Id": "471224", "Score": "0", "body": "@northerner You didn't either... hypocrite lol?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T10:17:39.443", "Id": "471226", "Score": "0", "body": "Math is already an abstract subject, hence it usually doesn't have meaningful variable names. You can't generalize the whole statement to all of computer programming." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T10:19:02.433", "Id": "471228", "Score": "0", "body": "Can you please discuss that in a chatroom. I am getting a bit annoyed about the pings right now." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T12:17:56.587", "Id": "240199", "ParentId": "240198", "Score": "3" } }, { "body": "<p>Not being familiar with the algorithm in question, it was very non-obvious to me what the code did, and in general I think it's good to write code in such a way that it's comprehensible with minimal reasonable effort even if the reader isn't a domain expert (i.e. they should be able to look up documentation, look at your code, and see how the two relate). The main hindrances I faced were:</p>\n\n<ol>\n<li>It wasn't immediately obvious that <code>x, y, u, v</code> represented two distinct series (where u was always a prior value of x, etc). In general there are a lot of variables in this code to keep track of, and not a lot of explanation of what they're all for.</li>\n<li>Dependencies between the different values likewise were not obvious. Having all the assignments smushed onto one line made it hard to discern this visually; it's nice to use compact tuple assignments when the relationships are obvious, but it doesn't necessarily <em>always</em> improve readability.</li>\n<li>There're no doc/comments explaining what's going on.</li>\n<li>The name ext_ggT doesn't follow Python's snake_case naming convention and is a bit cryptic.</li>\n</ol>\n\n<p>After reading the wiki link (thx Peilon) I was able to sort of reverse-engineer it and then I made some changes so that the code matches up more with my understanding based on the wiki article (and is commented so that anyone looking at this code side by side with the wiki article will immediately see what goes with what). </p>\n\n<pre><code>from collections import deque\nfrom typing import Tuple\n\ndef extended_euclidean(a: int, b: int) -&gt; Tuple[int, int, int]:\n \"\"\"\n Returns (gcd, x, y) such that:\n gcd = greatest common divisor of (a, b)\n x, y = coefficients such that ax + by = gcd\n \"\"\"\n # We only need to keep the last two elements of each series.\n r = deque([b, a], 2)\n s = deque([0, 1], 2)\n t = deque([1, 0], 2)\n\n # The next element of each series is a function of the previous two.\n # We stop building these series once r (the remainder) is zero; \n # the final result comes from the iteration prior to that one.\n while r[-1] != 0:\n q = r[-2] // r[-1]\n r.append(r[-2] % r[-1])\n s.append(s[-2] - s[-1] * q)\n t.append(t[-2] - t[-1] * q)\n\n return r[-2], s[-2], t[-2]\n\nassert extended_euclidean(240, 46) == (2, -9, 47)\n</code></pre>\n\n<p>The biggest change is that I've represented the various series described in the wiki article as iterables, rather than representing each as two scalars; this doesn't make much difference to the way the code actually runs, but the fact that these six values (previously a, b, x, y, u, and v) represent three distinct series is now very obvious to the reader. The three series are initialized and extended in such a way as to \"make alike look alike\" -- you can see at a glance how each successive element is computed from the prior two, and easily discern where there are and aren't dependencies between these values.</p>\n\n<p>You could initialize these series as simply:</p>\n\n<pre><code>r = [b, a]\ns = [0, 1]\nt = [1, 0]\n</code></pre>\n\n<p>and the code would return the correct result, but to preserve the behavior of only keeping the last two elements (which I agree is a good space optimization) I've converted them to <code>deque</code>s with <code>maxlen=2</code>. The deque abstracts away the business of automatically popping the unneeded values off of the left side, which helps declutter the \"interesting\" part of the implementation while still preserving the property of having it use constant space.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T04:27:17.753", "Id": "471185", "Score": "5", "body": "I strongly disagree with using deques. There is so much unnecessary overhead for a simple algorithm. The original implementation follows the mathematical formulation but this version strays from it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T07:17:43.003", "Id": "471200", "Score": "1", "body": "I timed things, and this is rougly twice as slow as the original code with `python3`, and ten times as slow with `pypy3`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T15:07:09.057", "Id": "471261", "Score": "1", "body": "Good points! In most real-world situations, it's more important to optimize reading and debugging a particular function than constant factors of its actual runtime, because human time is much more expensive than CPU time. But in a situation where every nanosecond counts because you're operating at massive scale, you may not want to use Python at all (say, use Rust to write the performance-sensitive part of your code and call the compiled library via CFFI from your Python code)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T15:08:36.770", "Id": "471262", "Score": "1", "body": "I'd be very interested in seeing other implementations that follow the description of the algorithm as described in Wiki (i.e. expressing it as the *r*, *s*, *t* series). On the way to this one I did a version with 2-tuples that probably performs better than deques, but I didn't like the way that it read." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-16T12:22:29.067", "Id": "514710", "Score": "0", "body": "Inspite of all reasons, simple commenting and meaningful variable names would have been enough. Spirit of simplicity is lost. In fact, yours needs original one to show (a Mathl. newbie) how simple it is. Might be both complement each other, so in a sense both implementations are needed." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T16:41:41.680", "Id": "240215", "ParentId": "240198", "Score": "10" } } ]
{ "AcceptedAnswerId": "240215", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T12:08:06.977", "Id": "240198", "Score": "3", "Tags": [ "python", "mathematics" ], "Title": "Extended Euclidean algorithm" }
240198
<p>I am modelling a user preference system with the following requirements </p> <ul> <li>a user can have attributes (foods they eat)</li> <li>a user can have dynamic categories of preferences</li> <li>users which have all their categories with at least one intersect can match</li> </ul> <p>So far I have used Postgres's arrays to build a system to avoid joins. NB. I'm not using proper keys at the moment for simplicity.</p> <pre><code>CREATE TABLE public.users ( name text, food text[] ); CREATE TABLE public.preferences ( name text, category text, food text[] ); INSERT INTO public.preferences VALUES ('John', 'Breakfast', '{toast,cereal}'); INSERT INTO public.preferences VALUES ('John', 'Dinner', '{ham}'); INSERT INTO public.preferences VALUES ('Jane', 'Breakfast', '{toast,eggs}'); INSERT INTO public.preferences VALUES ('Jack', 'Breakfast', '{grapefruit}'); INSERT INTO public.users VALUES ('John', '{peas,ham,"ice cream",toast}'); INSERT INTO public.users VALUES ('Jane', '{eggs,ham,"ice cream",cereal,toast}'); INSERT INTO public.users VALUES ('Jack', '{toast,cereal,eggs,peas}'); </code></pre> <p>I have a query that seems to work, however was wondering if anyone had any feedback. It works by asserting that there "are not any categories, which don't match".</p> <pre><code>select * from users u where name &lt;&gt; 'Jane' and not exists (select from preferences p where name = 'Jane' and not u.food &amp;&amp; p.food) and not exists (select from preferences p where u.name = p.name and not (select u.food from users u where u.name = 'Jane') &amp;&amp; p.food); name | food ------+------------------------------ John | {peas,ham,"ice cream",toast} (1 row) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T19:43:22.863", "Id": "471411", "Score": "0", "body": "What's the difference between \"a food that a user eats\" and \"a food that a user prefers to eat\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T19:45:04.127", "Id": "471412", "Score": "0", "body": "Also, can you describe what you want that query to actually do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T13:58:40.597", "Id": "471637", "Score": "0", "body": "@Reinderien return the users where they share at least one food in each category (meal). The \"prefers to eat\" is in a particular category." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T17:17:42.290", "Id": "471668", "Score": "0", "body": "I still do not understand the difference between your `users.food` and `preferences.food`. Does `users.food` just track a food to which a user is not allergic (an \"acceptable\" food)? Or are you trying to capture the difference between \"foods a user prefers without association to a category\" and \"foods a user prefers within a category\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T17:19:54.233", "Id": "471669", "Score": "0", "body": "Put another way: is there ever a case where a `users.food` will not have a corresponding entry in `preferences.food`, or vice versa?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T08:15:07.290", "Id": "472001", "Score": "0", "body": "Yes, that would be possible." } ]
[ { "body": "<blockquote>\n <p>I have used Postgres's arrays to build a system to avoid joins. NB. I'm not using proper keys at the moment for simplicity.</p>\n</blockquote>\n\n<p>One person's simplicity is another person's denormalized nightmare. Are you avoiding joins because of some already-analysed performance rationale? If so, fine. But if it's based on superstition, this is probably premature optimization.</p>\n\n<p>All of that is to say, the \"traditional\" normalized relational approach to this would be:</p>\n\n<ul>\n<li>A <code>user</code> table with an integer primary key</li>\n<li>A <code>food</code> table with an integer primary key</li>\n<li>A <code>meal</code> table with an integer primary key</li>\n<li>A <code>preference</code> table with foreign keys to <code>user</code>, <code>food</code> and <code>meal</code></li>\n</ul>\n\n<p>Don't be afraid of <code>join</code>. Or if you are, consider using a denormalized or \"tabular\" database like Mongo.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T08:17:08.913", "Id": "472002", "Score": "1", "body": "I reworked the code into a relational style, and used left joins coupled with group by count distinct on the meal table to ensure that there was one match in at least every meal. It does use a subselect, to ensure that both user's preferences are matched." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T19:00:45.863", "Id": "240354", "ParentId": "240202", "Score": "2" } } ]
{ "AcceptedAnswerId": "240354", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T12:57:26.437", "Id": "240202", "Score": "3", "Tags": [ "sql", "postgresql" ], "Title": "Modelling user preference system with categories" }
240202
<p>I have implemented the <a href="https://en.wikipedia.org/wiki/Simpson%27s_rule" rel="nofollow noreferrer">Simpson's rule</a> for numerical integration. </p> <p><a href="https://www.youtube.com/watch?v=ns3k-Lz7qWU" rel="nofollow noreferrer"><strong>Check this video for the implemented function.</strong></a></p> <pre><code>namespace Simpsons_method_of_integration { //https://www.youtube.com/watch?v=ns3k-Lz7qWU using System; public class Simpson { private double Function(double x) { return 1.0 / (1.0 + Math.Pow(x, 5)); //Define the function f(x) } public double Compute(double a, double b, int n) { double[] x = new double[n + 1]; double delta_x = (b - a) / n; x[0] = a; for (int j = 1; j &lt;= n; j++)//calculate the values of x1, x2, ...xn { x[j] = a + delta_x * j; } double sum = Function(x[0]); for (int j = 1; j &lt; n; j++) { if (j % 2 != 0) { sum += 4 * Function(x[j]); } else { sum += 2 * Function(x[j]); } } sum += Function(x[n]); double integration = sum * delta_x / 3; return integration; } } public class MainClass { public static void Main() { Simpson simpson = new Simpson(); double a = 0d;//lower limit a double b = 3d;//upper limit b int n = 6;//Enter step-length n if (n % 2 == 0)//n must be even { Console.WriteLine(simpson.Compute(a, b, n)); } else { Console.WriteLine("n should be an even number"); } Console.ReadLine(); } } } </code></pre> <p><strong><em>Output:</em></strong></p> <pre><code>1.07491527775614 </code></pre> <hr> <p>How can I make this source code more efficient?</p>
[]
[ { "body": "<p>In regards to performance or efficiency, I don't see anything that begs for attention.</p>\n\n<p>I would suggest <code>Simpson</code> class and its methods be <code>static</code>. You really are not saving any properties or state between invocations, so <code>static</code> makes more sense.</p>\n\n<p>The method named <code>Function</code> is a horrible name. Far too generic.</p>\n\n<p>I'm not even keen on the method name <code>Compute</code>, though it is an action verb. I'd be partial to <code>Integrate</code> which is also an action verb but more descriptive. The parameter names are decent. Since Simpson's Rule uses the non-descript <code>a</code> and <code>b</code>, it's okay that your method does as well. Perhaps <code>n</code> could be given a more descriptive name.</p>\n\n<p>Your use of braces and indentation looks good. Also good that <code>Function</code> is <code>private</code> and <code>Compute</code> is <code>public</code>. However, you do not provide any validation checks on <code>public</code> methods. What if someone entered <code>-999</code> as the value for <code>n</code>? </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T15:34:20.090", "Id": "240211", "ParentId": "240207", "Score": "2" } }, { "body": "<ul>\n<li><p>There is no reason to allocate the <code>double[] x</code> array. It is better to compute the argument as you go: initialize <code>double x = a;</code> and increment it <code>x += delta_x;</code> in the loop body.</p></li>\n<li><p><code>if</code> in the loop is usually a performance killer. Consider incrementing <code>j</code> by 2:</p>\n\n<pre><code> for (int j = 1; j &lt; n; j += 2)\n {\n sum += 2 * Function(x);\n x += delta_x;\n sum += 4 * Function(x);\n x += delta_x;\n }\n</code></pre>\n\n<p>Now depending on the parity of <code>n</code> the very last addition could be wrong, and you need to compensate for it.</p></li>\n<li><p><code>Function</code> shall not be a <code>Simpson</code>'s method. The <code>Simpson</code> shall not care what it integrates. Change the signature of <code>Compute</code> to accept the callable.</p></li>\n<li><p>The choice of <span class=\"math-container\">\\$\\dfrac{1}{1 + x^5}\\$</span> for an integrand looks strange. It is hard to verify that the result is correct. I recommend to test against some more friendly integrands first.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T20:53:55.143", "Id": "240227", "ParentId": "240207", "Score": "5" } }, { "body": "<p>You don't need the <code>double[]</code>.</p>\n\n<p>Example implementation that only loops once and discards the array:</p>\n\n<pre><code>public static double ComputeV2(double a, double b, int n)\n{\n double deltaX = DeltaX(a, b, n);\n\n // start with a sum of x_0 and x_n:\n double sum = Function(a) + Function(a + deltaX * n);\n\n for (int j = 1; j &lt; n; j++)\n {\n sum += Function(a + deltaX * j) * (j % 2 == 0 ? 2 : 4);\n }\n\n return Integrate(sum, deltaX);\n}\n</code></pre>\n\n<p>And if you're into LINQ, something like this also works:</p>\n\n<pre><code>public static double ComputeLinq(double a, double b, int n)\n{\n double deltaX = DeltaX(a, b, n);\n\n double sum =\n Enumerable\n .Range(1, n - 1)\n .Select(j =&gt; Function(a + deltaX * j) * (j % 2 == 0 ? 2 : 4))\n .Aggregate(\n seed: Function(a) + Function(a + deltaX * n),\n func: (acc, v) =&gt; acc + v);\n\n return Integrate(sum, deltaX);\n}\n</code></pre>\n\n<p>As for performance, here are some micro benchmarks:</p>\n\n<pre><code>\nBenchmarkDotNet=v0.12.1, OS=Windows 10.0.18363.720 (1909/November2018Update/19H2)\nIntel Core i7-8650U CPU 1.90GHz (Kaby Lake R), 1 CPU, 8 logical and 4 physical cores\n.NET Core SDK=2.2.301\n [Host] : .NET Core 2.2.6 (CoreCLR 4.6.27817.03, CoreFX 4.6.27818.02), X64 RyuJIT\n DefaultJob : .NET Core 2.2.6 (CoreCLR 4.6.27817.03, CoreFX 4.6.27818.02), X64 RyuJIT\n\n| Method | Mean | Error | StdDev | Median |\n|------------ |---------:|---------:|---------:|---------:|\n| SimpsonV1 | 286.6 ns | 5.53 ns | 11.30 ns | 285.9 ns |\n| SimpsonV2 | 270.1 ns | 5.52 ns | 14.04 ns | 267.0 ns |\n| SimpsonLinq | 510.8 ns | 11.67 ns | 34.23 ns | 500.1 ns |\n</code></pre>\n\n<p>As you can see, using LINQ is clearly slower, but is often more readable (not really in this case, in my opinion).</p>\n\n<p>\"My\" version is a bit faster than yours, but it's very negligible. The biggest gain is readability and succinctness, but I bet some will find it to be \"too\" short for its own good.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T21:12:01.480", "Id": "240228", "ParentId": "240207", "Score": "3" } }, { "body": "<p>This:</p>\n\n<blockquote>\n<pre><code> if (j % 2 != 0)\n {\n sum += 4 * Function(x[j]);\n }\n else\n {\n sum += 2 * Function(x[j]);\n }\n</code></pre>\n</blockquote>\n\n<p>can be expressed as:</p>\n\n<pre><code> sum += (2 &lt;&lt; (j % 2)) * Function(x);\n</code></pre>\n\n<hr>\n\n<p>In order to make your algorithm more useful, you should inject the <code>Function</code> as a delegate parameter to the method, and also make it <code>static</code>:</p>\n\n<pre><code>public static double Compute(Func&lt;double, double&gt; fx, double a, double b, int n)\n{\n double h = (b - a) / n;\n\n double sum = fx(a) + fx(b);\n double x = a;\n for (int j = 1; j &lt; n; j++)\n {\n x += h;\n sum += (2 &lt;&lt; (j % 2)) * fx(x);\n }\n\n return sum * h / 3;\n}\n</code></pre>\n\n<p>Used as:</p>\n\n<pre><code>Simpson.Compute(x =&gt; 1 / (1 + Math.Pow(x, 5)), a, b, n);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T13:23:25.330", "Id": "240275", "ParentId": "240207", "Score": "2" } } ]
{ "AcceptedAnswerId": "240275", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T14:10:16.280", "Id": "240207", "Score": "3", "Tags": [ "c#", "numerical-methods" ], "Title": "Simpson's method for numerically computing the integration of a function" }
240207
<p>I am developing an application in which the user can use different measurement systems. Currently, there is support for the metric and imperial measurement systems. To support these systems, I wrote a converter. Could you take a look at its code and tell how can it be improved.</p> <pre><code>public class SystemsMeasuresConverter { private Context context; private Profile profile; public SystemsMeasuresConverter(Context context, Profile profile) { this.context = context; this.profile = profile; } /** * Converts mass from some units to some units * * @param input mass in some units * @return mass some units */ public Number convertToMassUnit(Number input, SystemsMeasures from, SystemsMeasures to) { double constant = 1; switch (from) { case Imperial: if (to == Metric) { constant = 0.455; } break; case Metric: if (to == Imperial) { constant = 2.2; } break; } return MathUtil.round(input.doubleValue() * constant, MathUtil.GLOBAL_SCALE); } /** * Converts mass from some units to units selected in profile * * @param input mass in some units * @return mass in units of measurements selected in the user profile */ public Number convertToMassUnit(Number input, SystemsMeasures from) { return convertToMassUnit(input, from, profile.getSystemMeasures()); } /** * Converts mass from kilograms to units selected in profile * * @param input metric system * @return mass in units of measurements selected in the user profile */ public Number convertToMassUnit(Number input) { return convertToMassUnit(input, Metric, profile.getSystemMeasures()); } /** * Converts distance from units selected in profile to kilograms * * @param input metric system * @return distance in units of measurements selected in the user profile */ public Number convertToKg(Number input) { return convertToMassUnit(input, profile.getSystemMeasures(), SystemsMeasures.Metric); } /** * Returns abbreviations for mass units selected in profile * * @return abbreviations for mass units selected in profile */ public String getStringFromCurrentMassUnit() { SystemsMeasures unit = profile.getSystemMeasures(); switch (unit) { case Metric: return context.getString(R.string.kilogramsMassUnit); case Imperial: return context.getString(R.string.poundsMassUnit); } throw new RuntimeException("Cannot find Mass Unit"); } /** * Converts distance from some units to some units * * @param input mass in some units * @return mass some units */ public Number convertToDistanceUnits(Number input, SystemsMeasures from, SystemsMeasures to) { double constant = 1; switch (from) { case Imperial: if (to == Metric) { constant = 2.54; } break; case Metric: if (to == Imperial) { constant = 0.394; } break; } return MathUtil.round(input.doubleValue() * constant, MathUtil.GLOBAL_SCALE); } /** * Converts distance from some units to units selected in profile * * @param input distance in some units * @return distance in units of measurements selected in the user profile */ public Number convertToDistanceUnits(Number input, SystemsMeasures from) { return convertToDistanceUnits(input, from, profile.getSystemMeasures()); } /** * Converts distance from meters to units selected in profile * * @param input metric system * @return distance in units of measurements selected in the user profile */ public Number convertToDistanceUnits(Number input) { return convertToDistanceUnits(input, Metric, profile.getSystemMeasures()); } /** * Converts distance from units selected in profile to meters * * @param input metric system * @return distance in units of measurements selected in the user profile */ public Number convertToMeter(Number input) { return convertToDistanceUnits(input, profile.getSystemMeasures(), SystemsMeasures.Metric); } /** * Returns abbreviations for distance units selected in profile * * @return abbreviations for distance units selected in profile */ public String getStringFromCurrentDistanceUnit() { SystemsMeasures unit = profile.getSystemMeasures(); switch (unit) { case Metric: return context.getString(R.string.meters_distance_unit); case Imperial: return context.getString(R.string.feet_distance_unit); } throw new RuntimeException("Cannot find Mass Unit"); } } </code></pre> <p>SystemsMeasures</p> <pre><code>public enum SystemsMeasures { Metric(0), Imperial(1); private final int value; SystemsMeasures(int value) { this.value = value; } public int getValue(){ return value; } public static SystemsMeasures getById(int id) { for (SystemsMeasures e : values()) { if (e.value == id) return e; } return Metric; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T07:14:43.827", "Id": "471198", "Score": "1", "body": "attributes should be private and accessible using getters/setters. In your case, `context` and `profile` are package private." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T07:18:03.893", "Id": "471201", "Score": "1", "body": "I think `getById()` could technically be improved by storing the enums in a `HashMap` or something like this additionally but I don't think there are performance improvements as thete ate only two elements." } ]
[ { "body": "<p>I would replace all the switch statements with a Map.<br>\nMap key should be pair of from-to <code>SystemsMeasures</code>. Map value can be a container class that holds all conversion factors.<br>\nYou can write custom <code>Pair</code> or <code>Tuple</code> class or use ready made one from libraries such as Apache commons, Guava, etc.<br>\nThe container class can be something like </p>\n\n<pre><code>public class ConversionFactor {\n public double mass;\n public double distance;\n public ConversionFactor(double mass, double distance) {\n this.mass = mass;\n this.distance = distance;\n }\n}\n</code></pre>\n\n<p>The map can be defined (assuming <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html\" rel=\"nofollow noreferrer\">Apache commons Pair</a> which correctly implements <code>equals()</code> and <code>hashCode()</code>)</p>\n\n<pre><code>Map&lt;Pair&lt;SystemsMeasures, SystemsMeasures&gt;, ConversionFactor&gt;\n</code></pre>\n\n<p>Now, you just need to create a <code>Pair</code> instance that represents the requested conversion and <code>get()</code> the value from the map.</p>\n\n<p>an added advantage of this approach is that you can easily load the map values from file, avoiding <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers anti-pattern</a></p>\n\n<p>Example:</p>\n\n<pre><code>public static Map&lt;Pair&lt;SystemsMeasures, SystemsMeasures&gt;, ConversionFactor&gt; conversionMap =\n Map.of(\n new ImmutablePair&lt;&gt;(SystemsMeasures.Metric, SystemsMeasures.Imperial),\n new ConversionFactor(2.2, 0.394),\n new ImmutablePair&lt;&gt;(SystemsMeasures.Imperial, SystemsMeasures.Metric),\n new ConversionFactor(0.455, 2.54)\n );\n\npublic Number convertToMassUnit(Number input, SystemsMeasures from, SystemsMeasures to) {\n double constant = conversionMap.get(new ImmutablePair&lt;&gt;(from, to)).mass;\n return ... \n}\n</code></pre>\n\n<p>The above map can be represented in serialized form:</p>\n\n<pre><code>Metric, Imperial -&gt; 2.2, 0.394\nImperial, Metric -&gt; 0.455, 2.54\n</code></pre>\n\n<p>read the file into <code>List&lt;String&gt;</code> and parse it into the map. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T09:51:06.667", "Id": "471218", "Score": "0", "body": "Could you give some examples of this? (code, examples, articles)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T10:17:48.040", "Id": "471227", "Score": "1", "body": "see edited code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T12:49:54.217", "Id": "471244", "Score": "0", "body": "Why did you reject the change? Initially, the question rocked Android, for which Map.of does not work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T13:35:25.273", "Id": "471248", "Score": "0", "body": "the question is not specific to Android. and even if you don't want to use `Map.of`, it is bad practice to use double brace initialization" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T13:41:27.127", "Id": "471249", "Score": "0", "body": "But how can this be done differently if this is bad practice?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T13:54:36.007", "Id": "471253", "Score": "0", "body": "with `put(key, value)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T13:58:44.397", "Id": "471254", "Score": "0", "body": "put (new Pair <> (SystemsMeasures.Metric, SystemsMeasures.Imperial),\n new MeasuresConversionFactor (2.2, 0.394));\nDon't I do it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T15:12:50.693", "Id": "471263", "Score": "0", "body": "in the constructor of `SystemsMeasuresConverter`" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T09:32:20.987", "Id": "240264", "ParentId": "240208", "Score": "1" } }, { "body": "<p>I would suggest changing <code>SystemsMeasures</code> to</p>\n\n<pre><code>public enum SystemsMeasures {\n Metric(1.0,1.0),\n Imperial(2.54,0.455);\n\n public final double lengthFactor;\n public final double massFactor;\n\n SystemsMeasures(double lengthFactor,double massFactor) {\n this.lengthUnit = lengthUnit;\n this.lengthFactor = lengthFactor;\n }\n}\n</code></pre>\n\n<p>Then you can just write for example</p>\n\n<pre><code>/**\n * Converts mass from some units to some units\n *\n * @param input mass in some units\n * @return mass some units\n */\npublic Number convertToMassUnit(Number input, SystemsMeasures from, SystemsMeasures to) {\n return MathUtil.round(input.doubleValue() * from.MassFactor/to.MassFactor, MathUtil.GLOBAL_SCALE);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T13:13:39.160", "Id": "471246", "Score": "0", "body": "It seems to me to use LengthUnit and MassUnit will be superfluous, since this does not affect the work of the code and does not make any sense" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T13:20:53.160", "Id": "471247", "Score": "0", "body": "@Destroyer. You're right. I think that I added them for simplification of `getStringFromCurrentMassUnit()` and `getStringFromCurrentDistanceUnit()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T13:47:34.240", "Id": "471251", "Score": "0", "body": "These lines are in R.string. Therefore, for implementation, you need to use not string but id string, and i will have to use context in enum. In general, I think this is a bad idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T13:51:00.297", "Id": "471252", "Score": "0", "body": "@Destroyer. I approved your edit. You know more about the context than I do." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T12:59:22.487", "Id": "240272", "ParentId": "240208", "Score": "2" } } ]
{ "AcceptedAnswerId": "240272", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T14:15:02.983", "Id": "240208", "Score": "5", "Tags": [ "java", "beginner", "android", "converting", "unit-conversion" ], "Title": "Code to support different measurement systems" }
240208
<p>My controller is looking something like this.</p> <p>Each of the methods called generate some HTML. The concatenated HTML variable gives the final render of the page </p> <p>Is there a better way to generate my HTML to render coming from different functions:</p> <pre><code> $html = $renderer-&gt;render($clear_form); $html .= $this-&gt;render_preview(); $config = \Drupal::config('amu_import_ldap.settings'); if (null != $config) { $submits = $config-&gt;get('import_submits'); $html .= $this-&gt;render_ldap_imports($submits); } $build = [ '#markup' =&gt; Markup::create(" {$html} "), ]; return $build; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T16:58:53.367", "Id": "471152", "Score": "1", "body": "Hello Matoeil. Unfortunately your question has gained a close vote for missing a description. Please can you explain what your code does, currently your description means nothing to me. Given how small the code is it should be easy to explain everything it does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T07:47:19.867", "Id": "471205", "Score": "0", "body": "each of the methods called generate some html. The concatenenated html variable gives the final render of the page" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T08:14:52.193", "Id": "471209", "Score": "0", "body": "@Matoeil: Please [edit] your question to include that description." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T08:35:07.233", "Id": "471215", "Score": "0", "body": "this is done..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T13:41:09.463", "Id": "471381", "Score": "0", "body": "That wasn't much of an improvement. Please see our [FAQ on asking questions](https://codereview.meta.stackexchange.com/questions/2436/how-to-get-the-best-value-out-of-code-review-asking-questions)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T23:57:06.950", "Id": "472498", "Score": "1", "body": "Instead of concatenating, using the `.=` operator, it is more memory efficient to put the parts into an array, like `$html = []; $html[] = \"...\";` and at the end concatenate it: `$result = implode($html);`" } ]
[ { "body": "<p>Use a template engine like Twig, Plates or Blade.</p>\n\n<p>You should have base layouts, partials and templates.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T00:05:54.050", "Id": "240472", "ParentId": "240213", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T16:28:13.837", "Id": "240213", "Score": "0", "Tags": [ "php", "drupal" ], "Title": "concatenation of HTML from return functions" }
240213
<p>We have to reverse <code>char[]</code> using recursion.</p> <ul> <li>Input: <code>["H","a","n","n","a","h"]</code></li> <li>Output: <code>["h","a","n","n","a","H"]</code></li> </ul> <pre><code>package codeMonk; public class RevereseString { public char[] reverseStr(char[] reversedString, int startIndex , int lastIndex, int midIndex) { // Base Condition if(startIndex &gt; midIndex || midIndex &gt;= lastIndex){ return reversedString; } else { char storeChar = reversedString[startIndex]; reversedString[startIndex] = reversedString[lastIndex -1]; reversedString[lastIndex -1 ] = storeChar; return reverseStr(reversedString, ++startIndex , --lastIndex, midIndex); } } public static void main(String[] args) { char[] oldArray = {'A',' ','m','a','n',',',' ','a',' ','p','l','a','n',',',' ','a',' ','c','a','n','a','l',':',' ','P','a','n','a','m','a'}; int midIndex = 0 + (oldArray.length - 0)/2 ; RevereseString reverseStr = new RevereseString(); char [] newArray = reverseStr.reverseStr(oldArray, 0 , oldArray.length, midIndex); for(char ch : newArray) { System.out.print(ch +" "); } } } </code></pre> <p>This code works fine, but how can I improve it and reduce the lines of code?</p>
[]
[ { "body": "<p>You are not using any stored data in the <code>RevereseString</code> [sic] object, so you do not actually need to create the object. Changing <code>reverseStr()</code> to a <code>static</code> method, (optionally <code>private</code> as well) and you can remove <code>RevereseString reverseStr = new RevereseString();</code> to save one line of code.</p>\n\n<p>There is no need for a <code>midIndex</code>. You just need to reverse characters until the <code>startIndex</code> and <code>lastIndex</code> meet or cross. Thus you can remove <code>int midIndex = 0 + (oldArray.length - 0)/2 ;</code> and save another line of code.</p>\n\n<p>Finally, you are not returning a new array; you are returning the original <code>oldArray</code> and assigning that object to <code>newArray</code>. In other words, as <code>main()</code> finishes, <code>oldArray == newArray</code> is <code>true</code>. You have reversed the <code>oldArray</code> in place; there is no need for a return value from <code>reverseStr()</code>, so you can eliminate at least another two lines of code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T17:35:04.587", "Id": "240217", "ParentId": "240216", "Score": "4" } } ]
{ "AcceptedAnswerId": "240217", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T17:08:47.393", "Id": "240216", "Score": "4", "Tags": [ "java", "memory-optimization" ], "Title": "Reverse String : Recursion" }
240216
<p>attaching my try on implementing simple naive-bayes classifier for sentiment analysis as part of learning clojure and using functional programming on ML algorithms.</p> <p>I tried to invest more time in code readability, functional-operations &amp; mindset rather than efficiency (there are clearly parts in BoW creation which can be optimized), but would like to know if there are any logic that can be optimized and mostly <strong>get feedback on the clojure-style</strong> and code-test design.</p> <p>the algorithm was <a href="https://web.stanford.edu/~jurafsky/slp3/slides/7_Sent.pdf" rel="nofollow noreferrer">originally</a> written in imperative language, and I made my own interpretation of it. and it main points of training the data:</p> <ol> <li>generating bag of words (frequencies of tokens of a txt file)</li> <li>calculate prior = P(c) = num-of-class-labeled-documents/total-num-of-documents</li> <li>features is existence of a word in documents bow, so we compute the fraction of times each word appears among all words in all documents of specific-class.</li> <li>ignoring unknown words (removing them) </li> <li>applying laplace-smoothing</li> </ol> <p><a href="https://i.stack.imgur.com/NPigFm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NPigFm.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/lZ2jLt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lZ2jLt.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/NEDqgm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NEDqgm.png" alt="enter image description here"></a></p> <p><strong>tests:</strong></p> <pre><code>(deftest test-train-small (testing "tests train on small data-set, should return priors, likelihoods and vocab (ignored)" ;; to pass &gt; remove Math/log from classifier-class (let [expected {:classes '("neg" "pos") :priors '(3/5 2/5) :likelihoods '({"predictable" 1/17 "no" 1/17 "fun" 1/34}, {"predictable" 1/29 "no" 1/29 "fun" 2/29})}] (is (= expected (-&gt; (train (classes simple-path)) (dissoc :V) (pick-sample :likelihoods ["predictable" "no" "fun"]))))))) (deftest test-prediction-small (testing "tests prediction on small data-set, should return sentiments with neg &gt; pos" ;; to pass &gt; remove Math/log from classifier-class (let [{:keys [priors likelihoods V]} (train (classes simple-path)) test-doc (str simple-path "test/a") expected [(float (* 3/5 2/34 2/34 1/34)) (float (* 2/5 1/29 1/29 2/29))]] (is (= (round-decimal expected) (round-decimal (predict test-doc priors likelihoods V))))))) (deftest test-prediction-big (testing "tests prediction on Pang &amp; Lee polarity data-set, should classify correctly pos/neg" (let [{:keys [priors likelihoods V classes]} (train (classes polarity-path)) test1 (str polarity-path "test/a1") test2 (str polarity-path "test/a2") test3-imdb (str polarity-path "test/narcos-mex-pos") test4-imdb (str polarity-path "test/narcos-mex-neg")] (= "pos" (-&gt;&gt; (predict test1 priors likelihoods V) (argmax classes))) (= "neg" (-&gt;&gt; (predict test2 priors likelihoods V) (argmax classes))) (= "pos" (-&gt;&gt; (predict test3-imdb priors likelihoods V) (argmax classes))) (= "neg" (-&gt;&gt; (predict test4-imdb priors likelihoods V) (argmax classes)))))) </code></pre> <p><strong>classifier ns:</strong></p> <pre><code>; ============================================================ ;; utils (defn vocab [bows] (-&gt;&gt; bows (reduce (fn [s1 s2] (set/union s1 (set (keys s2)))) #{}))) (defn priors [classes] (let [num-files (map (fn [p] (-&gt; p (io/file) (.listFiles) (count))) classes)] (map #(Math/log (/ %1 (reduce + num-files))) num-files))) (defn likelihood [bow w words-count voc-count] {w (Math/log (/ ((fnil inc 0) (get bow w)) (+ words-count voc-count)))}) (defn likelihoods [bows V] (map #(reduce (fn [m w] (merge m (likelihood % w (reduce + (vals %)) (count V)))) {} V) bows)) ; ============================================================ ;; API (defn train [classes] (let [priors (priors classes) bows (map tokenizer/bow-dir classes) V (vocab bows) likelihoods (likelihoods bows V)] {:V V :classes (map #(last (str/split % #"/")) classes) :priors priors :likelihoods likelihoods})) (defn predict [test-doc priors likelihoods V] (let [words (with-open [rdr (io/reader test-doc)] (reduce (fn [words line] (concat words (-&gt;&gt; line (tokenizer/tokenize) (filter #(contains? V %))))) '() (line-seq rdr)))] (map (fn [pr lh] (reduce (fn [s w] (+ (float s) (float (get lh w)))) pr words)) priors likelihoods))) ; ============================================================ </code></pre> <p><strong>tokenizer ns:</strong></p> <pre><code>; ============================================================ ;; utils (defn tokenize [text] (as-&gt; text t (s/trim t) (filter #(or (Character/isSpace %) (Character/isLetterOrDigit ^Character %)) t) (apply str t) (s/lower-case t) (s/split t #"\s+") (into [] t))) ; ============================================================ ;; API (defn bow [s] (-&gt; s (tokenize) (frequencies))) (defn bow-file [file] (with-open [rdr (io/reader file)] (reduce (fn [m l] (as-&gt; l line (bow line) (merge-with + m line))) {} (line-seq rdr)))) (defn bow-dir [path] (as-&gt; path p (io/file p) (file-seq p) (reduce (fn [m f] (merge-with + m (bow-file f))) {} (rest p)))) ; ========================================== </code></pre> <p><a href="https://github.com/akotek/vicarious" rel="nofollow noreferrer">full code</a></p>
[]
[ { "body": "<p>This is pretty nice looking code. Just some small suggestions:</p>\n\n<p>You use <code>map</code> quite a bit here. While it certainly has its place, I've found that it's often better to use <a href=\"https://clojuredocs.org/clojure.core/mapv\" rel=\"nofollow noreferrer\"><code>mapv</code></a> instead. <code>map</code> is lazy and returns a <code>LazyList</code>, while <code>mapv</code> is strict and returns a vector.</p>\n\n<p>It's like the difference between a generator expression and a list comprehension in Python. If you need laziness, then good, use the lazy version. Often though, the production of a lazy list has so much overhead that the strict version performs better. Play around with it and see.</p>\n\n<hr>\n\n<pre><code>(reduce + num-files)\n</code></pre>\n\n<p>can also be written as</p>\n\n<pre><code>(apply + num-files)\n</code></pre>\n\n<p><code>+</code> has a var-arg overload that is essentially a reduction. I seem to recall though that the latter has the potential to perform slightly better. Just a heads up.</p>\n\n<hr>\n\n<p>In <code>priors</code>, I'd maybe do a empty check on <code>classes</code> at the beginning. If <code>classes</code> is empty, <code>(/ %1 (reduce + num-files)</code> will cause an exception.</p>\n\n<hr>\n\n<pre><code>((fnil inc 0) (get bow w))\n</code></pre>\n\n<p>This can make use of <code>get</code>'s third argument to default to 0, which gets rid of the need for <code>fnil</code>:</p>\n\n<pre><code>(inc (get bow w 0))\n</code></pre>\n\n<p>I think that reads better.</p>\n\n<hr>\n\n<p>In <code>tokenize</code>, you're using <code>as-&gt;</code> because of a single call at the bottom that needs the threaded argument in the first position instead of the last. Honestly, I think I'd just adjust that one call instead of using <code>as-&gt;</code> instead of <code>-&gt;&gt;</code>:</p>\n\n<pre><code>(defn tokenize [text]\n (-&gt;&gt; text\n (s/trim)\n (filter #(or (Character/isSpace %) (Character/isLetterOrDigit ^Character %)))\n (apply str)\n (s/lower-case)\n (#(s/split % #\"\\s+\")) ; Wrapped in in another function\n (into [])))\n</code></pre>\n\n<p>That's just a personal suggestion. I find that <code>as-&gt;</code> rarely helps readability, and most times that it's needed, it's the wrong solution anyways.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T22:00:10.983", "Id": "240233", "ParentId": "240218", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T17:56:39.057", "Id": "240218", "Score": "2", "Tags": [ "algorithm", "functional-programming", "clojure" ], "Title": "naive bayes sentiment analysis classifier in clojure" }
240218
<p>In my application we have four inputs radio controls and on the load the value is checked to true. When the user select another radio and then save the form I want to get the new value. I am using the find class but then I need to use checked[0]. Is there a better way to do this?</p> <p>JS</p> <pre><code>$(&quot;#form&quot;).submit(function (event) { event.preventDefault(); console.log('free-text-form'); var sortOrder = $(this).data('sortorder'); console.log(sortOrder); var form = $(this); console.log('Processing Current Check'); var checked = form.find(&quot;.radio-Class:checked&quot;); var currentChecked = checked[0]; console.log(currentChecked); console.log(currentChecked.value); if (checkedRegRef.length == 1) { var NewId = currentChecked.value; console.log(NewId); } }); </code></pre> <p>Working Example <a href="https://jsfiddle.net/tjmcdevitt/vh9n5srL/87/" rel="nofollow noreferrer">https://jsfiddle.net/tjmcdevitt/vh9n5srL/87/</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T19:05:22.590", "Id": "471157", "Score": "0", "body": "Error in console: `Uncaught ReferenceError: checkedRegRef is not defined`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T12:48:56.840", "Id": "471242", "Score": "0", "body": "Sorry I corrected it" } ]
[ { "body": "<p>With <code>checked[0]</code> you are getting a <a href=\"https://learn.jquery.com/using-jquery-core/faq/how-do-i-pull-a-native-dom-element-from-a-jquery-object/\" rel=\"nofollow noreferrer\">reference to the actual DOM element</a> (instead of the jQuery object) but that is unnecessary in your case since jQuery provides a <a href=\"https://api.jquery.com/val/\" rel=\"nofollow noreferrer\">val()</a> method, which returns the current value of the first element in the set of matched elements. So in your case, you could simply do: </p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var checkedVal = form.find(\".radio-Class:checked\").val();\n</code></pre>\n\n<p>A better way to get the selected value as pointed out <a href=\"https://stackoverflow.com/a/596369/3528132\">here</a> by <a href=\"https://stackoverflow.com/users/56018/peter-j\">@Peter J</a> is to use the <code>input[name=radioName]:checked</code> selector. Selecting through <code>name</code> attributes ensures that you select the desired radio group since these are meant to be unique. For better performance, you can pass in the form <code>id</code> as the second argument inside the selector method, which is used as a <a href=\"https://api.jquery.com/jquery()/#jQuery-selector-context\" rel=\"nofollow noreferrer\">context</a> here (this is same as if you would use <code>$(\"#form\").find(\"input[name=radioName]:checked\")</code>), here is the refactored code:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(\"#form\").submit(function(event) {\n var $formEl = $(this);\n var $labelEl = $formEl.find('#label1');\n var radioVal = $('input[name=RegimenReferences]:checked', $formEl).val();\n\n event.preventDefault();\n $labelEl.text(radioVal);\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n background: #20262E;\n padding: 20px;\n font-family: Helvetica;\n}\n\n#form {\n background: #fff;\n border-radius: 4px;\n padding: 20px;\n font-size: 25px;\n text-align: center;\n transition: all 0.2s;\n margin: 0 auto;\n width: 300px;\n}\n\nbutton {\n background: #0084ff;\n border: none;\n border-radius: 5px;\n padding: 8px 14px;\n font-size: 15px;\n color: #fff;\n}\n\n#banner-message.alt {\n background: #0084ff;\n color: #fff;\n margin-top: 40px;\n width: 200px;\n}\n\n#banner-message.alt button {\n background: #fff;\n color: #000;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;form id=\"form\" class=\"form-horizontal\" data-sortorder=\"1\"&gt;\n &lt;p&gt;Update Values&lt;/p&gt;\n &lt;label id=\"label1\" type=\"text\"&gt;1&lt;/label&gt;\n &lt;div&gt;\n &lt;label for=\"radio1\"&gt;\n &lt;input type=\"radio\" id=\"radio1\" name=\"RegimenReferences\" value=\"1\" class=\"radio-Class\" checked='true'&gt;\n (a) aaaaaa\n &lt;/label&gt;\n &lt;/div&gt;\n &lt;div&gt;\n &lt;label for=\"radio2\"&gt;\n &lt;input type=\"radio\" id=\"radio2\" name=\"RegimenReferences\" value=\"2\" class=\"radio-Class\"&gt;\n (b) bbbbbb\n &lt;/label&gt;\n &lt;/div&gt;\n &lt;div&gt;\n &lt;label for=\"radio3\"&gt;\n &lt;input type=\"radio\" id=\"radio3\" name=\"RegimenReferences\" value=\"3\" class=\"radio-Class\"&gt;\n (c) cccccc\n &lt;/label&gt;\n &lt;/div&gt;\n &lt;div&gt;\n &lt;label for=\"radio4\"&gt;\n &lt;input type=\"radio\" id=\"radio4\" name=\"RegimenReferences\" value=\"4\" class=\"radio-Class\"&gt;\n (c) cccccc\n &lt;/label&gt;\n &lt;/div&gt;\n &lt;div class=\"text-center\"&gt;\n &lt;button type=\"submit\" class=\"btn btn-primary modal-submit-btn\"&gt;Save&lt;/button&gt;\n &lt;button type=\"button\" class=\"btn btn-default modal-close-btn\" data-dismiss=\"modal\"&gt;Close&lt;/button&gt;\n &lt;/div&gt;\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><strong>Edit 1:</strong>\nSince you already got the form selected you can pass that as the context therefore you don't need the form <code>id</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T18:26:42.400", "Id": "240458", "ParentId": "240219", "Score": "3" } }, { "body": "<h2>Your question</h2>\n\n<blockquote>\n <p>I am using the find class but then I need to use checked[0] is there a better way to do this?</p>\n</blockquote>\n\n<p>As was already answered, the <a href=\"https://api.jquery.com/val\" rel=\"nofollow noreferrer\"><code>val()</code></a> method can be used to get the value of the first element matched in the collection. Additionally <a href=\"https://api.jquery.com/eq/\" rel=\"nofollow noreferrer\"><code>.eq()</code></a> could be used to get a reference to the first element if necessary.</p>\n\n<p>The <a href=\"https://stackoverflow.com/a/18043478/1575353\">accepted answer to <em>In jQuery, how do I get the value of a radio button when they all have the same name?</em></a> mentions both the jQuery <code>.val()</code> method, as well as a vanilla Javascript technique. </p>\n\n<blockquote>\n <p>Because this answer keeps getting a lot of attention, I'll also include a vanilla JavaScript snippet.</p>\n</blockquote>\n\n<p>It is wise to consider whether you really need jQuery on your page. Take a look at <a href=\"http://youmightnotneedjquery.com/\" rel=\"nofollow noreferrer\">youmightnotneedjquery.com/</a> (and also <a href=\"https://ilikekillnerds.com/2015/02/stop-writing-slow-javascript/\" rel=\"nofollow noreferrer\">this article</a>). If you decide to eliminate it, you could just access the form elements via <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements\" rel=\"nofollow noreferrer\"><code>HtmlFormElement.elements</code></a> and the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/forms\" rel=\"nofollow noreferrer\"><code>forms</code> property</a>.</p>\n\n<pre><code>const label = document.getElementById('label1');\ndocument.forms[0].addEventListener('submit', event =&gt; {\n event.preventDefault();\n label.innerHTML = document.forms[0].elements.RegimenReferences.value;\n});\n</code></pre>\n\n<p>With the approach above there are no function calls to query the DOM for the elements in the form submission callback handler. This may not be much faster but would require fewer function calls.</p>\n\n<h2>Other review points</h2>\n\n<ul>\n<li><strong>Indentation</strong> is inconsistent - the first line in the callback function is indented with three spaces, then the next line is indented with a tab and a space and then subsequent lines appear to be indented with twelve spaces. It is best to use consistent indentation for the sake of readability. </li>\n<li><strong>DOM lookups aren't cheap</strong> so it is wise to store those in variables - e.g. <code>const label</code> as defined in the snippet above.</li>\n<li>There is an <strong>Unused Variable</strong>: <code>sortOrder</code> (other than being logged to the console)</li>\n<li><p>It is wise to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity\" rel=\"nofollow noreferrer\"><strong>strict equality</strong> comparisons</a> unless there is a chance one operand might not have the same type. For example - instead of:</p>\n\n<blockquote>\n<pre><code>if (checkedRegRef.length == 1) {\n</code></pre>\n</blockquote>\n\n<p>use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity\" rel=\"nofollow noreferrer\"><code>===</code></a></p>\n\n<pre><code>if (checkedRegRef.length === 1) {\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T15:46:34.407", "Id": "471891", "Score": "0", "body": "Just out of curiosity and this might not be the best example, but when you say \"DOM lookups aren't cheap so it is wise to store those in variables\", isn't this debatable in this case if the label is intended to only change after the form is submitted? I always assumed that you don't want to store the DOM lookup by default and only if it's worth it. So my thinking here was: \"I have a label which only changes after the user clicks the button, I don't want to bloat the memory until then\". Even this is a very insignificant case, do I raise a valid point ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T15:52:17.670", "Id": "471896", "Score": "1", "body": "Yes it is debatable, and depends on various factors like how often the user would likely submit the form. In the \"best case\" scenario the user might only submit the form once or twice, leading to the callback function getting called and consequently the call to `.find()` to lookup the label element. In the \"worst case\" scenario the form might get submitted multiple times, leading to that lookup each time the callback is executed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T05:13:41.740", "Id": "240538", "ParentId": "240219", "Score": "0" } } ]
{ "AcceptedAnswerId": "240458", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T18:10:43.263", "Id": "240219", "Score": "2", "Tags": [ "javascript", "jquery", "event-handling", "form", "dom" ], "Title": "jQuery form.find radio class" }
240219
<p>I am aiming to implement a calculator in an object-oriented way.</p> <p>Here is the solution by using the strategy pattern.</p> <p>Looking forward to some valuable comments.</p> <pre><code>package oopdesign.calculator; public class AdditionStrategy implements CalculationStrategy { @Override public int calculate(int value1, int value2) { return value1 + value2; } } package oopdesign.calculator; public interface CalculationStrategy { int calculate(int value1, int value2); } package oopdesign.calculator; public class Calculator { public static Calculator instance = null; CalculationStrategy calculationStrategy; public void setCalculationStrategy(CalculationStrategy calculationStrategy) { this.calculationStrategy = calculationStrategy; } public static Calculator getInstance(){ if(instance == null){ instance = new Calculator(); } return instance; } public int calculate(int value1, int value2) { return calculationStrategy.calculate(value1, value2); } } package oopdesign.calculator; public class CalculatorMain { public static void main(String[] args) { Calculator c = Calculator.getInstance(); c.setCalculationStrategy(new AdditionStrategy()); System.out.println(c.calculate(5 ,2)); c.setCalculationStrategy(new SubtractionStrategy()); System.out.println(c.calculate(5 ,2)); c.setCalculationStrategy(new MultiplicationStrategy()); System.out.println(c.calculate(5 ,2)); c.setCalculationStrategy(new DivideStrategy()); System.out.println(c.calculate(5 ,2)); } } package oopdesign.calculator; public class DivideStrategy implements CalculationStrategy { @Override public int calculate(int value1, int value2) { return value1 / value2; } } package oopdesign.calculator; public class MultiplicationStrategy implements CalculationStrategy{ @Override public int calculate(int value1, int value2) { return value1 * value2; } } package oopdesign.calculator; public class SubtractionStrategy implements CalculationStrategy { @Override public int calculate(int value1, int value2) { return value1 - value2; } } </code></pre>
[]
[ { "body": "<h3>Review:</h3>\n<p>From extensibility and in pro of having the possibility of including in future versions more operations, it is a good approach. The code is very simple, and it is easy to read so it is very good your design proposal.</p>\n<blockquote>\n<p>The main purpose of applying design patterns is <em>to simplify</em> things, to reach the maximum level of abstraction and allow you to write meaningful code, not just repeat stuff</p>\n</blockquote>\n<p>So, you did good.</p>\n<p>However, there are some observations:</p>\n<pre class=\"lang-java prettyprint-override\"><code>package oopdesign.calculator;\n\n//Singleton is a good approach for this problem\npublic class Calculator {\n\n //By default any object is null\n //Do not put it as public, you have the getInstance method\n private static Calculator instance;\n\n //You are limiting the operations to handle\n CalculationStrategy calculationStrategy;\n\n //This is not a Singleton if you allow the default constructor (its public by default)\n private Calculator() {\n }\n\n public void setCalculationStrategy(CalculationStrategy calculationStrategy) {\n this.calculationStrategy = calculationStrategy;\n }\n\n public static Calculator getInstance() {\n if (instance == null)\n instance = new Calculator();\n return instance;\n }\n\n //You should think about handle the most general data type (this case double)\n public double calculate(double value1, double value2) {\n return calculationStrategy.calculate(value1, value2);\n }\n}\n</code></pre>\n<pre class=\"lang-java prettyprint-override\"><code>package oopdesign.calculator;\n\npublic class CalculatorMain {\n\n public static void main(String[] args) {\n\n Calculator c = Calculator.getInstance();\n\n //There is a problem with it, you need to instanciate the strategies\n //each time you need to use it\n c.setCalculationStrategy(new AdditionStrategy());\n System.out.println(c.calculate(5,2));\n\n //It requires space, plus you are not being efficient by storing\n //there operations (calculation strategies)\n c.setCalculationStrategy(new SubtractionStrategy());\n System.out.println(c.calculate(5,2));\n\n c.setCalculationStrategy(new MultiplicationStrategy());\n System.out.println(c.calculate(5,2));\n\n c.setCalculationStrategy(new DivideStrategy());\n System.out.println(c.calculate(5,2));\n }\n}\n</code></pre>\n<h3>An alternative</h3>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.HashMap;\nimport java.util.Map;\n\npublic class Calculator {\n\n private static Calculator instance;\n\n //search in Constant time (approximately)\n private Map&lt;String, CalculationStrategy&gt; calculationStrategies;\n\n private Calculator() {\n calculationStrategies = new HashMap&lt;&gt;();\n }\n\n public void addCalculationStrategy(String name, CalculationStrategy strategy) {\n calculationStrategies.put(name, strategy);\n }\n\n public static Calculator getInstance() {\n if (instance == null)\n instance = new Calculator();\n return instance;\n }\n\n //double b... means that there may be 0 to n parameters\n //consider that there are unitary operators or functions in a calculator\n public double calculate(String name, double a, double... b) {\n return calculationStrategies.get(name).calculate(a, b);\n }\n}\n</code></pre>\n<pre class=\"lang-java prettyprint-override\"><code>package oopdesign.calculator;\n\npublic class Main {\n\n public static void main(String[] args) {\n Calculator calculator = Calculator.getInstance();\n\n //Use a lambda instead\n calculator.addCalculationStrategy(&quot;+&quot;, (a, b) -&gt; a + b[0]);\n //[b] is taken as an array but is a variadic parameter\n calculator.addCalculationStrategy(&quot;-&quot;, (a, b) -&gt; a - b[0]);\n calculator.addCalculationStrategy(&quot;*&quot;, (a, b) -&gt; a * b[0]);\n calculator.addCalculationStrategy(&quot;/&quot;, (a, b) -&gt; a / b[0]);\n calculator.addCalculationStrategy(&quot;Abs&quot;, (a, b) -&gt; Math.abs(a));\n calculator.addCalculationStrategy(&quot;Cos&quot;, (a, b) -&gt; Math.cos(a));\n calculator.addCalculationStrategy(&quot;Sin&quot;, (a, b) -&gt; Math.sin(a));\n\n System.out.println(calculator.calculate(&quot;+&quot;, 1, 3));\n System.out.println(calculator.calculate(&quot;-&quot;, 1, 3));\n System.out.println(calculator.calculate(&quot;*&quot;, 1, 3));\n System.out.println(calculator.calculate(&quot;/&quot;, 1, 3));\n System.out.println(calculator.calculate(&quot;Abs&quot;, -66));\n System.out.println(calculator.calculate(&quot;Cos&quot;, 75));\n System.out.println(calculator.calculate(&quot;Sin&quot;, 28));\n System.out.println(calculator.calculate(&quot;+&quot;, 666, 777));\n }\n}\n</code></pre>\n<p>About <code>double b...</code> read this post about <a href=\"https://stackoverflow.com/questions/2635229/java-variadic-function-parameters\">Variadic function parameters</a>, as I said, it is a way to have multiple parameters, From 0 To N parameters</p>\n<p>Thanks for reading this answer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T03:30:58.503", "Id": "240243", "ParentId": "240221", "Score": "2" } }, { "body": "<p><strong>Readability and ease of use</strong></p>\n\n<p>I think the calculator should have simple functions : plus, minus, divide, multiple and use the strategy within the calculator. </p>\n\n<p><strong>State</strong></p>\n\n<p>You are setting the operation by a state in the calculator. Change state can lead to weird bugs.</p>\n\n<p>For example what will happen if you call calculator.Calculate without calling setCalculationStategy?</p>\n\n<p><strong>Singleton</strong></p>\n\n<p>I don't understand why the calculator is a singleton? What are the benefits? </p>\n\n<p>Think what will happen if you use it with multiple threads. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T05:56:59.413", "Id": "240253", "ParentId": "240221", "Score": "1" } }, { "body": "<p>I like they way you thought about the problem but it has some downsides..</p>\n<p>(The answer will only focus on the <em>Strategy Design Pattern</em> and ignores the use of the <em>Singleton Pattern</em>)</p>\n<hr />\n<h1>Without the Strategy Pattern</h1>\n<p>Let us compare the design you provide with a different approach:</p>\n<pre class=\"lang-java prettyprint-override\"><code>class Calculator {\n\n int add(int a, int b) {\n return a + b;\n }\n\n int substract(int a, int b) {\n return a - b;\n }\n\n int multiply(int a, int b) {\n return a * b;\n }\n\n int divide(int a, int b) {\n return a / b;\n }\n}\n\nclass Main {\n\n public static void main(String... args) {\n Calculator c = new Calculator();\n\n System.out.println(c.add(5 ,2));\n\n System.out.println(c.substract(5 ,2));\n\n System.out.println(c.multiply(5 ,2));\n\n System.out.println(c.divide(5 ,2));\n }\n\n}\n</code></pre>\n<p>The benefits of the new approach are:</p>\n<ul>\n<li>only 2 instead of 7 classes</li>\n<li>simply usage - no need to change the strategy for each operation</li>\n</ul>\n<p>As you can see the <em>strategy pattern</em> adds to much complexity to this simple problem.</p>\n<h1>Strategy Pattern is not made for this Use Case</h1>\n<p>The benefit of the Strategy Design Pattern is that it <a href=\"https://en.wikipedia.org/wiki/Strategy_pattern#cite_note-1\" rel=\"nofollow noreferrer\">enables selecting an algorithm at runtime</a>.</p>\n<p>But <em>algorithm</em> is not meant to switch between different types of calculations; it is much more about switching between different behaviors for different types of calculators.</p>\n<h1>A Possible Use Case</h1>\n<p>Imagine you want to sell your calculator and a potential customer has a 7-day trial period before he has to buy it. During the trial period the customer can only use <code>add</code> and <code>subtract</code>. If the customer does not buy the calculator after the trial period, no methods can be used.</p>\n<p>For this problem presentation we could have three types of calculators:</p>\n<ul>\n<li>trail-calculator</li>\n<li>purchased calculator</li>\n<li>unpurchased calculator</li>\n</ul>\n<h2>First Try without the Strategy Pattern</h2>\n<p>We could create 3 classes (to make it easy, I'll just demonstrate with <code>add</code>) and then we'll see the downside:</p>\n<pre class=\"lang-java prettyprint-override\"><code>class PurchasedCalculator {\n\n int add(int a, int b) {\n return a + b;\n }\n\n}\n\nclass UnpurchasedCalculator {\n\n int add(int a, int b) {\n throw NotPurchasedExecption()\n }\n\n}\n\nclass TrialCalculator {\n \n int add(int a, int b) {\n return a + b;\n }\n\n int multiply(int a, int b) {\n throw NotPurchasedExecption();\n }\n \n}\n\n</code></pre>\n<p>The downside of this approach is that we have many code duplication every where.</p>\n<h2>Second Try with the Strategy Pattern</h2>\n<p>To avoid code duplication and the flexibility not to create a new class for each calculator type, we can use the <em>Strategy Pattern</em>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>class Calculator {\n /* ... */\n \n Calculator(CalculationStrategy additionStrategy,\n CalculationStrategy substractionStrategy,\n CalculationStrategy multiplicationStrategy,\n CalculationStrategy dividitionStrategy) {\n this.additionStrategy = additionStrategy;\n this.substractionStrategy = substractionStrategy;\n this.multiplicationStrategy = multiplicationStrategy;\n this.divideStrategy = divideStrategy;\n }\n\n int add(int a, int b) {\n return additionStrategy.calculate(a, b);\n }\n\n /* ... */\n}\n</code></pre>\n<p>We can easy create different calculator types:</p>\n<pre><code>class Main {\n\n public static void main(String... args) {\n\n Calculator trial = new Calculator(new AdditionStrategy(), \n new SubstractionStrategy(),\n new NotPurchasedStrategy(),\n new NotPurchasedStrategy());\n\n Calculator purchased = new Calculator(new AdditionStrategy(), \n new SubstractionStrategy(),\n new MultiplicationStrategy(),\n new DividitionStrategy());\n\n Calculator unpurchased = new Calculator(new NotPurchasedStrategy(), \n new NotPurchasedStrategy(),\n new NotPurchasedStrategy(),\n new NotPurchasedStrategy());\n\n }\n\n}\n</code></pre>\n<p>Or modify the behavior at runtime - for instance the customer did not pay his subscription:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Calculator purchased = new Calculator(new AdditionStrategy(), \n new SubstractionStrategy(),\n new MultiplicationStrategy(),\n new DividitionStrategy());\n\npurchased.setAdditionStrategy(new NotPurchasedStrategy());\n/*...*/\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T11:45:53.507", "Id": "240555", "ParentId": "240221", "Score": "1" } } ]
{ "AcceptedAnswerId": "240243", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T18:47:41.173", "Id": "240221", "Score": "3", "Tags": [ "java", "object-oriented", "design-patterns", "strategy-pattern" ], "Title": "Calculator Object Oriented Design" }
240221
<p>Problem: You are given a board containing lower-case letters and a word that you have to form. You can only take the letters from the front or the back, hence you have to rotate the board left or right. You have to use the <strong>greedy</strong> approach (choose which rotation lets you take the letter the fastest on each turn) and get a list of rotations necessary to get the word.</p> <p>Example:</p> <pre><code>Initial Condition: Board: a g t c f word: cat Rotate Right -&gt; f a g t c Take c -&gt; f a g t Rotate Left -&gt; a g t f Take a -&gt; g t f etc </code></pre> <p>Code:</p> <pre><code> public static List&lt;Move&gt; SolveLetterBoard(List&lt;char&gt; board, string word) { List&lt;Move&gt; result = new List&lt;Move&gt;(); for (int i = 0; i &lt; word.Length; i++) { char curChar = word[i]; int leftPosition = board.IndexOf(curChar); int rightPosition = board.LastIndexOf(curChar); int location = 0; int where = leftPosition; Direction howToSpin = Direction.Left; //Is it easier to spin to the right or to the left if (board.Count - rightPosition &lt;= leftPosition) { where = board.Count - rightPosition - 1; location = board.Count - 1; howToSpin = Direction.Right; } Move curMove = new Move(howToSpin); for (int j = 0; j &lt; where; j++) { result.Add(curMove); //Spin the board char temp = board[location]; board.RemoveAt(location); board.Insert(board.Count - location, temp); } //Remove the letter curMove = new Move(howToSpin, curChar); board.RemoveAt(location); result.Add(curMove); } return result; } </code></pre> <p>The code works, but I was told by the interviewer that the code "Your final code showed some lack of best practices", without any elaboration. Could someone please advise what I did wrong.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T20:17:08.670", "Id": "471161", "Score": "0", "body": "Yes, it is C#. I modified the question and included sample input/output." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T03:37:44.190", "Id": "471184", "Score": "0", "body": "Please post the code of Move" } ]
[ { "body": "<p><strong>Single responsibility</strong> </p>\n\n<p>You represent the board as list but the board have specific actions that can be done: rotate left, rotate right, take from left, take from right. </p>\n\n<p>I suggest creating a class with the above functions. </p>\n\n<p><strong>Separate to functions</strong></p>\n\n<p>You are doing few things in Solve: finding the char, rotate the board, take the char from the board. Separate each to a function. </p>\n\n<p>Hint: look at your comments</p>\n\n<p>My advice is, when writing code, to write kind of pseodo code for the \"main\" function. Only when you finish it start implementing the missing functions. </p>\n\n<p><strong>For loop</strong></p>\n\n<p>You can replace the for loop on the word to foreach. </p>\n\n<p><strong>Static</strong></p>\n\n<p>You post only static method. In c# you must have a class so create a class with non static method. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T07:41:48.833", "Id": "471204", "Score": "0", "body": "Makes sense, Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T03:59:04.777", "Id": "240246", "ParentId": "240223", "Score": "2" } }, { "body": "<p>Overall I'd consider your approach to be \"procedural\" rather than object-oriented, which might have contributed to the feedback about \"lack of best practices\"</p>\n\n<p>I agree with Shanif that it would be best to create a class with different methods and avoid <code>static</code>. </p>\n\n<p>Below is an example of the object-oriented approach. </p>\n\n<p>Under the principle of encapsulation I wondered, \"Should the Board expose its inner workings of how it generates the moves?\" I decided no, and kept the Board's \"calculation\" methods private. </p>\n\n<p>When I first posted this answer I knew that the various moves had enough in common to be candidates for inheritance. And, I got around to implementing it. Now the <code>Move</code> family of classes all derive from an abstract base class.</p>\n\n<p>I also added the <code>Solution</code> class to capture the steps and help output them at the end.</p>\n\n<p>Admittedly, this object model might be \"overkill\" for an app of this size. But, I was more interested in modeling the domain than in outputting the results as tersely as possible. </p>\n\n<p>Despite its verbosity in meeting the currently-modest requirements, this object model provides a foundation upon which the app could grow to any size.</p>\n\n<p>Or, to put it another way... Object-oriented programming is useful for many things. Winning at <a href=\"https://en.wikipedia.org/wiki/Code_golf\" rel=\"nofollow noreferrer\">code golf</a> is not among them.</p>\n\n<p>Here's the output:<br>\n<a href=\"https://i.stack.imgur.com/YiXJ1.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YiXJ1.jpg\" alt=\"output\"></a></p>\n\n<p>And the code: </p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\npublic class App_LetterBoard\n{\n public void Run()\n {\n var board = new Board(\"agtcf\");\n board.Solve(\"cat\");\n board.OutputResult();\n\n Console.WriteLine();\n var board2 = new Board(\"agtcfqwerqweroqiweru\");\n board2.Solve(\"cat\");\n board2.OutputResult();\n }\n}\n\npublic class Board\n{\n private string initial; \n private string target; \n private string current; \n private string result;\n private char next;\n\n public Solution Solution { get; private set; } = new Solution();\n\n public Board(string initial) =&gt; this.initial = initial;\n\n public void Solve(string target)\n {\n this.target = target;\n result = string.Empty;\n current = initial; \n var index = 0;\n\n Solution.Add(new Start(initial));\n\n while (!result.Equals(target))\n { \n next = target[index++];\n var distanceLeft = current.IndexOf(next);\n var distanceRight = current.Length - current.LastIndexOf(next) - 1;\n if (distanceLeft &lt;= distanceRight)\n {\n captureLeft(distanceLeft);\n }\n else\n {\n captureRight(distanceRight);\n };\n\n result = $\"{result}{next}\";\n }\n }\n\n public void OutputResult()\n {\n Console.WriteLine($\"Find -&gt; {target}\");\n Console.WriteLine(Solution.ToString());\n }\n\n private void captureRight(int distance)\n {\n for (var i = 0; i &lt; distance; i++)\n {\n var move = new RotateRight(current);\n Solution.Add(move);\n current = move.After;\n }\n\n var take = new TakeRight(current);\n Solution.Add(take);\n current = take.After;\n }\n\n private void captureLeft(int distance)\n {\n for (var i = 0; i &lt; distance; i++)\n {\n var move = new RotateLeft(current);\n Solution.Add(move);\n current = move.After;\n }\n\n var take = new TakeLeft(current);\n Solution.Add(take);\n current = take.After;\n } \n}\n\npublic class Solution\n{\n public List&lt;Move&gt; Moves { get; private set; } = new List&lt;Move&gt;();\n\n public void Add(Move move) =&gt; Moves.Add(move);\n\n public override string ToString()\n {\n var sb = new StringBuilder();\n sb.AppendLine(string.Join(\"\\n\", Moves.Select(m =&gt; m.ToString())));\n return sb.ToString();\n }\n}\n\npublic abstract class Move\n{\n public abstract string Name { get; }\n\n public string Before { get; private set; }\n\n public string After =&gt; advance();\n\n public Move(string remaining) =&gt; Before = remaining;\n\n public override string ToString() =&gt; $\"{Name} -&gt; {spread(After)}\";\n\n protected abstract string advance();\n\n protected string removeLeft() =&gt; Before.Substring(1);\n\n protected string removeRight() =&gt; Before.Substring(0, Before.Length - 1);\n\n private string spread(string s) =&gt; string.Join(\" \", s.ToArray());\n}\n\npublic class Start : Move\n{\n public override string Name =&gt; \"Start\";\n\n public Start(string current) : base(current) {}\n\n protected override string advance() =&gt; Before;\n}\n\npublic class RotateLeft : Move\n{\n public override string Name =&gt; \"Rotate Left\";\n\n public RotateLeft(string current) : base(current) { }\n\n protected override string advance() =&gt; $\"{removeLeft()}{Before.First()}\";\n}\n\npublic class RotateRight : Move\n{\n public override string Name =&gt; \"Rotate Right\";\n\n public RotateRight(string current) : base(current) { }\n\n protected override string advance() =&gt; $\"{Before.Last()}{removeRight()}\";\n}\n\npublic abstract class Take : Move\n{\n public override string Name =&gt; \"Take\";\n public Take(string current) : base(current) { }\n}\n\npublic class TakeLeft : Take\n{\n public TakeLeft(string current) : base(current) { }\n\n protected override string advance() =&gt; removeLeft();\n}\n\npublic class TakeRight : Take\n{\n public TakeRight(string current) : base(current) { }\n\n protected override string advance() =&gt; removeRight();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T03:17:20.947", "Id": "471449", "Score": "0", "body": "Thank you. That is a great approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T12:28:39.267", "Id": "471482", "Score": "1", "body": "You're welcome, and thanks. Glad to help. I also did another pass on the code to move duplicate expressions into methods." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T22:12:47.967", "Id": "240362", "ParentId": "240223", "Score": "3" } } ]
{ "AcceptedAnswerId": "240246", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T19:45:04.547", "Id": "240223", "Score": "3", "Tags": [ "c#", "interview-questions" ], "Title": "Board Rotation Problem - Best Practices" }
240223
<p>This is my first major web scraping program in python. My code works nonetheless, I'm just not sure if it's the best OOP design. My code is below:</p> <pre><code>from bs4 import BeautifulSoup import requests import argparse import sys class ComicScraper(): # Class ComicScraper for scraping comic books def __init__(self, comic_titles, comic_prices, all_comics): self.comic_titles = comic_titles self.comic_prices = comic_prices self.all_comics = all_comics # url of comicbook site self.url = 'https://leagueofcomicgeeks.com/comics/new-comics/2020/' self.webpage = requests.get(self.url) # HTTP request for url # BeautifulSoup object of webpage self.soup = BeautifulSoup(self.webpage.content, 'html.parser') self.titles = list( map(BeautifulSoup.get_text, self.soup.find_all('div', class_='comic-title'))) self.comicinfo = [x.replace(u'\xa0', u'').strip() for x in list(map(BeautifulSoup.get_text, self.soup.find_all('div', class_='comic-details comic-release'))) ] self.prices = [ prices[-5:] if prices[-5:].startswith('$') else 'No price' for prices in self.comicinfo] def main(self): if len(sys.argv) == 1: print("###### New Comics ######") for title, info in zip(self.titles, self.comicinfo): print(title, '---&gt;', info) if self.all_comics: print("###### New Comics ######") for titles, info in zip(self, titles, self.comicinfo): print(title, '---&gt;', info) if self.comic_titles and self.comic_prices: print("###### New Comics ######") for title, prices in zip(self.titles, self.prices): print(title, '---&gt;', info) if self.comic_titles: for comic_title in self.comic_titles: print(comic_title) if self.comic_prices: for dol_amount in comic_prices: print(dol_amount) if __name__ == '__main__': parser = argparse.ArgumentParser() # Titles of comicbooks i.e "Detective Comics #1" parser.add_argument('-t', '--titles', help='Print comic titles ONLY', dest='titles') # Scrape prices of comic books in order parser.add_argument('-m', '--prices', help='Get comic prices ONLY', dest='prices') parser.add_argument('-a', '--all', help='Get titles, prices, publisher, and descriptions', dest='all_comics', action='store_true') args = parser.parse_args() scraper = ComicScraper(args.titles, args.prices, args.all_comics) scraper.main() </code></pre> <p>I have some doubts about how much instance variables I've used? Would refactoring this code as a bunch of functions be the best way? </p>
[]
[ { "body": "<h2>Bugs</h2>\n\n<p>Lines 32 and 42:</p>\n\n<pre><code> for titles, info in zip(self, titles, self.comicinfo):\n\n\n for dol_amount in comic_prices:\n</code></pre>\n\n<p>both have unresolved variable references - <code>titles</code> and <code>comic_prices</code>.</p>\n\n<h2>Bare class declaration</h2>\n\n<pre><code>class ComicScraper(): # Class ComicScraper for scraping comic books\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>class ComicScraper:\n \"\"\"\n For scraping comic books\n \"\"\"\n</code></pre>\n\n<p>Note the more common format for docstrings used.</p>\n\n<h2>Doing too much in an <code>init</code></h2>\n\n<pre><code>requests.get(self.url)\n</code></pre>\n\n<p>should probably not be done in an <code>__init__</code>. Constructors are usually best to initialize everything that the class will need without \"doing\" too much.</p>\n\n<h2>Argument names</h2>\n\n<p><code>titles</code> doesn't actually accept multiple titles; it only accepts one. Providing the argument twice overwrites the first value. That means that this loop:</p>\n\n<pre><code> for comic_title in self.comic_titles:\n</code></pre>\n\n<p>is actually going to loop through each of the characters in the provided string, which is probably not what you want.</p>\n\n<p>Reading the docs - <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/argparse.html</a> - you probably want <code>action='append'</code>.</p>\n\n<h2>Reaching past <code>argparse</code></h2>\n\n<p>This:</p>\n\n<pre><code> if len(sys.argv) == 1:\n</code></pre>\n\n<p>should not be done. Instead, rely on the output of <code>argparse</code>.</p>\n\n<h2>Suggested</h2>\n\n<p>Here is a re-thought program:</p>\n\n<pre><code>from bs4 import BeautifulSoup, Tag\nfrom datetime import date, datetime\nfrom typing import Iterable\nimport argparse\nimport re\nfrom requests import Session\n\n\nclass Comic:\n # · Apr 8th, 2020 · $7.99\n RELEASE_PAT = re.compile(\n r'^\\s*·\\s*'\n r'(?P&lt;month&gt;\\S+)\\s*'\n r'(?P&lt;day&gt;\\d+)\\w*?,\\s*'\n r'(?P&lt;year&gt;\\d+)\\s*'\n r'(·\\s*\\$(?P&lt;price&gt;[0-9.]+))?\\s*$'\n )\n\n def __init__(self, item: Tag):\n self.id = int(item['id'].split('-')[1])\n sku = item.select_one('.comic-diamond-sku')\n if sku:\n self.sku: str = sku.text.strip()\n else:\n self.sku = None\n\n consensus_head = item.find(name='span', text=re.compile('CONSENSUS:'))\n if consensus_head:\n self.consensus = float(consensus_head.find_next_sibling().strong.text)\n else:\n self.consensus = None\n\n potw_head = item.find(name='span', text=re.compile('POTW'))\n self.pick_of_the_week = float(potw_head.find_next_sibling().text.rstrip('%'))\n\n title_anchor = item.select_one('.comic-title &gt; a')\n self.title: str = title_anchor.text\n self.link = title_anchor['href']\n\n details = item.select_one('.comic-details')\n self.publisher: str = details.strong.text\n\n parts = self.RELEASE_PAT.match(list(details.strings)[2]).groupdict()\n self.pub_date: date = (\n datetime.strptime(\n f'{parts[\"year\"]}-{parts[\"month\"]}-{parts[\"day\"]}',\n '%Y-%b-%d'\n )\n .date()\n )\n price = parts.get('price')\n if price is None:\n self.price = price\n else:\n self.price = float(price)\n\n self.desc: str = list(item.select_one('.comic-description &gt; p').strings)[0]\n\n\nclass ComicScraper:\n URL = 'https://leagueofcomicgeeks.com/'\n\n def __init__(self):\n self.session = Session()\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.session.close()\n\n @staticmethod\n def _parse(content: str) -&gt; Iterable[Comic]:\n soup = BeautifulSoup(content, 'html.parser')\n list_items = soup.select('#comic-list &gt; ul &gt; li')\n return (Comic(li) for li in list_items)\n\n def get_from_page(self) -&gt; Iterable[Comic]:\n with self.session.get(self.URL + 'comics/new-comics') as response:\n response.raise_for_status()\n return self._parse(response.content)\n\n def get_from_xhr(self, req_date: date) -&gt; Iterable[Comic]:\n params = {\n 'addons': 1,\n 'list': 'releases',\n 'list_option': '',\n 'list_refinement': '',\n 'date_type': 'week',\n 'date': f'{req_date:%d/%m/%Y}',\n 'date_end': '',\n 'series_id': '',\n 'user_id': 0,\n 'title': '',\n 'view': 'list',\n 'format[]': (1, 6),\n 'character': '',\n 'order': 'pulls',\n }\n with self.session.get(self.URL + 'comic/get_comics', params=params) as response:\n response.raise_for_status()\n return self._parse(response.json()['list'])\n\n\ndef print_comics(comics: Iterable[Comic]):\n print(f'{\"Title\":40} {\"Publisher\":20} {\"Date\":10} {\"Price\":6}')\n\n for c in comics:\n print(\n f'{c.title[:40]:40} {c.publisher[:20]:20} '\n f'{c.pub_date}', end=' '\n )\n if c.price is not None:\n print(f' ${c.price:5.2f}', end='')\n print()\n\n\ndef main():\n parser = argparse.ArgumentParser()\n # Titles of comicbooks i.e \"Detective Comics #1\"\n parser.add_argument('-t', '--titles', help='Print these comic titles ONLY',\n action='append')\n args = parser.parse_args()\n titles = args.titles and set(args.titles)\n\n with ComicScraper() as scraper:\n comics = scraper.get_from_xhr(date(year=2020, month=3, day=25))\n if titles:\n comics = (c for c in comics if c.title in titles)\n print_comics(comics)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Points:</p>\n\n<ul>\n<li>Your original class is not useful as a class - it's effectively a function; the important stuff to capture in a class is distinct fields on the data you're trying to represent</li>\n<li>You can still class-ify the generator as a class method</li>\n<li>Use type hints</li>\n<li>Use set membership check for titles</li>\n<li>Use a regex to parse the info field</li>\n<li>Pull out price and date as a float and date, respectively; don't leave them stringly-typed</li>\n</ul>\n\n<p>Note the second method to use an XHR backend instead of the web front-end. The return format is awkward - they return rendered HTML as a part of the JSON payload - but the interface is more powerful and the method might be more efficient. I have not done a lot of investigation into what each of those parameters means; to learn more you will probably have to dig around the site using developer tools.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T01:19:22.980", "Id": "471179", "Score": "0", "body": "Thanks for the answer, it’s much appreciated! I just have a few questions: What does “Iterable” do?Which is better parsing with re or BeautifulSoup?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T01:24:28.810", "Id": "471180", "Score": "0", "body": "_What does “Iterable” do?_ It's a type hint that gives a promise for the type to be - literally - an iterable of a certain element type. It does not make promises about the ability to call `len`, or mutability, or durability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T01:25:08.947", "Id": "471181", "Score": "0", "body": "_Which is better parsing with re or BeautifulSoup?_ Generally BS if you can, but sometimes that's not enough and semantic information is mixed into a single string, in which case regexes can help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T01:42:11.530", "Id": "471182", "Score": "0", "body": "Edited for narrower, better-structured use of BS tree navigation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T06:18:21.110", "Id": "471193", "Score": "0", "body": "So, “Iterable” is just a sanity check to make sure that the argument passed is a iterable, am I right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T12:20:14.877", "Id": "471241", "Score": "0", "body": "Basically, yes. However, no runtime checks are performed - it's up to external tools like your IDE." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T18:14:11.620", "Id": "471285", "Score": "0", "body": "If you don't mind, could you explain how the print_comics() function works; I see that there is an f-string but I can't see where the \"Title\", \"Publisher\", \"Date\", and \"Price\" values come from. Likewise, it don't understand the numbers beside those values. Sorry, I don't mean to bombard you with questions, much thanks in advance!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T18:46:15.197", "Id": "471288", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/106566/discussion-between-reinderien-and-practical1)." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T21:35:26.983", "Id": "240231", "ParentId": "240225", "Score": "7" } }, { "body": "<p>Just one small contribution from me: I think your utilization of BeautifulSoup is not optimal. For example this bit of code is wasteful as it does not warrant using the <code>map</code> function:</p>\n\n<pre><code>self.titles = list(\n map(BeautifulSoup.get_text, self.soup.find_all('div', class_='comic-title')))\n</code></pre>\n\n<p>What does the map function do ? From the <a href=\"https://docs.python.org/3/library/functions.html#map\" rel=\"nofollow noreferrer\">documentation</a> (emphasis is mine):</p>\n\n<blockquote>\n <p>map(function, iterable, ...)</p>\n \n <p>Return an iterator that <strong>applies function to every item of iterable</strong>, yielding the results. If additional iterable arguments are\n passed, function must take that many arguments and is applied to the\n items from all iterables in parallel. With multiple iterables, the\n iterator stops when the shortest iterable is exhausted...</p>\n</blockquote>\n\n<p>A more straightforward of getting the same result (and trimming text) would be:</p>\n\n<pre><code>self.titles = [title.get_text().strip() for title in self.soup.find_all('div', class_='comic-title')]\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>self.titles = [title.get_text(strip=True) for title in self.soup.find_all('div', class_='comic-title')]\n</code></pre>\n\n<p>And there is no need to involve <code>BeautifulSoup.get_text</code> either. You've already loaded the soup, once is enough.</p>\n\n<p>Another thing:</p>\n\n<pre><code>self.comicinfo = [x.replace(u'\\xa0', u'').strip()\n for x in list(map(BeautifulSoup.get_text, self.soup.find_all('div', class_='comic-details comic-release')))\n ]\n</code></pre>\n\n<p>Here you are trying to get rid of the <a href=\"https://en.wikipedia.org/wiki/Non-breaking_space\" rel=\"nofollow noreferrer\">non-breaking space</a> <br/>\nAlthough we are dealing we just one pesky character you might encounter more unwanted 'characters' in the future when scraping UTF-8 encoded pages.</p>\n\n<p>Based on several posts like this <a href=\"https://stackoverflow.com/a/58692697/6843158\">one</a> and <a href=\"https://towardsdatascience.com/difference-between-nfd-nfc-nfkd-and-nfkc-explained-with-python-code-e2631f96ae6c\" rel=\"nofollow noreferrer\">this one</a> a possible strategy is to use the <a href=\"https://docs.python.org/3.5/library/unicodedata.html#unicodedata.normalize\" rel=\"nofollow noreferrer\"><code>unicodedata.normalize</code></a> function to derive canonical representations of those strings. Since the closest representation of a non-breaking space is of course a plain space, then we want a plain space.</p>\n\n<p>In short this will give a cleaned-up string that is more usable:</p>\n\n<pre><code>unicodedata.normalize(\"NFKD\", 'Archie Comics·\\xa0 Apr 8th, 2020 \\xa0·\\xa0 $7.99')\n\n# output: 'Archie Comics· Apr 8th, 2020 · $7.99'\n</code></pre>\n\n<p>(and there using the map function makes sense I think)</p>\n\n<p>The cost is importing one more dependency: <code>import unicodedata</code>\nAdmittedly that is not so easy to grasp and even experienced developers are having headaches with processing of Unicode text and character set conversions. But you can't really avoid those issues when doing scraping jobs, they will always torment you.</p>\n\n<p>One more reference on the topic: <a href=\"https://en.wikipedia.org/wiki/Unicode_equivalence\" rel=\"nofollow noreferrer\">Unicode equivalence</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T02:40:01.487", "Id": "240241", "ParentId": "240225", "Score": "3" } } ]
{ "AcceptedAnswerId": "240231", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T20:23:34.163", "Id": "240225", "Score": "5", "Tags": [ "python", "python-3.x", "web-scraping", "http", "beautifulsoup" ], "Title": "OOP Web-scraper w/ Python and BeautifulSoup" }
240225
<p>I've written a function that takes a sequence and check for every item in that sequence whether the current value a selection (obtained with a selection function) is different (or on the first iteration) from the previous computed value and if that's the case (we considered there is a change), then map the current item and returns a new mapped item along the current item.</p> <p>If there is no change the sequence keeps returning the current item and the last mapped item detected due to a change.</p> <pre><code>let differentOrNew option currentValue = match option with | Some value when currentValue &lt;&gt; value -&gt; true | Some _ -&gt; false | None -&gt; true let def&lt;'T&gt; = Unchecked.defaultof&lt;'T&gt; let mapChange selector mapping seq = let mutable previous = None let mutable change = def seq |&gt; Seq.map(fun item -&gt; let currentValue = selection item if differentOrNew previous currentValue then previous &lt;- Some currentValue change &lt;- mapping item item, change) |&gt; Seq.map(fun state -&gt; fst state, snd state) </code></pre> <p>That code works, but it's clearly not the best idiomatic piece of F# code I've ever seen. </p> <p>I am wondering how to get something more "F#-idiomatic".</p>
[]
[ { "body": "<blockquote>\n <p><code>|&gt; Seq.map(fun state -&gt; fst state, snd state)</code></p>\n</blockquote>\n\n<p>I think this last operation is unnecessary as it is a map from <code>'a * 'b</code> to <code>'a * 'b</code> (<code>fst</code> returns the first element in the tuple and <code>snd</code> the second).</p>\n\n<hr>\n\n<p>If you want to get rid of the mutable variables, you can use <code>Seq.mapFold</code> instead:</p>\n\n<pre><code>let mapChange selector mapping seq = \n seq\n |&gt; Seq.mapFold (fun (previous, change) item -&gt;\n let currentValue = selector item\n match differentOrNew previous currentValue with\n | true -&gt; \n let newChange = mapping item\n (item, newChange), (Some currentValue, newChange)\n | false -&gt; \n (item, change), (previous, change)\n ) (None, def)\n |&gt; (fst)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T07:36:51.860", "Id": "471203", "Score": "0", "body": "Yes you're right, I don't remember why I put `|> Seq.map(fun state -> fst state, snd state)`, guess I was a little bit too tired when I posted that =|.\nI only have one issue with mapFold implementations tho, is that it actually relies on `toArray` implementation behind the scene: https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/seq.fs#L1441" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T15:56:50.950", "Id": "471396", "Score": "0", "body": "https://github.com/dotnet/fsharp/issues/7009" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T06:24:30.860", "Id": "471459", "Score": "0", "body": "@KerryPerret: It's maybe a point, but the problem is, that you have to materialize the mapping in order to accumulate the final state. The current implementation do that by first convert the `seq` to an array. See also the first comment by cartermp." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T12:07:41.540", "Id": "471478", "Score": "0", "body": "I'm aware of that. The issues arises when I'm dealing with a big (huge) chunk of data." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T06:11:16.387", "Id": "240255", "ParentId": "240226", "Score": "2" } }, { "body": "<p>I like having a <code>Seq.groupAdjacentBy</code> helper function for this kind of thing. It uses mutation in its own small scope to keep the implementation simple and builds on F#'s own <code>Seq.groupBy</code>. It groups values based on their key according to a key generating function (like your function), but only puts values in the same group if they are adjacent. I like this because it has quite a well defined and understandable meaning so it's easy to re-use elsewhere:</p>\n\n<pre><code>module Seq =\n let groupAdjacentBy f xs =\n let mutable prevKey, i = None, 0\n xs\n |&gt; Seq.groupBy (fun x -&gt;\n let key = f x\n if prevKey &lt;&gt; Some key then\n i &lt;- i + 1\n prevKey &lt;- Some key\n (i, key))\n |&gt; Seq.map (fun ((_, k), v) -&gt; (k, v))\n</code></pre>\n\n<p>Using this, a function like yours becomes fairly simple to write:</p>\n\n<pre><code>let mapChange selector mapping xs =\n xs\n |&gt; Seq.groupAdjacentBy selector\n |&gt; Seq.collect (fun (_, values) -&gt;\n let values = values |&gt; Seq.toArray\n let mapped = mapping values.[0]\n seq {\n for x in values do\n x, mapped })\n\nlet isEven x = x % 2 = 0\n\nmapChange isEven string [1; 3; 2; 3] // seq [(1, \"1\"); (3, \"1\"); (2, \"2\"); (3, \"3\")]\n</code></pre>\n\n<p>Note that this uses \"unsafe\" access of the first item in an array, which would throw an exception for an empty array, but we know that any groups created by the grouping function must have at least one item (just like F#'s <code>Seq.groupBy</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T15:56:16.653", "Id": "471395", "Score": "0", "body": "nice! Thanks a ton!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T16:41:11.237", "Id": "471402", "Score": "0", "body": "One downside of the implementation is the `Seq.groupby` which may take a good chunk of memory if there is a lot data coming in." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T13:25:21.103", "Id": "471490", "Score": "0", "body": "@KerryPerret I hadn't considered that implicit requirement of laziness. Previously I had assumed that `Seq.groupBy` was lazy and didn't evaluate the whole sequence but I've realised it can't be, because it can't know the contents of the first group without checking all of the elements. However, `Seq.groupByAdjacent` could potentially be lazy but it would need to be implemented from scratch without using `Seq.groupBy`. I may do this some time..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T13:06:34.773", "Id": "240335", "ParentId": "240226", "Score": "2" } }, { "body": "<p>I ended up doing something like that:</p>\n\n<pre><code>let def&lt;'T&gt; =\n Unchecked.defaultof&lt;'T&gt;\n\nmodule Seq =\n\n let mapbi mapping source =\n source\n |&gt; Seq.scan(fun state item -&gt; fst state + 1I, item) (-1I, def)\n |&gt; Seq.skip(1)\n |&gt; Seq.map(fun (bi, item) -&gt; mapping bi item)\n\n let mapChange selector mapping source =\n source\n |&gt; mapbi (fun bi item -&gt; bi, item)\n |&gt; Seq.scan(fun (previousSelection, previousMappedItem, _) (bi, item) -&gt;\n if bi = 0I then\n (selector item, mapping item, item)\n else\n let currentSelection = selector item\n let mappedItem = mapping item\n if previousSelection &lt;&gt; currentSelection then\n (currentSelection, mappedItem, item)\n else\n (previousSelection, previousMappedItem, item)\n ) (def, def, def)\n |&gt; Seq.skip 1\n |&gt; Seq.map(fun (_, mappedItem, item) -&gt; mappedItem, item)\n\n// and its AsyncSeq counterpart\nmodule AsyncSeq =\n\n let mapbi mapping source =\n source\n |&gt; AsyncSeq.scan(fun state item -&gt; fst state + 1I, item) (-1I, def)\n |&gt; AsyncSeq.skip(1)\n |&gt; AsyncSeq.map(fun (bi, item) -&gt; mapping bi item)\n\n let mapChange selector mapping source =\n source\n |&gt; mapbi (fun bi item -&gt; bi, item)\n |&gt; AsyncSeq.scan(fun (previousSelection, previousMappedItem, _) (bi, item) -&gt;\n if bi = 0I then\n (selector item, mapping item, item)\n else\n let currentSelection = selector item\n let mappedItem = mapping item\n if previousSelection &lt;&gt; currentSelection then\n (currentSelection, mappedItem, item)\n else\n (previousSelection, previousMappedItem, item)\n ) (def, def, def)\n |&gt; AsyncSeq.skip 1\n |&gt; AsyncSeq.map(fun (_, mappedItem, item) -&gt; mappedItem, item)\n</code></pre>\n\n<p>(Dummy) Example:</p>\n\n<pre><code>[&lt;EntryPoint&gt;]\nlet main _ =\n Seq.replicate 4 [1 .. 3]\n |&gt; Seq.mapi(fun i s -&gt;\n s |&gt; Seq.map (fun item -&gt; {| SetIndex = i; RecordIndex = item |} ))\n |&gt; Seq.concat\n |&gt; AsyncSeq.ofSeq\n |&gt; AsyncSeq.mapChange\n (fun item -&gt; item.SetIndex)\n (fun item -&gt; List.init (item.SetIndex + 1) (fun _ -&gt; item.SetIndex))\n |&gt; AsyncSeq.iterAsync(fun (mappedItem, item) -&gt;\n async { printfn \"%A: %A\" item mappedItem })\n |&gt; Async.RunSynchronously\n |&gt; ignore\n 0\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>{ RecordIndex = 1\n SetIndex = 0 }: [0]\n{ RecordIndex = 2\n SetIndex = 0 }: [0]\n{ RecordIndex = 3\n SetIndex = 0 }: [0]\n{ RecordIndex = 1\n SetIndex = 1 }: [1; 1]\n{ RecordIndex = 2\n SetIndex = 1 }: [1; 1]\n{ RecordIndex = 3\n SetIndex = 1 }: [1; 1]\n{ RecordIndex = 1\n SetIndex = 2 }: [2; 2; 2]\n{ RecordIndex = 2\n SetIndex = 2 }: [2; 2; 2]\n{ RecordIndex = 3\n SetIndex = 2 }: [2; 2; 2]\n{ RecordIndex = 1\n SetIndex = 3 }: [3; 3; 3; 3]\n{ RecordIndex = 2\n SetIndex = 3 }: [3; 3; 3; 3]\n{ RecordIndex = 3\n SetIndex = 3 }: [3; 3; 3; 3]\n</code></pre>\n\n<p>Two things that are more idiomatic that my initial piece of code: </p>\n\n<ul>\n<li>No mutable</li>\n<li>Still work even if the initial sequence is empty</li>\n<li>Still \"Stream\" everything => memory allocation over long sequence is roughly constant</li>\n</ul>\n\n<p>Not fully satisfied, still kinda too cluttered =|</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T13:42:35.300", "Id": "471491", "Score": "0", "body": "I believe you can write the `Seq.mapChange` using `AsyncSeq.mapChange` instead of duplicating the code: `source |> AsyncSeq.ofSeq |> AsyncSeq.mapChange selector mapping |> AsyncSeq.toBlockingSeq`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T13:53:14.253", "Id": "471492", "Score": "0", "body": "The problem is the underlying implementation of `toBlockingSeq`.\nTrue, it's actually what I've done in my code. Will update my answer. Thanks for pointing this out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T10:47:12.053", "Id": "471761", "Score": "0", "body": "I'm not sure why that's a problem here. If you know the `AsyncSeq` doesn't contain any asynchronous work then you know you're not actually blocking threads." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T11:26:50.110", "Id": "471767", "Score": "0", "body": "Not saying it's an actual problem here.\nMy point is that it's also pretty cool to have an implementation which is as agnostic as possible so that if someone need to have some async operations it can be useful too." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T16:17:51.923", "Id": "240348", "ParentId": "240226", "Score": "1" } } ]
{ "AcceptedAnswerId": "240348", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T20:46:23.800", "Id": "240226", "Score": "3", "Tags": [ "f#", ".net-core" ], "Title": "Idiomatic F# for iterating a seq and mapping whenever changes occur on a given selection" }
240226
<p>The code reads in integer array from user input and builds a minimum heap via an iterative scheme. Are there any edge cases in which this approach would fail?</p> <p>For the following test case/command sequence:</p> <pre><code>1 4 3 10 12 6 -1 remove remove print </code></pre> <p>My output is <code>4 6 10 12</code> instead of <code>4 10 6 12</code>, is this an invalid implementation?</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;stdexcept&gt; #include &lt;cmath&gt; int readheap(int* theheap) { std::string num; int val = 0; int size = 0; std::cout &lt;&lt; &quot;Enter the elements of heap&quot; &lt;&lt; std::endl; std::getline(std::cin, num); std::istringstream iss(num); while (iss &gt;&gt; val) { if (val != ' ' &amp;&amp; val &gt; 0){ theheap[size] = val; ++size; } } if(size &lt;= 1) { throw std::runtime_error(&quot;Invalid user input&quot;); } for (int k = 1; k &lt; size; ++k) { if (theheap[k] &gt; theheap[(k - 1) / 2]) { int j = k; while (theheap[j] &gt; theheap[(j - 1) / 2]) { std::swap(theheap[j], theheap[(j - 1) / 2]); j = (j - 1) / 2; } } } for (int k = size - 1; k &gt; 0; --k) { std::swap(theheap[0], theheap[k]); int j = 0, index; do { index = (2 * j + 1); if (theheap[index] &lt; theheap[index + 1] &amp;&amp; index &lt; (k - 1)) ++index; if (theheap[j] &lt; theheap[index] &amp;&amp; index &lt; k) std::swap(theheap[j], theheap[index]); j = index; } while (index &lt; k); } std::cout &lt;&lt; &quot;Size of heap is &quot; &lt;&lt; size &lt;&lt; '\n'; return size; } void heapRemove(int* theheap, int&amp; size) { for(int i=0; i&lt;size-1; ++i){ theheap[i] = theheap[i+1]; } int* x = theheap; x = nullptr; delete x; size--; for (int k = 1; k &lt; size; ++k) { if (theheap[k] &gt; theheap[(k - 1) / 2]) { int j = k; while (theheap[j] &gt; theheap[(j - 1) / 2]) { std::swap(theheap[j], theheap[(j - 1) / 2]); j = (j - 1) / 2; } } } for (int k = size - 1; k &gt; 0; --k) { std::swap(theheap[0], theheap[k]); int j = 0, index; do { index = (2 * j + 1); if (theheap[index] &lt; theheap[index + 1] &amp;&amp; index &lt; (k - 1)) ++index; if (theheap[j] &lt; theheap[index] &amp;&amp; index &lt; k) std::swap(theheap[j], theheap[index]); j = index; } while (index &lt; k); } } void heapPrint(int* theheap, int size) { for (int i = 0; i &lt; size; ++i){ std::cout &lt;&lt; theheap[i] &lt;&lt; ' '; } std::cout &lt;&lt; '\n'; } int main() { int* theheap = new int[10]; int size = readheap(theheap); heapPrint(theheap, size); heapRemove(theheap, size); heapPrint(theheap, size); std::cout &lt;&lt; size &lt;&lt; std::endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T08:43:32.290", "Id": "471217", "Score": "1", "body": "There is this post about converting recursive code to iterative. https://stackoverflow.com/questions/159590/way-to-go-from-recursion-to-iteration. You can convert a known algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T12:08:02.757", "Id": "471240", "Score": "0", "body": "Is a 1-element heap really invalid user input? (well, you asked for edge cases...)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-11T22:52:45.827", "Id": "478400", "Score": "0", "body": "I reversed the change you made to the code in [revision](https://codereview.stackexchange.com/revisions/240232/2) (i.e. `if(size < 1) `). Please do not 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 you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-11T22:54:56.403", "Id": "478401", "Score": "0", "body": "@mypronounismonicareinstate, yes that should be if(size < 1)." } ]
[ { "body": "<h2>Memory over-runs</h2>\n\n<p><code>readheap</code> is non-size-aware, so it's wide open to an overrun error (or even a deliberate overrun attack). Pass in a size, or use a sized data structure like a <code>vector</code>.</p>\n\n<h2>Indentation</h2>\n\n<p>You should fix it up for this line:</p>\n\n<pre><code>for (int k = 1; k &lt; size; ++k) {\n</code></pre>\n\n<h2>Order-of-operations</h2>\n\n<p>Neither of these expressions need parentheses:</p>\n\n<pre><code>index = (2 * j + 1); \n\nindex &lt; (k - 1)\n</code></pre>\n\n<h2>Deleting a null?</h2>\n\n<pre><code>x = nullptr;\ndelete x;\n</code></pre>\n\n<p>Does that actually run without crashing?</p>\n\n<h2>Const arguments</h2>\n\n<pre><code>void heapPrint(int* theheap, int size) {\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>void heapPrint(const int *theheap, int size) {\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-11T23:00:34.897", "Id": "478402", "Score": "0", "body": "The specific problem I'm solving requires the specific function signatures I utilized. No vectors, just pointers to integers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T18:44:19.210", "Id": "240353", "ParentId": "240232", "Score": "2" } }, { "body": "<ol>\n<li>Explicit use of new and delete for memory management is old school and very very prone to memory leaks. Use containers like std::vector or std::array. In current code, you are leaking memory pointed by theheap pointer.</li>\n<li>Function readheap is doing two things. Reading input from cin into array theheap and then converting theheap array into actual heap. Split it into separate functions. ReadInput and Heapify</li>\n<li>To improve code readability, index operation like <code>theheap[(j - 1) / 2]</code> or <code>index = (2 * j + 1)</code> can be encapsulated in GetParent, GetLeftChild, GetRightChild like APIs.</li>\n<li>Heapify in iterative mode can look like below. Please note switching from recursion from iteration shouldn't change code logic. Recursion vs iteration can be seen as embedding difference. </li>\n</ol>\n\n<pre><code> void BuildHeap(std::vector&lt;int&gt;&amp; theHeap)\n {\n for (int i = theHeap.size() / 2; i &gt;= 0; i--)\n {\n Heapify(theHeap, i);\n }\n }\n\n void Heapify(std::vector&lt;int&gt;&amp; theHeap, size_t index)\n {\n // Next three lines (stack and while loop) needed for converting recursion to iteration. If you remove these three lines and add recusrion call in place of callStack.push leaving other code unchanged, you will get recursive version of Heapify. \n std::stack&lt;int&gt; callStack;\n callStack.push(index);\n while (!callStack.empty())\n {\n callStack.pop();\n size_t left = GetLeft(index);\n size_t right = GetRight(index);\n size_t smallest = index;\n if (left &lt; theHeap.size() &amp;&amp; theHeap[left] &lt; theHeap[smallest])\n smallest = left;\n if (right &lt; theHeap.size() &amp;&amp; theHeap[right] &lt; theHeap[smallest])\n smallest = right;\n\n if (smallest != index)\n {\n auto temp = m_buffer[index];\n m_buffer[index] = m_buffer[smallest];\n m_buffer[smallest] = temp;\n callStack.push(smallest); // Line needed for converting recursion to iteration\n }\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T10:00:19.493", "Id": "471609", "Score": "1", "body": "The `std::floor` is unnecessary for integer division." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T10:17:21.743", "Id": "471610", "Score": "0", "body": "@L.F. Yes...my bad..correcting it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-11T22:47:30.573", "Id": "478399", "Score": "0", "body": "The specific problem I'm solving requires the function signatures I utilized. No vectors, just pointers to integers." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T11:42:47.820", "Id": "240386", "ParentId": "240232", "Score": "2" } }, { "body": "<h1>The heapRemove algorithm</h1>\n<p><code>heapRemove</code> appears to remove the root element from the heap. However, it implements some sort of combination of <a href=\"https://en.wikipedia.org/wiki/Binary_heap#Insert\" rel=\"nofollow noreferrer\">&quot;bubble up&quot;</a> (applied to every element) and <a href=\"https://en.wikipedia.org/wiki/Binary_heap#Extract\" rel=\"nofollow noreferrer\">&quot;bubble down&quot;</a> (also applied to every element). That's extreme overkill, and turns what should be an O(log n) operation into an O(n log n) operation - that's not good.</p>\n<p>Maybe the reason your code works that way, is that your solution for removing the root element was shifting every element down by one position. Don't do that, it already costs O(n) time just to do that, and it breaks the heap property to an unncessary degree so it takes a lot of work to restore the heap. The usual (and fast) solution is taking the <em>last</em> element of the heap and drop it into <code>theHeap[0]</code>, then bubble down from the root until the heap property is restored.</p>\n<h1><code>readheap</code></h1>\n<p><code>readheap</code> mixes IO and algorithms, when possible I recommend separating them, and it is possible here. <code>readheap</code> also mixes tons of bubble up and bubble down, which is again overkill. Pick one strategy and use it, not both. Applying bubble up to each element results in an O(n log n) heap construction algorithm, applying bubble down <a href=\"https://en.wikipedia.org/wiki/Binary_heap#Building_a_heap\" rel=\"nofollow noreferrer\">in a particular way</a> can give you an O(n) heap construction algorithm.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T09:25:38.243", "Id": "240434", "ParentId": "240232", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T21:35:30.970", "Id": "240232", "Score": "4", "Tags": [ "c++", "algorithm", "array", "stream", "heap" ], "Title": "Min heap without recursion" }
240232
<p>I made a pagination algorithm but in my opinion it is too complicated and it is quite difficult to be understood. This algorithm should show 5 pages where in the middle is the current page. It should also show two pages before and two pages after the selected page (if these pages exist). </p> <p><a href="https://i.stack.imgur.com/baFTu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/baFTu.png" alt="enter image description here"></a></p> <p>So, I just want to generate the array which is underlined in the above picture.</p> <p>Here is my code:</p> <pre><code>public class Pagination { private int totalPages; private int selectedPage; private int offset; public Pagination() { totalPages = 6; selectedPage = 4; offset = 5; } public static void main(String[] args) { Pagination pagination = new Pagination(); System.out.println(pagination.buildPaginationConditions().toString()); } private List&lt;Integer&gt; buildPaginationConditions() { if (selectedPage &lt;= offset / 2) { return doShowFirstPages(); } return buildPagination(); } private List&lt;Integer&gt; doShowFirstPages() { List&lt;Integer&gt; pagination = new LinkedList&lt;Integer&gt;(); for (int i = 1; i &lt;= offset; i++) { if (totalPages &gt;= i) { pagination.add(i); } } return pagination; } private List&lt;Integer&gt; buildPagination() { List&lt;Integer&gt; pagination = new LinkedList&lt;Integer&gt;(); int delta = offset / 2; // How many pages to left/right int paginationMiddle = (int) Math.ceil((double) offset / 2); for (int i = 1; i &lt;= offset; i++) { if (i &lt; paginationMiddle) { pagination.add(selectedPage - delta); delta--; continue; } if (paginationMiddle == i) { pagination.add(selectedPage); delta = 1; continue; } if (totalPages &gt;= selectedPage + delta) { pagination.add(selectedPage + delta); delta++; continue; } if (selectedPage &gt;= totalPages - 1) { //If it is the last or the penultimate page shift the pages to the right woth 1/2 positions int noOfGapsInPagination = offset - pagination.size(); int temp = new Integer(offset); for (int j = 0; j &lt; noOfGapsInPagination; j++) { pagination.add(j, totalPages - (--temp)); } break; } } return pagination; } } </code></pre> <p>The algorithm works but I want to write that <code>for loop</code> from <code>buildPagination()</code> much more simpler because it looks too complicated now . </p> <p>I know that I can to extract those pices of code from <code>if conditions</code> in smaller methods but it is not going to simplify the code to much. Do you have any suggestions?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T08:26:13.913", "Id": "471212", "Score": "0", "body": "I tried to understand the algorithm but didn't sucseed. Please add more examples, especially the edge cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T08:32:25.020", "Id": "471214", "Score": "0", "body": "I think the solution should be calculating the start and the end of the range. But it is very different from your solution. Am I missing something?" } ]
[ { "body": "<p>the most simple algorithm would be to calculate the start and end indices</p>\n\n<pre><code> // set start index relative to selected \n int start = selectedPage - (offset / 2);\n // adjust for first pages \n start = Math.max(start, 1);\n // set end index relative to start \n int end = start + offset - 1;\n // adjust start and end for last pages \n if (end &gt; totalPages) {\n end = totalPages;\n start = end - offset + 1;\n }\n\n return IntStream.rangeClosed(start, end).boxed()\n .collect(Collectors.toList());\n</code></pre>\n\n<p>as for code review: </p>\n\n<ol>\n<li>method signatures correctly return interface <code>List</code>. however, there are two places where you initialize the list with a concrete implementation. now imagine you would decide that <code>ArrayList</code> is better suited. you need to remember to modify two places. </li>\n<li>while on the subject: don't use <code>LinkedList</code>. it has an extremely narrow use case where it is preferable over <code>ArrayList</code>. this is not one of them. Especially if you initialize the <code>ArrayList</code> with initial size.</li>\n<li>use Java 8 collection stream (if you've learned it) it is more efficient and concise than for loop </li>\n<li>The code does not use java standard indentation. code inside if block should be indented inward.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T10:39:21.273", "Id": "471233", "Score": "0", "body": "Pff, it is much more simpler and it works perfectly. Thank you very much for the advices." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T08:55:33.217", "Id": "240261", "ParentId": "240235", "Score": "2" } } ]
{ "AcceptedAnswerId": "240261", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T22:51:38.650", "Id": "240235", "Score": "2", "Tags": [ "java", "algorithm", "pagination" ], "Title": "Java pagination algorithm" }
240235
<p>I've been using Python for around 3 months and decided to make a simple text adventure game for fun and to exercise a lot of ideas I've been learning about. I've just recently learned about classes and OOP, as well as modules so those are the two features I'm the least sure of. It's mostly a base and has two rooms set up, but I'm pretty proud of it so far as I feel like its fairly readable and has good style (though I admittedly have nothing to compare it with.) So far I have four modules that I've distinguished from each other, mostly for readability. My use of classes is shallow, let me know how I could improve on it! I have two rooms set up so far.</p> <p>Main module: </p> <pre><code> """ This is the main file, it contains the functions for the rooms as well as the startup sequences.""" import actions import room_info as rooms import character_and_items as char """TODO LIST: -Implement save features(Save module?) -Add some spunk into the descriptions, make it fun yet concise!! """ # output def print_frog_title(): print(" ____ ___ __ __ ") print(" / __/______ ___ _ / _ |___/ / _____ ___ / /___ _________ ") print(" / _// __/ _ \/ _ `/ / __ / _ / |/ / -_) _ \/ __/ // / __/ -_)") print("/_/ /_/ \___/\_, / /_/ |_\_,_/|___/\__/_//_/\__/\_,_/_/ \__/ ") print(" /___/ ") # input def check_start(): print_frog_title() print(" A game by Mopi Productions ") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("For a list of commands type 'h', 'help', or '?'") def load_room(room): char.current_room = room room_dict = { "burrow": burrow, "burrow_basement": burrow_basement, "front_of_house": front_of_house } func = room_dict.get(room, lambda: "ERROR") # To be quite frank I don't really understand lambda: ERROR yet func() def burrow(): print("You are in your burrow. The front door is to the north.") while True: action = actions.get_action(rooms.burrow) if action[0] == "mopi": load_room(action[1]) if action == "down": if rooms.burrow.variables["trapdoor_opened"] and "lantern" in char.character_inventory: load_room("burrow_basement") break elif not rooms.burrow.variables["rug_moved"]: print("You cant go that way!") elif rooms.burrow.variables["rug_moved"] and not rooms.burrow.variables["trapdoor_opened"]: print("The trapdoor is shut.") elif "lantern" not in char.character_inventory: print("It's far too dark down there, you should stay up here until you find a light source.") elif action == "north": if rooms.burrow.variables["door_unlocked"]: load_room("front_of_house") else: print("The front door is locked!") elif action in rooms.directions: print("You cant go that way!") elif action[0] == "examine": if action[1] in ("rug", "carpet", "lump"): if not rooms.burrow.variables["rug_moved"]: print("Upon further examination, the 'lump' appears to be handle shaped. You should try moving " "the rug.") else: print("Your beloved family heirloom has been rudely shoved against a wall. What would Aunt Frogatha think?") elif action[1] == "door": print("Your door is locked. You'd unlock it, but you've lost the key.") elif action[1] == "cabinet": if rooms.burrow.variables["cabinet_opened"]: if rooms.burrow.variables["jar_taken"]: print("It's an open cabinet with barren shelves.") else: print("It's an open cabinet with barren shelves excepting a single empty jar.") else: print("It's a closed cabinet where you keep your dishware.") elif action[0] == "move": if action[1] in ("rug", "carpet"): if not rooms.burrow.variables["rug_moved"]: print("You moved the rug, and underneath you found a trapdoor! This isn't a new discovery.") rooms.burrow.variables["rug_moved"] = True else: print("You've already kicked the rug into the corner! Better to not do any more damage.") elif action[0] == "use": if action[1] == "trapdoor" and rooms.burrow.variables["rug_moved"]: print("You opened the trapdoor.") rooms.burrow.variables["trapdoor_opened"] = True elif action[1] == "door": if not rooms.burrow.variables["door_unlocked"] and "key" not in char.character_inventory: print("The door is locked, and you seem to have misplaced your key.") elif not rooms.burrow.variables["door_unlocked"] and "key" in char.character_inventory: print("The door is locked, you should using your key.") else: load_room("burrow_basement") break elif action[0] == "open": if action[1] == "trapdoor" and rooms.burrow.variables["rug_moved"]: print("You opened the trapdoor.") rooms.burrow.variables["trapdoor_opened"] = True elif action[1] == "door": if not rooms.burrow.variables["door_unlocked"] and "key" in char.character_inventory: print("You unlocked the front door! Welcome to the outside ") elif "key" not in char.character_inventory: print("The door is locked, and you seem to have misplaced your key.") else: print("The door is already open!") elif action[1] == "cabinet": if not rooms.burrow.variables["jar_taken"]: print("You opened the cabinet, there is an empty jar inside.") rooms.burrow.room_contents.append("jar") else: print("You opened the cabinet, it is empty") elif action[0] == "close": if action[1] == "trapdoor" and rooms.burrow.variables["rug_moved"]: print("You closed the trapdoor.") rooms.burrow.variables["trapdoor_opened"] = False elif action[1] == "door": print("The door is already closed, you like it that way.") else: continue def burrow_basement(): print("You are in your basement. There is a trapdoor above you.") while True: action = actions.get_action(rooms.burrow_basement) if action == "up": if rooms.burrow.variables["trapdoor_opened"]: load_room("burrow") break else: print("The trapdoor is shut.") elif action in rooms.directions: print("You can't go that way!") elif action[0] == "examine": if action[1] == "key_hook": if "key" in rooms.burrow_basement.room_contents: print("It is a handmade key hook your Uncle Frogert made. Its single hook remains unoccupied.") else: print("It is handmade key hook your Uncle Frogert made. It holds an old key.") elif action[1] == "icebox": print("It is an icebox where you store your cold foods, but it hasn't been filled in months.") elif action[0] == "move": if action[1] == "icebox" and not rooms.burrow_basement.variables["icebox_moved"]: pass elif action[1] == "icebox": pass elif action[0] == "use": if action[1] == "icebox" and not rooms.burrow_basement.variables["icebox_opened"]: rooms.burrow_basement.variables["icebox_opened"] = True if not rooms.burrow_basement.variables["fish_sticks_taken"]: print("You opened the icebox, there's a lonely box of fish sticks inside with colorful writing on it.") rooms.burrow_basement.room_contents.append("fish_sticks") else: print("You opened the icebox, it's empty devoid of a few lonely ice cubes. ") elif action[1] == "icebox": print("You closed the icebox like a good roommate.") rooms.burrow_basement.variables["icebox_opened"] = False if "fish_sticks" in rooms.burrow_basement.room_contents and not rooms.burrow.variables["fish_sticks_taken"]: rooms.burrow_basement.room_contents.remove("fish_sticks") elif action[0] == "open": if action[1] == "trapdoor" and not rooms.burrow.variables["trapdoor_opened"]: print("You opened the trapdoor.") rooms.burrow.variables["trapdoor_opened"] = True elif action[1] == "trapdoor": print("The trapdoor is already opened.") elif action[1] == "icebox" and not rooms.burrow_basement.variables["icebox_opened"]: rooms.burrow_basement.variables["icebox_opened"] = True if not rooms.burrow_basement.variables["fish_sticks_taken"]: print("You opened the icebox, there's a lonely box of fish sticks inside with colorful writing on it.") rooms.burrow_basement.room_contents.append("fish_sticks") else: print("You opened the icebox, it's empty devoid of a few lonely ice cubes. ") elif action[0] == "close": if action[1] == "trapdoor" and rooms.burrow.variables["rug_moved"]: print("You closed the trapdoor.") rooms.burrow.variables["trapdoor_opened"] = False elif action[1] == "icebox" and rooms.burrow_basement.variables["icebox_opened"]: print("You closed the icebox like a good roommate.") rooms.burrow_basement.variables["icebox_opened"] = False if "fish_sticks" in rooms.burrow_basement.room_contents and not rooms.burrow.variables["fish_sticks_taken"]: rooms.burrow_basement.room_contents.remove("fish_sticks") else: continue def front_of_house(): print("You are in front of your burrow") while True: break """ def room_template(): print("ROOM. EXITS") while True: action = actions.get_action(rooms.ROOM) if action[0] == "mopi": load_room(action[1]) if action == DIRECTION: elif action in rooms.directions: print("You cant go that way!") elif action[0] == "examine": elif action[0] == "move": elif action[0] == "use": elif action[0] == "open": elif action[0] == "close": else: continue """ def main(): check_start() print( "You are in a burrow, but not just any burrow. The burrow you reside in is in fact" "\nthe estate of Von Frogerick III, who just so happens to be your great great grandfather." "\nThe immense and fascinating history of your lineage matters not though, for you are hungry." "\nYou should find a fly to eat.") load_room("burrow") main() </code></pre> <p>Actions module:</p> <pre><code> """This is the actions module, it contains functions required to process user input and processes minor actions itself""" import random import room_info as rooms import character_and_items as char snarky_remark_list = ["And how exactly are you going to do that?", "Fat chance", "In your dreams", "Inconceivable!", "Aunt Frogatha would be ashamed.."] # Commands to add, - eat - anything else? # output def print_help(): print("--HELP--\n-'l' or 'look' - Provides description of room\n-'north' or 'n' - goes in specified direction" "\n-'examine' + object to examine it more closely\n-'move' + object to move an object" "\n-'use' + object to use an object\n-'down' or 'd' - move up or down" "\n-'inventory' or 'i' - displays inventory\n-'open' or 'close' - opens or closes an object" "\n-'read' - reads an object\n-'use __ on __' - uses one object on another") # this checks if the complex action is able to be performed on the object given def actions_match(complex_u_in, room): if (complex_u_in[0] == "take" and complex_u_in[1] in rooms.take_ob(room)) \ or (complex_u_in[0] == "use" and complex_u_in[1] in rooms.use_ob(room)) \ or (complex_u_in[0] == "examine" and complex_u_in[1] in rooms.exam_ob(room)) \ or (complex_u_in[0] == "move" and complex_u_in[1] in rooms.mov_ob(room)) \ or (complex_u_in[0] in ("open", "close") and complex_u_in[1] in rooms.open_ob(room)): return True else: return False # Consider moving this into the items module? def use_on(obj1, obj2): if obj1 == "key" and char.current_room == "burrow" and "key" in char.character_inventory and obj2 == "door": rooms.burrow.variables["door_unlocked"] = True print("You unlocked the door!") # Sort objects under the world class into an array. def get_room_contents(room): return rooms.exam_ob(room) + rooms.use_ob(room) + rooms.mov_ob(room) + rooms.take_ob(room) + rooms.open_ob(room) # Every action that doesn't return an input should be ended with return False # a complex action is an action containing more than one word. def check_complex_actions(room, complex_u_in): room_contents_list = get_room_contents(room) # relabeled for readability action = complex_u_in[0] item = complex_u_in[1] try: # Dev command to load rooms for testing if action == "mopi" and item in rooms.all: return ["mopi", item] # Dropping items is a character based action, and not a room based. Therefore it is separated. if len(complex_u_in) == 4 and (action == "use" and complex_u_in[2] == "on") \ and (char.use_on_items[item] == complex_u_in[3]): use_on(item, complex_u_in[3]) return False elif len(complex_u_in) == 3 and (item + "_" + complex_u_in[2]) in char.double_word_list: item = item + "_" + complex_u_in[2] complex_u_in.pop() if action == "drop" and item in char.character_inventory: rooms.append_to_room(room, item) char.character_inventory.remove(item) print("You dropped the " + item) return False elif action == "take" and item in rooms.take_ob(room): if item in rooms.contents(room): char.character_inventory.append(item) rooms.remove_from_room(room, item) # This removes the underscore in two-word objects if "_" in item: item = item.replace("_", " ") print("You took the " + item) return False else: print("You see no such thing!") return False elif action == "read" and (item in room_contents_list or item in char.character_inventory): item_description = char.get_description(item, "read") if item_description != "": if "_" in item: item = item.replace("_", " ") print("The " + item + " reads: " + item_description) else: print("You can't read that!") return False elif action == "examine" and (item in char.character_inventory or (item in rooms.contents(room) and item not in rooms.exam_ob(room))): item_description = char.get_description(item, "examine") if "_" in item: item = item.replace("_", " ") print(item_description) return False elif item in room_contents_list: if actions_match(complex_u_in, room): return complex_u_in elif action[0] == "examine": print("There's nothing to see of importance.") else: print(random.choice(snarky_remark_list)) return False else: print("You see no such thing!") return False except IndexError: # In case user inputs half of a command print(action + " what?") return False def get_action(room): complex_actions = ["move", "use", "examine", "take", "drop", "open", "close", "read", "mopi"] while True: # u_in stands for user input u_in = input("-&gt; ").lower().strip() print() complex_u_in = u_in.split(" ") if complex_u_in[0] in complex_actions: u_in = check_complex_actions(room, complex_u_in) if u_in != False: # Consider editing this bit? little sloppy return u_in else: # This loops if an action is not returned. continue if u_in in ("h", "?", "help"): print_help() elif u_in in ("look", "l"): rooms.get_description(room) elif u_in in ("inventory", "i"): char.print_inventory() elif u_in in ("north", "n"): return "north" elif u_in in ("south", "s"): return "south" elif u_in in ("west", "w"): return "west" elif u_in in ("east", "e"): return "east" elif u_in in ("northwest", "nw"): return "northwest" elif u_in in ("northeast", "ne"): return "northeast" elif u_in in ("southwest", "sw"): return "southwest" elif u_in in ("southeast", "se"): return "southeast" elif u_in in ("down", "d"): return "down" elif u_in in ("up", "u"): return "up" elif u_in in ("ribbit", "r"): print("you let out a cute ribbit") elif u_in in ("fuck", "shit", "damn"): print("That was awfully rude of you :(") elif u_in == "heck": print("No swearing!!!! &gt;:(") elif u_in in ("mopi", "mopi productions"): print("Mopi says: 'eat hot pant,, lie.'") else: print("That command was not recognized") </code></pre> <p>Character and items module:</p> <pre><code>"""This is the character module, it stores information on the character and items.""" double_word_list = ["fish_sticks", "key_hook", "front_door", "bedroom_door"] character_inventory = [] current_room = None def print_inventory(): if len(character_inventory) &lt; 1: print("Your pockets are empty! Wait, how do frogs have pockets?") else: print("--INVENTORY--") for item in character_inventory: print("-" + item) # This could get tedious for every item in the game, look for an alternative solution? def get_description(item, form): item_dict = { "pamphlet": pamphlet, "fish_sticks": fish_sticks, "key": key, "lantern": lantern, "photo": photo, "jar": jar } ob = item_dict.get(item, lambda: "ERROR") try: if form == "read": return ob.read_description elif form == "examine": return ob.exam_description except AttributeError: return "There's nothing to see of importance." use_on_items ={ "key": "door" } class Items: def __init__(self, read_desc, exam_desc): self.read_description = read_desc self.exam_description = exam_desc pamphlet = Items("The flies future is YOUR Future. Donate today!", "This is an annoying pamphlet, it came in the mail") fish_sticks = Items("MOPI Brand Fish Sticks! Unethically sourced, deep fried fun!", "These fish sticks are LONG expired, and unethically sourced at that. Better leave them be.") key = Items("34TH BURROW STREET", "It's an old cast iron key, it's been in your family for generations.") lantern = Items("", "It's a trusty oil lamp. It provides plenty of light, and was just recently topped off.") photo = Items("Forever yours and always :) Jan. 10, 1993", "It's a wedding photo of your Aunt Frogatha and Uncle Frogert. They're posing in front of the pond, " "many flies can be seen buzzing in the background. There's something written on the back.") jar = Items("", "It is an empty glass jar.") </code></pre> <p>Room info module:</p> <pre><code>"""This module contains information on every room as well as the room class""" directions = ["north", "n", "south", "s", "east", "e", "west", "w", "up", "u", "down", "d"] all = ["burrow", "burrow_basement"] # This is a workaround for the from room_info import * method. # Ideally this would all be one function, with a room parameter and an info parameter def exam_ob(room): return room.examinable_objects def use_ob(room): return room.usable_objects def mov_ob(room): return room.movable_objects def take_ob(room): return room.takeable_objects def open_ob(room): return room.open_ob def contents(room): return room.room_contents def append_to_room(room, item): room.room_contents.append(item) def remove_from_room(room, item): try: room.room_contents.remove(item) except ValueError: print("You see no such thing!") def get_description(room): print(room.description) if room == burrow: if not burrow.variables["rug_moved"]: print("There is a handwoven rug lying in the center of your room, with a bothersome lump in the middle.") elif burrow.variables["rug_moved"] and not burrow.variables["trapdoor_opened"]: print("There is a handwoven rug rudely shoved in to the corner. In the center of your room, there is a " "shut trapdoor.") else: print("There is a handwoven rug rudely shoved in to the corner. In the center of your room is an open " "trapdoor. Talk about a safety hazard!") if "lantern" in burrow.room_contents: print("A lit lantern hangs loosely on the wall.") if "pamphlet" in burrow.room_contents: print("An annoying informational pamphlet lies on the floor.") if "photo" in burrow.room_contents: print("A framed photo rests cheerily on the mantle.") if burrow.variables["cabinet_opened"]: print("There is an open cabinet on the far wall where you store dishware.") else: print("There is a shut cabinet on the far wall.") for item in burrow.room_contents: if item not in ("lantern", "pamphlet", "cabinet", "photo", "jar"): print("You've left a " + item + " here.") if room == burrow_basement: if not burrow_basement.variables["icebox_moved"]: if not burrow_basement.variables["icebox_opened"]: print("A securely shut ice box sits near the ladder.") else: print("An open ice box sits near the ladder") elif burrow_basement.variables["icebox_moved"]: if not burrow_basement.variables["icebox_opened"]: print("A knocked over ice box lies miserably near the ladder, luckily its still latched shut.") else: print("A knocked over ice box lies miserably near the ladder, spilling its contents everywhere." "\nIf only someone hadn't knocked it over...") if "fish sticks" in burrow_basement.room_contents: if burrow_basement.variables["icebox_moved"] and burrow_basement.variables["icebox_opened"]: print("A box of fish sticks is rapidly defrosting on the floor.") class World: def __init__(self, exam_ob, mov_ob, use_ob, take_ob, open_ob): self.examinable_objects = exam_ob self.movable_objects = mov_ob self.usable_objects = use_ob self.takeable_objects = take_ob self.open_ob = open_ob burrow = World(["rug", "door", "lump"], ["rug"], ["door", "trapdoor", "cabinet"], ["lantern", "pamphlet", "photo", "jar"], ["front_door", "trapdoor", "bedroom_door", "cabinet"]) burrow.room_contents = ["lantern", "pamphlet", "photo", "cabinet"] burrow.description = "You're in a cozy burrow, and a well furnished one at that. The room is lit by an assortment of " \ "\nwarm candles and lanterns. Your front door is to the north, and the door to your Aunt and " \ "Uncle's bedroom lies to the South West" burrow.variables = { "rug_moved": False, "trapdoor_opened": False, "door_unlocked": False, "cabinet_opened": False, "jar_taken": False } burrow_basement = World(["key_hook", "key", "icebox", "fish_sticks"], ["icebox"], ["icebox"], ["fish_sticks", "key"], ["trapdoor", "icebox"]) burrow_basement.room_contents = ["key", "icebox"] burrow_basement.description = "You're in a muddy basement that serves as more of a storage room than any sort of " \ "living quarters.\nThere is a key hook on the far wall." \ " A ladder leads out of the basement." burrow_basement.variables = { "icebox_moved": False, "icebox_opened": False, "fish_sticks_taken": False } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T15:51:54.463", "Id": "471269", "Score": "2", "body": "If you're doing this to learn programming and Python, carry on, a game is a very good experiment for that. If you're actually trying to make a text adventure game, I suggest you look into using TADS 3, which is a very well-designed system just for that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T08:22:08.283", "Id": "471346", "Score": "2", "body": "As @xxbbcc correctly notes, this is a good way to learn Python, but if your goal is to write interactive fiction, look into *Inform 7*. It is an astonishingly sophisticated system for building such games." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T10:02:39.270", "Id": "471362", "Score": "1", "body": "An alternative way to structure things is like [LambdaMOO](http://lambda.moo.mud.org/pub/MOO/ProgrammersManual.html), where everything is an object, and the commands the player types are implemented as methods on those objects. Objects have inheritance and a couple of built-in properties such as `owner` and `location`, but almost everything, including people, rooms, containers, doors, even a text editor, are implemented with end-user-written methods and properties added to those minimal objects." } ]
[ { "body": "<pre><code>import room_info as rooms\nimport character_and_items as char\n</code></pre>\n\n<p>If you're going to import them this way all the time, why didn't you just name the modules <code>rooms</code> and <code>char</code> respectively? What's the point of all the extra typing? Btw, it's conventional in text adventures to refer to the <code>player</code>; I'd go with <code>import player</code> over <code>import char</code>, just to de-confuse the syntax highlighter.</p>\n\n<p>Your function <code>print_frog_title</code> is used in only one place. You should just inline it there.</p>\n\n<hr>\n\n<pre><code>snarky_remark_list = [\"And how exactly are you going to do that?\", \"Fat chance\", \"In your dreams\", \"Inconceivable!\",\n \"Aunt Frogatha would be ashamed..\"]\n</code></pre>\n\n<p>When you start version-controlling your source code, you'll realize that it's better to indent sequences so that they have one element per line. This allows you to add and remove elements without introducing extra diffs into your history. Also add a trailing comma on <em>each</em> element; don't sigil the last element specially from all the rest.</p>\n\n<pre><code>snarky_remark_list = [\n \"And how exactly are you going to do that?\",\n \"Fat chance\",\n \"In your dreams\",\n \"Inconceivable!\",\n \"Aunt Frogatha would be ashamed..\",\n]\n</code></pre>\n\n<p>English grammar nit: I notice that some of these remarks end with punctuation and some don't. Another: You wrote <code>mantle</code> when you meant <code>mantel</code>.</p>\n\n<p>Your <code>room_dict</code> has nice git-friendly indentation, but is also missing that trailing comma on the last element.</p>\n\n<hr>\n\n<pre><code>character_inventory = []\ncurrent_room = None\n</code></pre>\n\n<p>These two variables feel like they should be data members of a <code>class Player</code>. But then there's other stuff in this module that is clearly unrelated to the player, e.g.</p>\n\n<pre><code># This could get tedious for every item in the game...\ndef get_description(item, form):\n</code></pre>\n\n<p>So number one, I'd consider splitting that out into an <code>items</code> or <code>objects</code> module; and number two, you already know the non-tedious solution! Just imagine that instead of writing</p>\n\n<pre><code>pamphlet = Items(\"The flies future is YOUR Future. Donate today!\",\n \"This is an annoying pamphlet, it came in the mail\")\n</code></pre>\n\n<p>you wrote</p>\n\n<pre><code>pamphlet = Item(\n name=\"pamphlet\",\n read=\"The flies future is YOUR Future. Donate today!\",\n examine=\"This is an annoying pamphlet, it came in the mail\",\n)\n</code></pre>\n\n<p>And instead of</p>\n\n<pre><code>key = Items(\"34TH BURROW STREET\",\n \"It's an old cast iron key, it's been in your family for generations.\")\n</code></pre>\n\n<p>imagine that you wrote</p>\n\n<pre><code>key = Item(\n name=\"key\",\n read=\"34TH BURROW STREET\",\n examine=\"It's an old cast iron key, it's been in your family for generations.\",\n use_on=[\"door\"],\n)\n</code></pre>\n\n<p>Can you see how to implement the constructor of <code>class Item</code> now?</p>\n\n<p>EDITED TO ADD: It'd be something like this.</p>\n\n<pre><code>class Item:\n def __init__(self, name, read, examine, use_on=None):\n self.name = name\n self.read = read\n self.examine = examine\n self.use_on = use_on or []\n # self.location = burrow\n # self.inroom_description = \"There is a %s here.\" % name\n</code></pre>\n\n<p>No member functions are necessary yet.</p>\n\n<p>And how to implement <code>get_description</code>? ...Well, almost. Suppose we wrote our list of \"all the items in the game\" like <em>this!</em></p>\n\n<pre><code>all_items = [\n Item(\n name=\"pamphlet\",\n read=\"The flies future is YOUR Future. Donate today!\",\n examine=\"This is an annoying pamphlet, it came in the mail\",\n ),\n Item(\n name=\"key\",\n read=\"34TH BURROW STREET\",\n examine=\"It's an old cast iron key, it's been in your family for generations.\",\n use_on=[\"door\"],\n ),\n]\n</code></pre>\n\n<p>Now <code>get_description</code> starts out something like</p>\n\n<pre><code>def get_description(verb, noun):\n for item in all_items:\n if item.name == noun:\n if verb == \"examine\":\n return item.examine\n elif verb == \"read\":\n return item.read\n return \"I don't see what you're referring to.\"\n</code></pre>\n\n<p>You could preprocess <code>all_items</code> into a dict mapping from names to <code>Item</code> objects, to save two levels of indentation in that loop.</p>\n\n<pre><code>def get_description(verb, noun):\n item = all_items_by_name.get(noun, None)\n [...]\n</code></pre>\n\n<p>Notice that I quietly turned <code>Items</code> plural into <code>Item</code> singular, and also turned <code>form</code> into <code>verb</code>.</p>\n\n<hr>\n\n<pre><code># This is a workaround for the from room_info import * method.\n# Ideally this would all be one function, with a room parameter and an info parameter\ndef exam_ob(room):\n return room.examinable_objects\ndef use_ob(room):\n return room.usable_objects\n</code></pre>\n\n<p>Okay, this seems insane. Why not just take the one place you call <code>rooms.exam_ob(room)</code> and write <code>room.examinable_objects</code> instead?</p>\n\n<hr>\n\n<p>Your handling of takeable objects seems tedious and naïve... but also probably unavoidable, if you want to have that level of control over the messages. (The photo is cheerily on the mantel; the fish sticks are defrosting on the floor; etc.) If you want to add the ability to drop arbitrary objects in arbitrary places, you'll have to find a new way of doing these messages.</p>\n\n<p>Have you seen <a href=\"http://literateprogramming.com/adventure.pdf\" rel=\"nofollow noreferrer\">Donald Knuth's literate version of <em>Adventure</em>?</a> See particularly section 63, on page 43.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T07:00:25.273", "Id": "471197", "Score": "0", "body": "Thank you a ton for the smaller style pointers, it really helps. The better utilization of the item class was super smart, and I'm not quite sure why I didn't think of it! That being said, how would you go about defining the class? Would it be a simple class Item: pass, or does it use parameters still? Classes are definitely still confusing to me, but I learn best by asking questions. Thanks for your help!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T15:37:32.023", "Id": "471266", "Score": "1", "body": "Added a definition for `class Item`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T04:45:38.007", "Id": "240248", "ParentId": "240237", "Score": "7" } }, { "body": "<p>An interesting beginning to your game. I'd be interested to seeing how it turns out.</p>\n\n<hr>\n\n<p>Text adventure games are usually data-driven. This means you would have a game engine (program) that would read a game description file (data), and execute the same instructions for every action in every location in the game, producing different outcomes based on the game data.</p>\n\n<p>What you have written is not data driven. You have a function for handling actions in the <code>burrow()</code>, another for the <code>burrow_basement()</code>, and another for <code>front_of_house()</code>. The code is these functions look very similar, and very repetitive, which is why we can write it once, and change the outcome based on the data.</p>\n\n<p>A problem with the way you've written the game is recursion. If you start in the burrow, and you can go down into the basement or north to the front of the house. Each of those actions calls <code>load_room(location)</code> which never returns, and calls its own function for handling that new room location. For instance, if you go down to the basement, <code>load_room(\"burrow_basement\")</code> is called, and it calls <code>burrow_basement()</code>, which in response to an \"up\" action would call <code>load_room(\"burrow\")</code>, which would call <code>burrow()</code>. We keep getting deeper and deeper into the call stack. If the player keeps exploring, eventually they will run into Python's stack limit. You could fix this by increasing the stack size, but that is just a kludge; the correct solution is to get rid of the recursion.</p>\n\n<hr>\n\n<h1>Object model</h1>\n\n<h2>Places</h2>\n\n<p>You should start by defining some things. Like rooms. A room is location the player can be in. It should have a short name (\"Kitchen\", \"Burrow's Basement\"), and a longer description. The player may or may not have been in the room before. It will have connections (exits) to other locations. There may be items in the room.</p>\n\n<pre><code>class Room:\n def __init__(self, name, description):\n self.name = name\n self.description = description\n self.visited = False\n self.exits = { }\n self.contents = []\n</code></pre>\n\n<h2>Things</h2>\n\n<p>Beyond rooms, the world is full of objects, or things. Things will have a name, and perhaps a description. Some things can be carried (photos, pamphlets, jars, ...) where as other things must remain where they are (stoves, sinks). Some things can be worn, like a coat or a hat. It might be hidden:</p>\n\n<pre><code>class Thing:\n def __init__(self, name, description):\n self.name = name\n self.description = description\n self.fixed = False\n self.moved = False\n self.wearable = False\n self.concealed = False\n</code></pre>\n\n<h2>Containers</h2>\n\n<p>Some things can be placed inside other things. Fish sticks may be found in an ice box. The ice box is usually closed, but occasionally open. Some containers may be locked, like a cabinet. Some containers may be see through, like a china cabinet. You can climb into some containers, like a wardrobe or a car, but most you cannot.</p>\n\n<pre><code>class Container(Thing):\n def __init__(self, name, description):\n super().__init__(name, description)\n self.contents = []\n self.open = False\n self.locked = False\n self.key = None\n self.transparent = False\n self.enterable = False\n</code></pre>\n\n<p>Is a room a container? Rooms have names, descriptions, and contents. And they are enterable.</p>\n\n<h2>Supporters</h2>\n\n<p>Some things can be placed on other things. You can put a jar on a table. You can put a key on a hook. So perhaps some containers should be considered a supporter, instead. You can even enter some supporters, such as climbing into a bed.</p>\n\n<h2>Animate</h2>\n\n<p>Some things can move around, and have behaviours. You can talk to some of them, such as a shopkeeper, and they will talk back. Other actors, might not talk back, such as a cat.</p>\n\n<p>A shopkeeper (an animate thing) might be wearing pants with pockets (a container) which may contain a pocket watch (openable).</p>\n\n<p>Is the player an animate container??? They can hold things (inventory), move around (animate), take things (container), hold things, wear things.</p>\n\n<h2>Doors</h2>\n\n<p>A door sits between two rooms. A door could be open or closed. If it is closed, it may or may not be locked. </p>\n\n<pre><code>class Door(Thing):\n def __init__(self, name, description, key=None)\n self.name = name\n self.description = description\n self.open = False\n self.lockable = key is not None\n self.locked = True if key else False\n self.key = key\n self.connects = []\n\n\nliving_room = Room(\"Living Room\", \"A place for the family to hang out\")\ndining_room = Room(\"Dining Room\", \"Many meals were had here\")\nbasement = Room(\"Basement\", \"A dark and dingy hole in the ground\")\n\ntrap_door = Door(\"Trap door\", \"A piece of wood, with a basic hinge and a ring handle\")\ntrap_door.concealed = True\ntrap_door.connects = [living_room, basement]\n\ndining_room.exits[\"south\"] = living_room\nliving_room.exits[\"north\"] = dining_room\nliving_room.exits[\"down\"] = trap_door\nbasement.exits[\"up\"] = trap_door\n</code></pre>\n\n<p>Here, we have two exits from the living room, north directly to the dining room (no door), and down to a <code>trap_door</code>. The <code>trap_door</code> is concealed, so if the player is in the living room, and the try to go \"down\", initially they should get a \"you can't go that way\". Moving the rug should reveal the trap door (marking it not concealed), allowing travel through the door to the other location it connects to. Maybe:</p>\n\n<pre><code>rug = Thing(\"A rug\", \"A thick heavy rug, passed down through the ages\")\nrug.fixed = True\ndef rug_move():\n print(\"You pull back the corner of the rug, revealing a trap door\")\n rug.description = \"One corner of the rug has been lifted to reveal a trap door\"\n trap_door.concealed = False\nrug.on_move = run_move\n</code></pre>\n\n<p>Now if your game logic allows you to type \"lift rug\" or \"move rug\", you could parse the word \"rug\", find the object with that name in the <code>location.contents</code>, and call that object's <code>.on_move()</code> function, which tells you what happened, changes the rug's description, and removes the concealed attribute from the trap door.</p>\n\n<hr>\n\n<h1>Example</h1>\n\n<p>Something to get you started. The lantern is just a <code>Thing</code>. The <code>rug</code> is actually a <code>Rug</code> (a special <code>Thing</code>), which has an action defined in the <code>frog.py</code> game file.</p>\n\n<p>Notice the adventure game framework can be reused for many different games.</p>\n\n<p>This is a \"better\" way that you're previous approach, but I wouldn't say it is a good way, yet. The framework has a lot of detail to flush out, and reworked to include better visibility and touchability. Items should optionally have a <code>.has_light</code> attribute. A room <code>.has_light</code> if it itself has that attribute set to True, or if an item within it has that attribute, unless the item is in a closed container (unless that container is transparent).</p>\n\n<p>If you continue down this road, eventually you'll re-invent the <a href=\"http://inform7.com\" rel=\"noreferrer\">Inform 7</a> interactive fiction framework. Good luck.</p>\n\n<h2>adventure.py</h2>\n\n<pre><code>COMMANDS = { 'go', 'move', 'use', 'examine', 'open', 'close', 'inventory' }\n\nDIRECTIONS = set()\nREVERSE_DIRECTION = {}\n\nfor fwd, rev in (('n', 's'), ('e', 'w'), ('u', 'd')):\n DIRECTIONS.add(fwd)\n DIRECTIONS.add(rev)\n REVERSE_DIRECTION[fwd] = rev\n REVERSE_DIRECTION[rev] = fwd\n\nclass CantSee(Exception):\n pass\n\nclass Thing:\n def __init__(self, short_description, **kwargs):\n self.short_description = short_description\n self.long_description = None\n self.concealed = False\n self.scenery = False\n self.fixed = False\n self.openable = False\n\n for key, value in kwargs.items():\n if not key in self.__dict__:\n raise ValueError(\"Unrecognized argument: \"+key)\n self.__dict__[key] = value\n\n def description(self):\n return self.short_description\n\n def examine(self):\n if self.long_description:\n print(self.long_description)\n else:\n print(\"There is nothing special about it\")\n\n def move(self):\n if self.fixed:\n print(\"You can't move it\")\n else:\n print(\"You move it a bit.\")\n\n\nclass Container(Thing):\n def __init__(self, short_description, **kwargs):\n self.contents = {}\n self.openable = True\n self.open = False\n self.transparent = False\n\n super().__init__(short_description, **kwargs)\n\n def containing():\n if self.contents:\n return \", \".join(item.description() for item in self.contents())\n return \"nothing\"\n\n\n def description(self):\n text = self.short_description\n if self.openable:\n if self.open:\n text += \" (which is closed)\"\n else:\n text += \" (which is open)\"\n\n if self.open or self.transparent:\n if self.contents:\n text += \"(containing \" + self.containing() + \")\"\n\n return description\n\n\nclass Door(Thing):\n def __init__(self, short_description, **kwargs):\n\n self.lockable = False\n self.locked = False\n self.key = None\n self.connects = {}\n\n super().__init__(short_description, **kwargs)\n\n self.fixed = True\n self.closed = True\n\nclass Room(Thing):\n\n def __init__(self, name, **kwargs):\n self.exits = {}\n self.visited = False\n self.contents = set()\n\n super().__init__(name, **kwargs)\n\n def exit_to(self, direction, destination, door=None):\n reverse = REVERSE_DIRECTION[direction]\n\n if door:\n door.connects[direction] = destination\n door.connects[reverse] = self\n self.exits[direction] = door\n destination.exits[reverse] = door\n else:\n self.exits[direction] = destination\n destination.exits[reverse] = self\n\n def enter(self):\n print(\"Location:\", self.short_description)\n if not self.visited:\n self.describe()\n self.visited = True\n\n def visible_things(self):\n return [item for item in self.contents if not item.concealed]\n\n def describe(self):\n if self.long_description:\n print(self.long_description)\n print()\n\n items = [item for item in self.visible_things() if not item.scenery]\n\n for item in items:\n if item.concealed or item.scenery:\n continue\n\n if items:\n print(\"You see:\")\n for item in items:\n print(\" \", item.description())\n\nclass Player(Container):\n def __init__(self):\n super().__init__(\"yourself\")\n self.long_description = \"As good looking as ever.\"\n\n self.openable = False\n self.location = None\n self.alive = True\n\n def inventory(self):\n if self.contents:\n print(\"You are carring:\")\n for item in self.contents:\n print(\" \", item.description)\n else:\n print(\"You have nothing.\")\n\n def go(self, direction):\n destination = self.location.exits.get(direction, None)\n if isinstance(destination, Door):\n door = destination\n destination = door.connects[direction]\n if door.concealed:\n destination = None\n elif door.closed:\n if door.locked:\n print(\"You'd need to unlock the door first\")\n return\n print(\"First opening the\", door.short_description)\n\n if destination:\n self.location = destination\n destination.enter()\n else:\n print(\"You can't go that way\")\n\nclass Game:\n def __init__(self, protagonist):\n self.player = protagonist\n self.game_over = False\n self.turns = 0\n\n def welcome(self):\n print(\"A text adventure game.\")\n\n def help(self):\n print(\"Examine everything.\")\n\n def get_action(self):\n while True:\n command = input(\"\\n&gt; \").lower().split()\n\n if command:\n if len(command) == 1:\n if command[0] in DIRECTIONS:\n command.insert(0, 'go')\n if command[0] == 'i':\n command[0] = 'inventory'\n\n if command == ['inventory']:\n self.player.inventory()\n\n elif command == ['help']:\n self.help()\n\n elif command[0] == 'go':\n if len(command) == 2 and command[1] in DIRECTIONS:\n return command\n else:\n print(\"I'm sorry; go where?\")\n\n elif command[0] in COMMANDS:\n return command\n\n else:\n print(\"I don't understand\")\n\n def go(self, direction):\n self.player.go(direction)\n\n def item(self, thing):\n items = self.player.location.visible_things()\n for item in items:\n if thing in item.short_description:\n return item\n raise CantSee(thing)\n\n def move(self, thing):\n item = self.item(thing)\n item.move() \n\n def perform_action(self, command):\n if command[0] == 'go' and len(command) == 2:\n self.go(command[1])\n elif command[0] == 'move' and len(command) == 2:\n self.move(command[1])\n else:\n print(\"Command not implemented\")\n\n\n def play(self):\n self.welcome()\n\n self.player.location.enter()\n\n while not self.game_over:\n command = self.get_action()\n try:\n self.perform_action(command)\n self.turns += 1\n except CantSee as thing:\n print(\"You don't see a\", thing)\n\n if not self.player.alive:\n print(\"You have died.\")\n else:\n print(\"Game over.\")\n</code></pre>\n\n<h2>frog.py</h2>\n\n<pre><code>from adventure import Thing, Room, Door, Player, Game\n\nburrow = Room(\"Your Burrow\")\nbasement = Room(\"Your Basement\")\nfront_yard = Room(\"Your Front Yard\")\n\nfront_door = Door(\"Front Door\")\ntrap_door = Door(\"Trap Door\", concealed=True)\nburrow.exit_to('n', front_yard, front_door)\nburrow.exit_to('d', basement, trap_door)\n\nclass Rug(Thing):\n def move(self):\n if trap_door.concealed:\n print(\"Moving the rug reveals a trap door to the basement.\")\n trap_door.concealed = False\n else:\n super().move()\n\nrug = Rug(\"a rug\", fixed=True)\nburrow.contents.add(rug)\nlantern = Thing(\"a lantern\")\nburrow.contents.add(lantern)\n\n\nplayer = Player()\nplayer.location = burrow\n\nclass FrogGame(Game):\n def welcome(self):\n print(\"\"\"\\\nYou are in a burrow, but not just any burrow. The burrow you reside in is in\nfact the estate of Von Frogerick III, who just so happens to be your great\ngreat grandfather. The immense and fascinating history of your lineage matters\nnot though, for you are hungry. You should find a fly to eat.\n\"\"\")\n\ngame = FrogGame(player)\n\nif __name__ == '__main__':\n\n game.play()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T06:51:21.710", "Id": "471195", "Score": "0", "body": "Hey! First of all, thanks for the response. It's immensely insightful and really shows how useful classes are in python. The concept is still pretty new to me, so I hope you don't mind if I try to clarify. From my current understanding, switching to an object model would basically remove the need for room functions, and have one major function that processes actions by referring to classes and class methods? Would it be subdivided into rooms still? Or could I just process the action \"move rug\" by having it refer to the rug which is known to be in the burrow? What if I have duplicate items?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T15:23:58.903", "Id": "471264", "Score": "3", "body": "I would also add that each object (including actions) should have a list of synonyms that can be used, so if the player opts to \"lift carpet\", it will understand that this is the same as \"move rug\"." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T05:49:36.447", "Id": "240252", "ParentId": "240237", "Score": "20" } } ]
{ "AcceptedAnswerId": "240252", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T23:51:05.903", "Id": "240237", "Score": "23", "Tags": [ "python", "beginner", "python-3.x", "object-oriented", "adventure-game" ], "Title": "Zork-like text adventure w/ Python" }
240237
<p>I was recently intrigued by the Hindley Milner algorithm (for type inference) and decided to implement it in python. After implementing it, I got the feeling that the implementation was incorrect. I also felt that it wasn't very pythonic, and was sort of inefficient. Here is my code (it isn't as long as it looks-- there is just a lot of documentation):</p> <p><strong>ie_ast.py</strong></p> <pre class="lang-py prettyprint-override"><code>class InferenceError(Exception): pass class Type: pass class Node: pass class Int(Type, Node): def __init__(self, number): """A basic integer node Args: number: a integer """ self.number = number def get_type(self): return self def show(self): return "int" class Float(Type, Node): def __init__(self, number): """A basic float node Args: number: a float """ self.number = number def get_type(self): return self def show(self): return "float" class String(Type, Node): def __init__(self, string): """A basic string node Args: string: a string """ self.string = string def get_type(self): return self def show(self): return "string" class Bool(Type, Node): def __init__(self, _bool): """A basic boolean node Args: _bool: a boolean """ self._bool = _bool def get_type(self): return self def show(self): return "bool" class Void(Type, Node): def __init__(self): """No type""" def get_type(self): return self def show(self): return "void" class Wildcard(Type, Node): def __init__(self): """Genric type (for return smts)""" def get_type(self): return self def show(self): return "wildcard" class Unknown(Type, Node): def __init__(self): """A currently unknow type""" def get_type(self): return self def show(self): return "unknown" class Ident(Node): def __init__(self, name): """An identifer Args: name: a name """ self.name = name self.type = Unknown() def annotate_type(self, _type): self.type = _type def get_type(self): return self.type class BinOp(Node): def __init__(self, left, op, right): """A binary operation node Args: left: the left hand side node op: the opertaion (+/-/*//) right: the right hand side node """ self.left = left self.op = op self.right = right self.type = Unknown() def annotate_type(self, _type): self.type = _type def get_type(self): return self.type class IfElse(Node): def __init__(self, condition, if_program, else_program): """A if-else node Args: condition: a Bool of true/false if_program: what to do if the condition evaluates as true else_program: what to do if the condition evaluates as false """ self.condition = condition self.if_program = if_program self.else_program = else_program self.if_program_type = Unknown() self.else_program_type = Unknown() self.type = Unknown() def annotate_if_program_type(self, _type): self.if_program_type = _type def annotate_else_program_type(self, _type): self.else_program_type = _type def get_if_program_type(self): return self.if_program_type def get_else_program_type(self): return self.else_program_type def annotate_type(self, _type): self.type = _type def get_type(self): return self.type class VarDef(Node): def __init__(self, name, value): """A variable node node Args: name: the variable's name value: the variable's value """ self.name = name self.value = value self.type = Unknown() def annotate_type(self, _type): self.type = _type def get_type(self): return self.type class FuncDef(Node): def __init__(self, name, args, program): """A function node Args: name: the function's name args: the function's arguments of an unknown type program: the function's program """ self.name = name self.args = args self.program = program self.type = Unknown() def annotate_type(self, _type): self.type = _type def get_type(self): return self.type class FuncCall(Node): def __init__(self, name, args): """A function call node Args: name: the function's name args: the function's arguments """ self.name = name self.args = args self.type = Unknown() if self.name.name != "return" else Wildcard() def annotate_type(self, _type): self.type = _type def get_type(self): return self.type </code></pre> <p><strong>ie.py</strong></p> <pre class="lang-py prettyprint-override"><code>from ie_ast import * class InferenceEngine: def __init__(self): """Builds a type table for a supplied ast""" # built in functions self.built_ins = ["println", "return"] def infer(self, node_list, type_table, actual_node_list): """Inference machinery Args: node_list: a list of nodes type_table: the table to read and write types actual_node_list: None if it node_list is the base program. If it is not None, it must the base_program Returns: An annotated node_list """ if actual_node_list is None: actual_node_list = node_list for node in node_list: if isinstance(node, Ident): self.infer_ident(node, type_table, actual_node_list) elif isinstance(node, BinOp): self.infer_bin_op(node, type_table, actual_node_list) elif isinstance(node, IfElse): self.infer_if_else(node, type_table, actual_node_list) elif isinstance(node, VarDef): self.infer_var_def(node, type_table, actual_node_list) elif isinstance(node, FuncDef): self.infer_func_def(node, type_table, actual_node_list) elif isinstance(node, FuncCall): self.infer_func_call(node, type_table, actual_node_list) elif isinstance(node, Int): # int does not need to be type checked because it is # a basic type, and can't be reduced pass elif isinstance(node, Float): # float does not need to be type checked because it is # a basic type, and can't be reduced pass elif isinstance(node, String): # string does not need to be type checked because it is # a basic type, and can't be reduced pass elif isinstance(node, Bool): # bool does not need to be type checked because it is # a basic type, and can't be reduced pass return node_list def infer_ident(self, node, type_table, node_list): """Gets the type of any identifier Args: node: the ident node type_table: the table to read and write types actual_node_list: the base program Returns: An annotated ident """ node.annotate_type(type_table[node.name]) def infer_bin_op(self, node, type_table, node_list): """Infers the type of any binop (+/-/*//) Args: node: the binop node type_table: the table to read and write types actual_node_list: the base program Returns: An annotated binop node """ left_type = self.infer([node.left], type_table, node_list)[0].get_type() right_type = self.infer([node.right], type_table, node_list)[0].get_type() # check if the left type and right type are not the same if type(left_type) is not type(right_type): raise InferenceError("incompatible types") node.annotate_type(left_type) def infer_if_else(self, node, type_table, node_list): """Infers the type of a if-else smt (and runs type checks) Args: node: an if-else node type_table: the table to read and write types actual_node_list: the base program Returns: An annotated (and type checked) if-else node """ condition_type = self.infer([node.condition], type_table, node_list)[0].get_type() # makes sure that the condition's type is bool if not isinstance(condition_type, Bool): raise InferenceError( "expected if-else condition to be of type bool") # look for returns statements in the if program # this is done to make sure all of them return the # same type if_ret_types = self.look_for_return_smts(node.if_program, self, type_table) if if_ret_types: if not len(set(map(type, if_ret_types))) == 1: raise InferenceError( "if program has multiple return statements that don't return the same thing" ) node.if_program_type = if_ret_types[0] else: node.if_program_type = Void() # look for returns statements in the else program # this is done to make sure all of them return the # same type else_ret_types = self.look_for_return_smts(node.else_program, self, type_table) if else_ret_types: if not len(set(map(type, else_ret_types))) == 1: raise InferenceError( "else program has multiple return statements that don't return the same thing" ) node.else_program_type = else_ret_types[0] else: node.else_program_type = Void() # can't say the if and else statement's program don't return # the same type if one of them is unknown if type(node.if_program_type) is not type( node.else_program_type) and not isinstance( node.if_program_type, Unknown) and not isinstance( node.else_program_type, Unknown): raise InferenceError( "if statement and else statement return different types") node.annotate_type( node.if_program_type if not isinstance( node.if_program_type, Unknown) else node.else_program_type) def infer_var_def(self, node, type_table, node_list): """Gets the type of any variable Args: node: a vardef node type_table: the table to read and write types actual_node_list: the base program Returns: An annotated vardef node """ var_type = self.infer([node.value], type_table, node_list)[0].get_type() type_table[node.name.name] = var_type node.annotate_type(var_type) def infer_func_def(self, node, type_table, node_list, skip_args=False): """Attempts to get the type of a function upon definition Args: node: a funcdef node type_table: the table to read and write types actual_node_list: the base program Returns: An (maybe almost) annotated funcdef node """ # inserts itself into the type table for when # it is called type_table[node.name.name] = node if not skip_args: for arg in node.args: type_table[arg.name] = Unknown() arg.annotate_type(Unknown()) # gets the program's node annotated with their respective types node.program = self.infer(node.program, type_table, node_list) return_types = self.look_for_return_smts(node.program, self, type_table) # removes all the returns that have a type of unknown filtered_rets = [ elm for elm in return_types if not isinstance(elm, Unknown) ] # checks is the function's program has return statements # that don't return the same type if filtered_rets: if not len(set(map(type, filtered_rets))) == 1: raise InferenceError( "function has return statements with incompatible types") node.annotate_type(filtered_rets[0]) else: node.annotate_type(Void()) if skip_args: return node def infer_func_call(self, node, type_table, node_list): """Infers the type of a function, intern getting its own type Args: node: a funccall node type_table: the table to read and write types actual_node_list: the base program Returns: An annotated funccall node """ if node.name.name not in self.built_ins: # get the function previously inserted into the type table func = type_table[node.name.name] # annotate the function's args with the types of the # arguments supplied to the function call for arg, call_arg in zip(func.args, node.args): arg_type = self.infer([call_arg], type_table, node_list)[0].get_type() type_table[arg.name] = arg_type arg.annotate_type(arg_type) # now that we know the args types we can completely # infer the function's program's types, thus # getting the function's type changed_func = self.infer_func_def(func, type_table, node_list, True) node.annotate_type(changed_func.get_type()) type_table[node.name.name] = changed_func node_list[node_list.index(func)] = changed_func else: # annotate the node with the type of its argument node.annotate_type( self.infer(node.args, type_table, node_list)[0].get_type()) def look_for_return_smts(self, program, ie, type_table): """Looks for return smts in a given program Args: program: the program to search in ie: an inference engine type_table: the table to read and write types Returns: All the return smt type in a given program """ return_smts = [] for program_node in program: if isinstance(program_node, FuncCall) and program_node.name.name == "return": # insert into the return smts list the type of the argument return_smts.append( ie.infer(program_node.args, type_table, None)[0].get_type()) elif isinstance(program_node, IfElse): return_smts.extend( ie.infer( self.look_for_return_smts(program_node.if_program, ie, type_table), type_table, None)) return_smts.extend( ie.infer( self.look_for_return_smts(program_node.else_program, ie, type_table), type_table, None)) return return_smts </code></pre> <p><strong>main.py</strong></p> <pre><code>from ie import InferenceEngine from ie_ast import * # example usage """ foo = 123 + 123 foobar = True if foobar: pi else: 3.1415 println(foo) def bar(a, b, c): baz = foobar if foobar: if false: return a + b else: return c + b else: if true: return 123 else: return 321 abc = bar(12.2, 123321, foo) * foo / 456 """ ie = InferenceEngine() type_table = {} program = [ VarDef(Ident("foo"), BinOp(Int("123"), "+", Int("123"))), VarDef(Ident("foobar"), Bool("true")), IfElse(Ident("foobar"), [String("pi")], [Float("3.1415")]), FuncCall(Ident("println"), [Ident("foo")]), FuncDef( Ident("bar"), [Ident("a"), Ident("b"), Ident("c")], [ VarDef(Ident("baz"), Ident("foobar")), IfElse( Ident("foobar"), [ IfElse( Bool("false"), [ FuncCall( Ident("return"), [BinOp(Ident("a"), "+", Ident("b"))]) ], [ FuncCall( Ident("return"), [BinOp(Ident("c"), "+", Ident("b"))]) ]) ], [ IfElse( Bool("true"), [FuncCall(Ident("return"), [Int("123")])], [FuncCall(Ident("return"), [Int("321")])]) ]) ]), VarDef( Ident("abc"), BinOp( FuncCall( Ident("bar"), [Int("12.12"), Int("123321"), Ident("foo")]), "*", BinOp(Ident("foo"), "/", Int("456")))), ] infered = ie.infer(program, type_table, None) # print out the type table print("type table:") print({k: v.get_type().show() for k, v in type_table.items()}) </code></pre> <p>Does this follow the hindley milner algorithm, and is there some way I could make it better?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T06:16:30.020", "Id": "471192", "Score": "0", "body": "Maybe the files could have been better named!" } ]
[ { "body": "<p>Your first file could be a lot shorter if you made the <code>Type</code> class slightly more than a useless empty namespace:</p>\n\n<pre><code>class Type:\n name = None\n\n def get_type(self):\n return self\n\n def show(self):\n if self.name is None:\n raise NotImplementedError\n return self.name\n</code></pre>\n\n<p>Then all your other types get shorter:</p>\n\n<pre><code>class Int(Type, Node):\n \"\"\"A basic integer node\"\"\"\n name = \"int\"\n\n def __init__(self, number):\n \"\"\"A basic integer node\n\n Args:\n number: an integer\n \"\"\"\n self.number = number\n</code></pre>\n\n<p>Especially the ones that don't need any argument in the constructor:</p>\n\n<pre><code>class Void(Type, Node):\n \"\"\"No type\"\"\"\n name = \"void\"\n</code></pre>\n\n<p>It could be argued that the <code>show</code> method should be called <code>__str__</code> or <code>__repr__</code>, making them <a href=\"https://rszalski.github.io/magicmethods/\" rel=\"nofollow noreferrer\">magic methods</a>, depending on your need.</p>\n\n<p>Similarly for <code>Node</code>:</p>\n\n<pre><code>class Node:\n\n def annotate_type(self, _type):\n self.type = _type\n\n def get_type(self):\n return self.type\n</code></pre>\n\n<p>At this point you could also realize that there is no need to have these getters and setters in the first place. <a href=\"https://www.python-course.eu/python3_properties.php\" rel=\"nofollow noreferrer\">In Python using a plain attribute is usually preferred</a>. You can always start with an attribute and add getters and setters if you need them (i.e. if they do more than just getting and setting an attribute) by using <code>property</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T08:35:56.800", "Id": "240260", "ParentId": "240239", "Score": "2" } } ]
{ "AcceptedAnswerId": "240260", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T01:27:03.440", "Id": "240239", "Score": "2", "Tags": [ "python", "algorithm" ], "Title": "Type inference similar to hindley milner in python" }
240239
<p>I am hoping to make a quick decision tree using the if statement in excel vba. The point is to have a message with a prompt show up and then it will take the person through the prompts based on the answers. Can my current approach be improved upon in any way?</p> <pre><code>Sub Decision_tree() a = MsgBox("Want To Play A Game?", 3) If a = 6 Then MsgBox "Let the games begin!", 1 ElseIf a = 7 Then MsgBox "Okay. Press ctrl K to start over." End Else MsgBox "Sad. Come back later. Press ctrl K to start." End End If a = MsgBox("are you a boy?", vbYesNo) If a = 6 Then '** b = MsgBox("does your names start before O?", vbYesNo) If b &lt; 7 Then d = MsgBox("do you live in logan?", vbYesNo) ElseIf b = 7 Then f = MsgBox("Is your name 4 letters?", vbYesNo) If d = 6 Then h = MsgBox("Did you serve your mission with Josh?", vbYesNo) ElseIf f = 6 Then MsgBox "Your name is Ryan" ElseIf f = 7 Then MsgBox "your name is Trevon" ElseIf d = 7 Then j = MsgBox("Did you serve a mission with Josh?") ElseIf h = 6 Then MsgBox "Your name is Cade" ElseIf h = 7 Then K = MsgBox("are you a DJ?", vbYesNo) ElseIf j = 6 Then MsgBox "your name is Houston" ElseIf j = 7 Then MsgBox "your name is Cameron" ElseIf K = 6 Then MsgBox "your name is Jack with a j" ElseIf K = 7 Then MsgBox "your name is burton" ElseIf a = 7 Then c = MsgBox("does your name start Before N?", vbYesNo) ElseIf c = 6 Then e = MsgBox("does your name have a K in it?", vbYesNo) ElseIf c = 7 Then g = MsgBox("do you own a jeep?", vbYesNo) ElseIf e = 6 Then i = MsgBox("Are you from Idaho?", vbYesNo) ElseIf g = 6 Then MsgBox "your name is olivia" ElseIf g = 7 Then MsgBox "your name is tiffany" ElseIf i = 6 Then MsgBox "Your name is Kasey" ElseIf i = 7 Then MsgBox "Your name is Mckenna" End If End If End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T08:36:21.200", "Id": "471216", "Score": "0", "body": "I've edited your question a bit because before it came across like you hadn't worked out how to implement the decision tree and your code wasn't working yet, which would have been out of scope for the site (and put off potential reviewers). Also some of your code wasn't formatted correctly so I hope I've fixed that for you, but does the indentation look the same as it does in Excel? Is that how you'd expect it to be? If not, then just paste your code straight from Excel editor and put triple back ticks ``` above and below the code, and it should appear indented exactly the same as the original" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T10:46:16.090", "Id": "471234", "Score": "1", "body": "The inconsistent indenting makes this _really_ difficult to read." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T10:53:16.687", "Id": "471235", "Score": "1", "body": "I'd have to say that code doesn't work because it won't even compile. At the very minimum, it's missing an `End If` at the end. Does it actually do what you want it to do, and you're looking to make it do so in a better, more readable, more logical way; or does it not work and you're looking to figure out why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T11:43:19.183", "Id": "471236", "Score": "1", "body": "@FreeMan There is no missing `End If` because one of the If statements is a single-line If statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T12:00:49.377", "Id": "471237", "Score": "1", "body": "@M.Doerner That indentation really is misleading then! Maybe op could use Rubberduck's indenter to get the code looking nice, there's an interactive online example [here](http://rubberduckvba.com/indentation) - just paste the code in the box to have it indented. Or [install the addin](https://github.com/rubberduck-vba/Rubberduck/releases/latest) so you can indent from within Excel (and do a lot of other stuff too)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T15:39:55.470", "Id": "471267", "Score": "0", "body": "@M.Doerner you are correct. I was attempting to format after pasting into a blank workbook and had expanded that 1-liner into 2 lines and that broke it. _Mea Culpa_" } ]
[ { "body": "<p>Let me start with a few quick things to enhance readability and then give some pointers how one could make this more maintainable, if one wanted to.</p>\n\n<h2>Magic Numbers</h2>\n\n<p>One thing that makes your code hard to follow is that you use magic numbers instead of named constants at multiple places. You already use <code>vbYesNo</code> for the MsgBox options most of the time. I wonder why you use <code>3</code> instead of <code>vbYesNoCancel</code> in the first message box. Moreover, the code would be more intuitive, if you replaced <code>6</code> by <code>vbYes</code> and <code>7</code> by <code>vbNo</code>. Whenever you want to use an explicit number in code, ask yourself whether there is a constant for that already and, if not, define a constant of your own and give it a semantic name.</p>\n\n<h2>Indentation</h2>\n\n<p>As @Greedo has pointed out in the comments, the strange indentation might be an artifact of how you have posted the code. However, as is, the indentation makes the code unreadable. <code>ElseIf</code>s should line up with the corresponding <code>If</code> statements and their content should be indented one level deeper. Then, you know which level of the tree you are in while reading the code.</p>\n\n<h2>Reuse of Variables</h2>\n\n<p>It is generally confusing in code, if you reuse a local variable. There is no benefit from reusing the variable <code>a</code> here. Still, the reader of the code has to know that it has been reused for an entirely different question in the second part of the procedure.</p>\n\n<h2>Naming</h2>\n\n<p>Code should always strive to be self-documenting. The most important part in this is good naming of variables and procedures. They should always have a name indicating what they are/do; variables, properties and functions should be nouns and procedures should be verbs. Here, expressiveness trumps shortness: there is no problem with having a long name if you cannot express the meaning in a short name. If this leads to a very long name, it might be a smell that you should split something up.\nIn you specific case, all your answers are single letter variables without any meaning, which is not ideal. E.g. a better name for <code>e</code>, or rather <code>e = vbYes</code>, would be <code>nameStartsWithK</code>.\nNote that applying semantic naming would have avoided the reuse of the variable <code>a</code> automatically since there is no sensible common name for the two uses. </p>\n\n<h2>Declaring Variables</h2>\n\n<p>Do yourself a favor and always declare you local variables, e.g. using <code>Dim a As Long</code> right before using <code>a</code> the first time. This documents the variables type and subsequent assignment with an incompatible type will result in an error instead of unexpected behaviour. (VBA does a lot of <em>helpful</em> implicit conversions, though.)</p>\n\n<h2>Option Explicit</h2>\n\n<p>Please, always use <code>Option Explicit</code> on top of your component. You can let the editor add it automatically for new components by ticking <em>Require Variable Declaration</em> under <em>Tools->Options->Editor</em>. This will force you to declare all your variables. A very helpful side-effect is that it will catch typos in uses of your variables. E.g. is you try to reference <code>nameStartsWithK</code> but type <code>nameStartWithK</code>, it will complain that <code>nameStartWithK</code> is not declared. Without <code>Option Explicit</code>, you get a new variable of type <code>Variant</code> instead, which is really not what you want here.</p>\n\n<h2>Use of End</h2>\n\n<p>The <code>End</code> statement is something that usually should never be used. In general, it is unexpected behaviour that a called procedure terminates the entire program. Instead, the procedure should probably use <code>Exit Sub</code> in order to return execution to its caller.</p>\n\n<h2>Use of Single-Line If Statements</h2>\n\n<p>Single-line If statements like <code>If b &lt; 7 Then d = MsgBox(\"do you live in logan?\", vbYesNo)</code> are generlly a bit confusing because there is no <code>End If</code> one starts to expect out of habit. However, this is amplified tremendously without proper indentation since it is not immediate clear for the reader what the next <code>ElseIf</code> refers to. </p>\n\n<h2>Select Case Statement</h2>\n\n<p>For your first <code>If</code> block, a <em>Select Case statement</em> would probably be semantically more appropriate.</p>\n\n<pre><code>Select a\n Case vbYes\n MsgBox \"Let the games begin!\"\n Case vbNo\n MsgBox \"Okay. Press ctrl K to start over.\"\n Case Else\n MsgBox \"Sad. Come back later. Press ctrl K to start.\"\nEnd Select\n</code></pre>\n\n<p>Note that I have removed the option <code>1</code> in the first case, which is <code>vbOKCancel</code>. More on this, next.</p>\n\n<h2>User Experience</h2>\n\n<p>Your first query to the user whether he wants to play a game has two somewhat strange features. </p>\n\n<ol>\n<li>When you confirm that the game starts, you do this in a message box with option <code>vbOKCancel</code> but never react to the result. As the user, I would expect that clicking the Cancel will abort the game. If the effect of <code>Cancel</code> is the same as <code>OK</code>, do not display a <code>Cancel</code> button.</li>\n<li>It is usually percieved as rather annoying, if a dialog pops up in response to cancelling. This is exactly what happens in your first query to the user.</li>\n</ol>\n\n<h2>Using Indirection to Improve Maintainability</h2>\n\n<p>When speaking about maintainability and flexibility one has to ask what you might want to change in the future and what is a hindering proper automated testing. In the case of this simple game, the latter is probably not a real concern, but for parts of larger applications, it is.</p>\n\n<p>The main point of possible change I see here, is the presentation to the user. Not entirely by coincidence, this is also what would hinder any automated testing since blocking dialogs are a pain for that.</p>\n\n<p>This is a bit more advanced, but what you could do to abstract away the use of the message box is to add a new class <code>YesNoUserInteraction</code> with a single function </p>\n\n<pre><code>Public Function UserAgrees(ByVal questionText As String) As Boolean\n UserAgrees = (MsgBox(questionText , vbYesNo) = vbYes)\nEnd Function\n</code></pre>\n\n<p>The you new it up and save it in a variable <code>Dim userInteraction As YesNoUserInteraction</code> in your code <code>Set userInteraction = New YesNoUserInteraction</code> and use that instead of the message box.</p>\n\n<p>Going one step further, you can split out the part newing up the object and pass it as a parameter to the procedure.</p>\n\n<pre><code>Public Sub Decision_tree()\n Dim userInteraction As YesNoUserInteraction\n Set userInteraction = New YesNoUserInteraction\n DecisionTreeImpl userInteraction \nEnd Sub\n\nPrivate Sub DecisionTreeImpl(ByVal userInteraction As YesNoUserInteraction)\n ...\nEnd Sub\n</code></pre>\n\n<p>This has the benefit that another class could implement <code>YesNoUserInteraction</code> and that could be provided as the user interaction to the implementation instead. This way, you can change the presentation entirely, e.g. using a custom user form, or automate the answers for unit testing.</p>\n\n<p>The way it is, the intent to allow other implementations is not really clear though. We can go one step further and introduce a dedicated interface class <code>IYesNoUserInteraction</code> for the interaction.</p>\n\n<pre><code>Public Function UserAgrees(ByVal questionText As String) As Boolean\nEnd Function\n</code></pre>\n\n<p>Then, we can turn <code>YesNorUserInteraction</code> into <code>YesNoMsgBoxInteraction</code> and implement the interface.</p>\n\n<pre><code>Implements IYesNoUserInteraction\n\nPrivate Function IYesNoUserInteraction_UserAgrees(ByVal questionText As String) As Boolean\n UserAgrees = (MsgBox(questionText , vbYesNo) = vbYes)\nEnd Function\n</code></pre>\n\n<p>To get the right names and signatures for the members to implement, you can use the two drop downs at the top of the code pane.</p>\n\n<p>Finally, we can use it in the setup code.</p>\n\n<pre><code>Public Sub Decision_tree()\n Dim userInteraction As IYesNoUserInteraction\n Set userInteraction = New YesNoMsgBoxInteraction\n DecisionTreeImpl userInteraction \nEnd Sub\n\nPrivate Sub DecisionTreeImpl(ByVal userInteraction As IYesNoUserInteraction)\n ...\nEnd Sub\n</code></pre>\n\n<p>This makes it clear that we can provide anything to the procedure that honors the contract to take a question and return an answer in the form of a Boolean with <code>True = Yes</code>.</p>\n\n<p>Obviously, this does not deal with the first question to the user, since you want to allow cancellation. You could do that in a similar way as presented here, but not with a simple Boolean. </p>\n\n<h2>Separation of Responsibilities</h2>\n\n<p>The last observation above points to a further thing that could be improved in your code. Currently, it violates the so-called <em>Single Responsibility Principle</em>. In essence, it states that any unit of computation, e.g. a procedure, should be responsible for one and only one thing. Yours actually is for two: asking the user whether he wants to play at all and playing the game. </p>\n\n<p>What you could do instead is to extract a function and a procedure. The function could ask whether the user wants to play and return <code>True</code> if he wants to play and <code>False</code>, otherwise. Then, the procedure actually playing the game is only called if the user wanted to play.</p>\n\n<p>Since the procedure is not large, this does not seem to be much of a problem that it might change for entirely different reasons: changing how a user is asked and playing the game differently. However, if you ever want to write something more complicated, you should get into the habit of splitting things up into small units with a defined purpose. That makes reading the code and figuring out what it actually does later on much easier.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T03:44:59.643", "Id": "471330", "Score": "0", "body": "Wow thank you @Ivenbach this was super informational. Especially for someone like me who is an newbie to vba. I will start doing this. Thanks for the help!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T04:31:19.803", "Id": "471332", "Score": "0", "body": "Uh... I just edited 2 minor typos. It is @M.Doerner whom you should be thanking. He’s the one that wrote that article, not me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T10:33:25.613", "Id": "471363", "Score": "0", "body": "Thanks @JoshBullough that you appreciate my answer that much. If you find it that helpful, you might want to mark it as the answer. Alternatively, you could wait a few more days to see whether a better answer will be posted." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T11:28:18.613", "Id": "240267", "ParentId": "240249", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T04:46:55.170", "Id": "240249", "Score": "1", "Tags": [ "vba" ], "Title": "Designing a text based guessing game with a branching decision tree" }
240249
<h2>Raw Data & Analysis Objective</h2> <p>There is a company called Nerdina Entertainment (Nerdina for short). It's been decided to optimize the operation costs of 4 departments (see below). These have 4 types of specialists on staff. Each of the 4 types is characterized by three base properties: pay rate per month, gallons of coffee consumed per month and (just for the fun of it) the amount of code units (whatever this means) produced per month. Additionally, Nerdina employs a system of grades: each employee is assigned a grade that affects their monthly pay rate. Head of a department is a special status that alters all of the base stats. The summary of the available data is in the next sections.</p> <p>The preliminary goal is to produce a report like this:</p> <pre> +--------------+-------+------------+--------------+------------+---------------+ | DEPARTMENT | STAFF | LABOR COST | COFFEE DRUNK | CODE UNITS | COST PER UNIT | +--------------+-------+------------+--------------+------------+---------------+ | Analytics | 17 | 142,450 | 102 | 1,037 | 137.4 | +--------------+-------+------------+--------------+------------+---------------+ | Training | 16 | 129,050 | 102 | 1,265 | 102 | +--------------+-------+------------+--------------+------------+---------------+ | Development | 36 | 335,150 | 224 | 3,175 | 105.6 | +--------------+-------+------------+--------------+------------+---------------+ | Sales | 28 | 218,450 | 131 | 1,045 | 209 | <b>+--------------+-------+------------+--------------+------------+---------------+ | TOTAL | 97 | 825,100 | 559 | 6,522 | 554 | +--------------+-------+------------+--------------+------------+---------------+ | AVERAGE | 24.25 | 206,275 | 139.75 | 1,630.5 | 138.5 | +--------------+-------+------------+--------------+------------+---------------+</b> </pre> <h2>Employee Types</h2> <p>Base stats. The figures for pay rate, coffee consumption and code units produced are per month.</p> <pre> +----------+---------+--------+------+ | TYPE | PAYRATE | COFFEE | CODE | +----------+---------+--------+------+ | Manager | 7,000 | 5 | 75 | +----------+---------+--------+------+ | Marketer | 6,600 | 4 | 5 | +----------+---------+--------+------+ | Engineer | 8,300 | 8 | 200 | +----------+---------+--------+------+ | Analyst | 7,500 | 12 | 125 | +----------+---------+--------+------+ </pre> <p>NOTE: Heads of the departments earn and drink two times the base figure and don't produce any code.</p> <h2>Grades</h2> <pre> +-------+-----------+ | GRADE | PAYRATE | +-------+-----------+ | 1 | base | +-------+-----------+ | 2 | base×1.25 | +-------+-----------+ | 3 | base×1.5 | +-------+-----------+ </pre> <h2>Staff</h2> <p>E.g. 6×man3 translates to 6 Managers of Grade 3</p> <pre> +--------------+-------------------------------------------------+ | DEPARTMENT | STAFF | +--------------+-------------------------------------------------+ | Analytics | 9×man1, 3×man2, 2×ana3, 2×mar1 + chief 1×man2 | +--------------+-------------------------------------------------+ | Training | 8×man1, 3×mar1, 2×ana1, 2×eng2 + chief 1×man2 | +--------------+-------------------------------------------------+ | Development | 12×man2, 10×mar1, 8×eng2, 5×ana3 + chief 1×eng3 | +--------------+-------------------------------------------------+ | Sales | 13×man1, 11×mar2, 3×mar3 + chief 1×man1 | +--------------+-------------------------------------------------+ </pre> <h2>My Solution</h2> <p>This is a long one.</p> <pre><code>&lt;?php /** * input.php * the input format is determined by me based on the given data. * I've been told by the peers that the current one is way too complicated and * the array should look like this: * $input = [ * ['Analytics', 9, Employee::MANAGER, 1], * ['Training', 8, Employee::MANAGER, 1], * ... * ]; * Please advise on this point */ $input = [ 'Analytics' =&gt; [ [9, Employee::MANAGER, 1], [3, Employee::MANAGER, 2], [2, Employee::ANALYST, 3], [2, Employee::MARKETER, 1], [1, Employee::MANAGER, 2, true] ], 'Training' =&gt; [ [8, Employee::MANAGER, 1], [3, Employee::MARKETER, 1], [2, Employee::ANALYST, 1], [2, Employee::ENGINEER, 2], [1, Employee::MANAGER, 2, true] ], 'Development' =&gt; [ [12, Employee::MANAGER, 2], [10, Employee::MARKETER, 1], [8, Employee::ENGINEER, 2], [5, Employee::ANALYST, 3], [1, Employee::ENGINEER, 3, true] ], 'Sales' =&gt; [ [13, Employee::MANAGER, 1], [11, Employee::MARKETER, 2], [3, Employee::MARKETER, 3], [1, Employee::MANAGER, 1, true] ] ]; /** * padstring.php * a function facilitating the report output later on */ function padString($string, $length, $side = "right", $pad = " ") { if (strlen($string) == $length) { return $string; } else { $charsNeeded = $length - strlen($string); // 5 $padding = str_repeat($pad, $charsNeeded); ($side == "right") ? ($string = $string . $padding) : ($string = $padding . $string); return $string; } } /** * classes.php */ abstract class Employee { const MANAGER = "Manager"; const MARKETER = "Marketer"; const ENGINEER = "Engineer"; const ANALYST = "Analyst"; protected int $grade; protected bool $chief; public function __construct(int $grade, bool $chief = false) { $this-&gt;grade = $grade; $this-&gt;chief = $chief; } /** * the following methods are in place to make sure all subclasses * include the base properties returned by these methods */ abstract public function getBaseRate(); abstract public function getBaseCoffeeConsumption(); abstract public function getBaseCodeProduced(); public function getActualPay(): float { $rate = $this-&gt;getBaseRate(); if ($this-&gt;grade == 2) { $rate *= 1.25; } elseif ($this-&gt;grade == 3) { $rate = $rate * 1.5; } return $this-&gt;chief ? $rate * 2 : $rate; } public function getActualCoffeeConsumption(): float { return $this-&gt;chief ? $this-&gt;getBaseCoffeeConsumption() * 2 : $this-&gt;getBaseCoffeeConsumption(); } public function getActualCodeProduced(): int { return $this-&gt;chief ? 0 : $this-&gt;getBaseCodeProduced(); } } class Manager extends Employee { protected $baseRate = 7000; protected $baseCoffeeConsumption = 5; protected int $baseCodeProduced = 75; public function getBaseRate(): float { return $this-&gt;baseRate; } public function getBaseCoffeeConsumption(): float { return $this-&gt;baseCoffeeConsumption; } public function getBaseCodeProduced(): int { return $this-&gt;baseCodeProduced; } } class Marketer extends Employee { protected $baseRate = 6600; protected $baseCoffeeConsumption = 4; protected int $baseCodeProduced = 5; public function getBaseRate(): float { return $this-&gt;baseRate; } public function getBaseCoffeeConsumption(): float { return $this-&gt;baseCoffeeConsumption; } public function getBaseCodeProduced(): int { return $this-&gt;baseCodeProduced; } } class Engineer extends Employee { protected $baseRate = 8300; protected $baseCoffeeConsumption = 8; protected int $baseCodeProduced = 200; public function getBaseRate(): float { return $this-&gt;baseRate; } public function getBaseCoffeeConsumption(): float { return $this-&gt;baseCoffeeConsumption; } public function getBaseCodeProduced(): int { return $this-&gt;baseCodeProduced; } } class Analyst extends Employee { protected $baseRate = 7500; protected $baseCoffeeConsumption = 12; protected int $baseCodeProduced = 125; public function getBaseRate(): float { return $this-&gt;baseRate; } public function getBaseCoffeeConsumption(): float { return $this-&gt;baseCoffeeConsumption; } public function getBaseCodeProduced(): int { return $this-&gt;baseCodeProduced; } } class Department { protected string $name; protected array $staff; public function __construct($name) { $this-&gt;name = $name; } public function getName() { return $this-&gt;name; } public function addToStaff(Employee $employee) { $this-&gt;staff[] = $employee; } public function getStaffNumber() { return count($this-&gt;staff); } public function getLaborCost() { $laborCost = 0; foreach ($this-&gt;staff as $employee) { $laborCost += $employee-&gt;getActualPay(); } return $laborCost; } public function getCoffeeConsumption() { $coffee = 0; foreach ($this-&gt;staff as $employee) { $coffee += $employee-&gt;getActualCoffeeConsumption(); } return $coffee; } public function getCodeProduced() { $code = 0; foreach ($this-&gt;staff as $employee) { $code += $employee-&gt;getActualCodeProduced(); } return $code; } public function getCostPerUnit() { return round($this-&gt;getLaborCost() / $this-&gt;getCodeProduced(), 2); } } class Company { protected array $depts; public function __construct(array $depts) { $this-&gt;depts = $depts; } public function getDepts() { return $this-&gt;depts; } public function getTotalStaffNumber() { $staffNumber = 0; foreach ($this-&gt;depts as $dept) { $staffNumber += $dept-&gt;getStaffNumber(); } return $staffNumber; } public function getTotalLaborCost() { $laborCost = 0; foreach ($this-&gt;depts as $dept) { $laborCost += $dept-&gt;getLaborCost(); } return $laborCost; } public function getTotalCoffeeConsumption() { $coffee = 0; foreach ($this-&gt;depts as $dept) { $coffee += $dept-&gt;getCoffeeConsumption(); } return $coffee; } public function getTotalCodeProduced() { $code = 0; foreach ($this-&gt;depts as $dept) { $code += $dept-&gt;getCodeProduced(); } return $code; } public function getTotalCostPerUnit() { $cost = 0; foreach ($this-&gt;depts as $dept) { $cost += $dept-&gt;getCostPerUnit(); } return $cost; } public function getAverageStaffNumber() { return round($this-&gt;getTotalStaffNumber() / count($this-&gt;depts), 2); } public function getAverageLaborCost() { return round($this-&gt;getTotalLaborCost() / count($this-&gt;depts), 2); } public function getAverageCoffeeConsumption() { return round($this-&gt;getTotalCoffeeConsumption() / count($this-&gt;depts), 2); } public function getAverageCodeProduced() { return round($this-&gt;getTotalCodeProduced() / count($this-&gt;depts), 2); } public function getAverageCostPerUnit() { return round($this-&gt;getTotalCostPerUnit() / count($this-&gt;depts), 2); } /** * should I use echo or is it better to put the entire report string in a variable * and return it? */ public function printReport() { $regcol = 15; $widecol = 20; echo padString('DEPARTMENT', $widecol) . padString('STAFF', $regcol, 'left') . padString('LABOR COST', $regcol, 'left') . padString('COFFEE DRUNK', $regcol, 'left') . padString('CODE UNITS', $regcol, 'left') . padString('COST PER UNIT', $regcol, 'left') . "\n"; echo padString('=', $widecol, 'right', '=') . padString('=', $regcol, 'right', '=') . padString('=', $regcol, 'right', '=') . padString('=', $regcol, 'right', '=') . padString('=', $regcol, 'right', '=') . padString('=', $regcol, 'right', '=') . "\n"; foreach ($this-&gt;depts as $dept) { echo padString($dept-&gt;getName(), $widecol) . padString($dept-&gt;getStaffNumber(), $regcol, 'left') . padString($dept-&gt;getLaborCost(), $regcol, 'left') . padString($dept-&gt;getCoffeeConsumption(), $regcol, 'left') . padString($dept-&gt;getCodeProduced(), $regcol, 'left') . padString($dept-&gt;getCostPerUnit(), $regcol, 'left') . "\n"; } echo padString('=', $widecol, 'right', '=') . padString('=', $regcol, 'right', '=') . padString('=', $regcol, 'right', '=') . padString('=', $regcol, 'right', '=') . padString('=', $regcol, 'right', '=') . padString('=', $regcol, 'right', '=') . "\n"; echo padString('TOTAL', $widecol) . padString($this-&gt;getTotalStaffNumber(), $regcol, 'left') . padString($this-&gt;getTotalLaborCost(), $regcol, 'left') . padString($this-&gt;getTotalCoffeeConsumption(), $regcol, 'left') . padString($this-&gt;getTotalCodeProduced(), $regcol, 'left') . padString($this-&gt;getTotalCostPerUnit(), $regcol, 'left') . "\n"; echo padString('AVERAGE', $widecol) . padString($this-&gt;getAverageStaffNumber(), $regcol, 'left') . padString($this-&gt;getAverageLaborCost(), $regcol, 'left') . padString($this-&gt;getAverageCoffeeConsumption(), $regcol, 'left') . padString($this-&gt;getAverageCodeProduced(), $regcol, 'left') . padString($this-&gt;getAverageCostPerUnit(), $regcol, 'left') . "\n"; } } /** * main.php */ function makeDepts(array $input): array { $depts = []; foreach ($input as $dept =&gt; $staff) { $currentDept = new Department($dept); foreach ($staff as $employeeGroup) { $quantity = $employeeGroup[0]; $type = $employeeGroup[1]; $grade = $employeeGroup[2]; $chief = isset($employeeGroup[3]) ? true : false; for ($c = 0; $c &lt; $quantity; $c++) { $employeeObject = new $type($grade, $chief); $currentDept-&gt;addToStaff($employeeObject); } } $depts[] = $currentDept; } return $depts; } $depts = makeDepts($input); $company = new Company($depts); $company-&gt;printReport(); </code></pre> <p>I'd appreciate any comments or suggestions!</p>
[]
[ { "body": "<ul>\n<li><p>I find it odd that you have declared <code>padString()</code> despite php already offering <a href=\"https://www.php.net/manual/en/function.str-pad.php\" rel=\"nofollow noreferrer\">str_pad()</a>.</p></li>\n<li><p>I think I'd favor declaring <code>grade</code>-based rate multipliers as a configurable lookup array rather than a hardcoded condition block. This way you can maintain that logic without touching the method.</p></li>\n<li><p>There is a lot of duplicated method logic in the Department class, this could be D.R.Y.ed out with a single summing method that is fed the correct method name by which to fetch the correct data.</p></li>\n<li><p>The same advice applies to your Company class regarding the repeated summing and averaging methods.</p></li>\n<li><p>I recommend that all elements in the <code>$input</code> rows be declared with a consistent number of rows. In other words, you shouldn't need to check if <code>$employeeGroup[3]</code> is set. This way you can unpack the row values into readable individual values from within the nested <code>foreach()</code> declaration. <a href=\"https://3v4l.org/SbgZs\" rel=\"nofollow noreferrer\">Demo</a></p>\n\n<pre><code>foreach ($input as $dept =&gt; $staff) {\n foreach ($staff as [$quantity, $type, $grade, $chief]) {\n ...\n }\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T08:44:06.473", "Id": "471348", "Score": "1", "body": "Thank you very much for your comment! It is immensely helpful. I haven't ever built any meaningful projects yet, so your post provided much TIL knowledge. I had no idea about the existence of `str_pad()` or the nifty format of `foreach` loop that you demonstrated. I've found just two possible syntaxes in the official manual, so I've learnt a great deal from your recommendations, and they've rendered my code so much more concise. I can't thank you enough!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T08:47:15.880", "Id": "471350", "Score": "0", "body": "Family time now. Later, when I am free." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T09:00:22.327", "Id": "471353", "Score": "0", "body": "Oooof, I'm have a super hard time figuring out formatting on here.\nThank you, @mickmackusa I'm looking forward to your further assessment!\n\nI'm still struggling to come up with declaring a single method that would unify the series of those you mentioned as having duplicated logic. Indeed, pretty much all of my Department and Company methods exhibit this flaw. For instance, Department's getLaborCost(), getCoffeeConsumption() and getCodeProduced() could be summarized into something like this:" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T09:03:30.093", "Id": "471354", "Score": "0", "body": "`public function getData() {`\n `$data = 0;`\n `foreach ($this->staff as $employee) {`\n `$data += $employee->callASpecificEmployeeMethod();`\n `}`\n `return $data;`\n `}`\n\nI am sorry, but for some reason selecting this chunk of code and pressing Ctrl+K doesn't yield the desired effect." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T09:36:35.157", "Id": "471358", "Score": "1", "body": "Comments do not enjoy the same formatting niceties. Backticking is the only way. Look, this demo isn't instantly ready for your script, but the basic premise is that you have a single method that makes iterated calls of a method based on a passed-in variable. https://3v4l.org/B7bcC" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T05:23:48.617", "Id": "471597", "Score": "0", "body": "Wow! Following your advice I have managed to slash a whole lot of repetitive logic off my code. Thank you so much once again, Matt! I'm not sure if it's okay if I continue to bug you with this code, so if it's not, please just ignore this message!\nPrinting out the report was the preparatory stage, so now I'm going to have to continue working on it to illustrate some of the ideas that Nerdina's Board of Directors has come up with to optimize the cost of production. They involve various measures like laying some staff off, bumping the salary as well as promotion and demotion of others." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T05:24:01.580", "Id": "471598", "Score": "0", "body": "So what I was going to start with is creating three separate methods within the Company class that would clone the objects contained within the $depts property, alter them and then use them to create three new respective Company objects so that I can use the printReport() method on each of them. This way I can create just one Company object -- $company -- and then call $company->printPlan1(), $company->printPlan2() and $company->printPlan3().\nSo I was wondering if it's even common practice to declare methods within Class A that spew out objects of the very same Class A?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T10:31:19.083", "Id": "240266", "ParentId": "240250", "Score": "1" } } ]
{ "AcceptedAnswerId": "240266", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T04:59:00.357", "Id": "240250", "Score": "2", "Tags": [ "php", "object-oriented" ], "Title": "Expenses Calculation Using OOP in PHP" }
240250
<p><a href="https://leetcode.com/problems/increasing-order-search-tree/" rel="nofollow noreferrer">https://leetcode.com/problems/increasing-order-search-tree/</a></p> <p>Please review for performance<br></p> <blockquote> <p>Given a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.</p> </blockquote> <p><a href="https://i.stack.imgur.com/hryJW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hryJW.png" alt="enter image description here"></a></p> <blockquote> <p>Constraints:</p> <p>The number of nodes in the given tree will be between 1 and 100. Each node will have a unique integer value from 0 to 1000.</p> </blockquote> <pre><code>using System.Collections.Generic; using GraphsQuestions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TreeQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/increasing-order-search-tree/ /// &lt;/summary&gt; [TestClass] public class IncreasingBstTest { [TestMethod] public void ExampleTest() { // 5 // / \ // 3 6 // / \ \ // 2 4 8 // / / \ // 1 7 9 TreeNode root = new TreeNode(5); root.left = new TreeNode(3); root.left.left = new TreeNode(2); root.left.right = new TreeNode(4); root.left.left.left = new TreeNode(1); root.right = new TreeNode(6); root.right.right = new TreeNode(8); root.right.right.left = new TreeNode(7); root.right.right.right = new TreeNode(9); var forEach = new InOrderForEach(); root = forEach.IncreasingBST(root); int res = 1; var curr = root; while (curr != null) { Assert.AreEqual(res, curr.val); curr = curr.right; res++; } } } } public class InOrderForEach { public TreeNode IncreasingBST(TreeNode root) { if (root == null) { return null; } List&lt;int&gt; vals = new List&lt;int&gt;(); InOrder(root, vals); var ans = new TreeNode(0); TreeNode curr = ans; foreach (var v in vals) { curr.right = new TreeNode(v); curr = curr.right; } return ans.right; } private void InOrder(TreeNode root, List&lt;int&gt; vals) { if (root == null) { return; } InOrder(root.left, vals); vals.Add(root.val); InOrder(root.right, vals); } } } </code></pre>
[]
[ { "body": "<p>There isn't much to review. <code>InOrder()</code> is merely a depth-first-search, so maybe I would call it that.</p>\n\n<p>You could though optimize a bit, if you created the new \"tree\" as you traverse the old one:</p>\n\n<pre><code> public class InOrderForEach\n {\n TreeNode newRoot = new TreeNode(0);\n TreeNode current = null;\n\n public TreeNode IncreasingBST(TreeNode root)\n {\n if (root == null)\n {\n return null;\n }\n current = newRoot;\n InOrder(root);\n return newRoot.right;\n }\n\n private void InOrder(TreeNode root)\n {\n if (root == null)\n {\n return;\n }\n InOrder(root.left);\n current = current.right = new TreeNode(root.val);\n InOrder(root.right);\n }\n\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T12:59:48.327", "Id": "471245", "Score": "1", "body": "Thank you as always. This will be o(H) i kike it" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T11:38:13.600", "Id": "240268", "ParentId": "240251", "Score": "2" } } ]
{ "AcceptedAnswerId": "240268", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T05:35:15.610", "Id": "240251", "Score": "2", "Tags": [ "c#", "programming-challenge", "binary-search-tree" ], "Title": "LeetCode: Increasing Order Search Tree C#" }
240251
<p>After poking around in some areas of python, I've decided to try Pygame. After about two hours of coding, this is what I came up with:</p> <pre><code>import pygame import time import random pygame.init() pygame.font.init() WINDOW = pygame.display.set_mode((500, 500)) pygame.display.set_caption('snake') FOOD_COORS = [] TICK = 15 RUN = True SNAKE_COMP = [[50, 50, 2], [40, 50, 2], [30, 50, 2], [20, 50, 2], [10, 50, 2]] f = [random.randint(0, 50)*10, random.randint(0, 50)*10] d = 2 CLOCK = pygame.time.Clock() def hit(): time.sleep(3) pygame.quit() class snake(): def __init__(self, SNAKE_COMP): self.x, self.y = SNAKE_COMP[0][0:2] def draw(self, SNAKE_COMP): self.SNAKE_COMP = SNAKE_COMP for i in range(0, len(SNAKE_COMP)): pygame.draw.rect(WINDOW, (255, 255, 255), (SNAKE_COMP[i][0], SNAKE_COMP[i][1], 10, 10)) def hit_check(self, SNAKE_COMP): self.SNAKE_COMP = SNAKE_COMP if SNAKE_COMP[0][0] &gt;= 500 or SNAKE_COMP[0][0] &lt; 0: hit() if SNAKE_COMP[0][1] &gt;= 500 or SNAKE_COMP[0][1] &lt; 0: hit() test_l = [[]] for i in range(0, len(SNAKE_COMP)): test_l.append(tuple(SNAKE_COMP[i][0:2])) for i in range(0, len(test_l)): if test_l.count(test_l[i]) &gt; 1: hit() class food(): global FOOD_COORS def draw(self): x, y = self.x, self.y pygame.draw.rect(WINDOW, (255, 255, 255), (x, y, 10, 10)) def spawn(self, SNAKE_COMP): global FOOD_COORS self.SNAKE_COMP = SNAKE_COMP test_l = [[]] for i in range(0, len(SNAKE_COMP)): test_l.append(SNAKE_COMP[i][0:2]) g = True while g: x = random.randint(0, 49)*10 y = random.randint(0, 49)*10 if [x, y] not in test_l: g = False FOOD_COORS = [x, y] self.x, self.y = x, y snek = snake(SNAKE_COMP) apple = food() apple.spawn(SNAKE_COMP) s = False g = False while RUN: CLOCK.tick(TICK) for event in pygame.event.get(): if event.type == pygame.QUIT: RUN = False keys = pygame.key.get_pressed() if keys[pygame.K_UP] and d != 3: d = 1 elif keys[pygame.K_RIGHT] and d != 4: d = 2 elif keys[pygame.K_DOWN] and d != 1: d = 3 elif keys[pygame.K_LEFT] and d != 2: d = 4 if g != True and SNAKE_COMP[0][0:2] != FOOD_COORS: last = len(SNAKE_COMP) - 1 for i in range(1, len(SNAKE_COMP)): SNAKE_COMP[len(SNAKE_COMP)-i][2] = SNAKE_COMP[len(SNAKE_COMP)-i-1][2] SNAKE_COMP[0][2] = d for i in range(0, len(SNAKE_COMP)): if SNAKE_COMP[i][2] == 1: SNAKE_COMP[i][1] -= 10 elif SNAKE_COMP[i][2] == 2: SNAKE_COMP[i][0] += 10 elif SNAKE_COMP[i][2] == 3: SNAKE_COMP[i][1] += 10 elif SNAKE_COMP[i][2] == 4: SNAKE_COMP[i][0] -= 10 else: k = SNAKE_COMP[0][2] FOOD_COORS.append(k) if k == 1: FOOD_COORS[1] -= 10 elif k == 2: FOOD_COORS[0] += 10 elif k == 3: FOOD_COORS[1] += 10 elif k == 4: FOOD_COORS[0] -= 10 SNAKE_COMP.insert(0, FOOD_COORS) apple.spawn(SNAKE_COMP) snek.hit_check(SNAKE_COMP) apple.draw() snek.draw(SNAKE_COMP) pygame.display.update() WINDOW.fill((0, 0, 0)) pygame.quit() </code></pre> <p>I definitely thinks this can be improved, just not sure how.</p>
[]
[ { "body": "<p>This isn't really todo with the code, but, it's always a good idea to add comments to your code to make it more readable and understandable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T15:42:06.083", "Id": "240286", "ParentId": "240254", "Score": "2" } }, { "body": "<p>The variable names are not good.</p>\n<p>What is <code>f</code>? What is <code>d</code>? What does <code>SNAKE_COMP</code> even mean? I understand the first two values in it to be coordinates, but what is the third, and since it's always 2, why is it not a constant?</p>\n<p>What does <code>hit</code> mean? Hitting the wall? Hitting food? Hitting another snake? Collision is another common term which is a bit more clear.</p>\n<p>What is <code>FOOD_COORS</code>? Is it supposed to be COOR<strong>D</strong>S ?</p>\n<p>I guess <code>d</code> is direction. Then name it <code>direction</code>. And use names for the directions, don't call them 1, 2, 3, 4.</p>\n<p>If you make the code readable, it increases the chance that others will take time to read it and give feedback.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T00:48:51.743", "Id": "247747", "ParentId": "240254", "Score": "0" } }, { "body": "<ul>\n<li><p>The names of classes should be in CamelCase instead of snake_case.<br />\nThe class names <code>snake</code> and <code>food</code> should be capitalized.</p>\n</li>\n<li><p>Argument names should be in lowercase.<br />\n<code>SNAKE_COMP</code> can be changed to <code>snake_comp</code> or something similar to that.</p>\n</li>\n<li><p>You should not instance attributes outside of <code>__init__</code>.<br />\n<code>self.SNAKE_COMP</code> should be declared inside <code>__init__</code> or should be removed completely, since it's not being used at all in either of the classes.</p>\n</li>\n<li><p>You don't need parenthesis after a class name unless you are inheriting from another class.<br />\n<code>Snake()</code> and <code>Food()</code> should just be <code>Snake</code> and <code>Food</code> respectively</p>\n</li>\n<li><p>As @JamesRobinson correctly said so, add comments to the ambiguous parts of your code so the readers will be able to understand what it is supposed to do.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T09:52:53.267", "Id": "247768", "ParentId": "240254", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T05:59:43.097", "Id": "240254", "Score": "3", "Tags": [ "python", "python-3.x", "pygame", "snake-game" ], "Title": "Pygame snake as first game" }
240254
<p>So the idea came from the fact that</p> <ul> <li><code>connmanctl</code> only completes filenames/directories when used non-interactively,</li> <li>whereas when used interactively (executing <code>connmanctl</code> without arguments an interactive shell is started), it does support autocompletion, but when it comes to completing services (wifi networks, ethernet connections, bluetooth devices, ...) it completes the <em>service path</em> (as it is referred to in <code>man connmanctl</code>, instead of the name of the connection. In other words, if a line of <code>connmanctl services</code> is the following <pre><code>myHomeWifi wifi_79829c350ea0_41542d233241335454_managed_psk </code></pre> then <code>connmanctl connect wifi&lt;Tab&gt;</code> will complete the second string, whereas I would like <code>connmanctl connect myH&lt;Tab&gt;</code> to complete the first.</li> </ul> <p>If there is an in-<code>connmanctl</code> solution, feel free to point me to that, but I took this unpleasant feature of <code>connmanctl</code> as a chance to write a wrapper for it which also handles autocompletion.</p> <p>The wrapper itself is just this:</p> <pre class="lang-bsh prettyprint-override"><code>#!/usr/bin/env bash declare -A map eval "$(command connmanctl services | \ awk 'NF &gt; 1 { print "map["$(NF - 1)"]="$NF; next } { print "map["$NF"]="$NF }')" i=0 declare -a args for arg in "$@"; do [[ "${map[$arg]}" ]] &amp;&amp; args[i++]="${map[$arg]}" || args[i++]="$arg" done command connmanctl "${args[@]}" </code></pre> <p>Essentially it does the following:</p> <ul> <li>It should be called with the same arguments you would call <code>connmanctl</code>.</li> <li>Builds an associative array out of <code>connmanctl services</code>'s output,</li> <li>loops on the command line arguments and substitutes the <code>wifi_*</code>-like string if the other string matched (I guess this is a weak point, in the case a service is named, for instance, <code>connect</code>),</li> <li>and then forwards the modified list of arguments to <code>connmanctl</code>.</li> </ul> <p>The autocompletion is handled by the following script, where the heredoc is handmade by exploring how <code>connmanctl</code> completes.</p> <pre class="lang-bsh prettyprint-override"><code>#!/usr/bin/env bash main='ConnMan' _ConnMan_completions() { mapfile -t COMPREPLY &lt; &lt;(compgen -W "$(__compListGen "${COMP_WORDS[@]}")" -- "${COMP_WORDS[$COMP_CWORD]}") } __compListGen() { __tree | __subTree "$@" | __expandServices | __dropChildren } __subTree() { # forward in to out if no args (( $# == 0 )) &amp;&amp; tee &amp;&amp; return # remove the last parameter if it's being completed (( $# == COMP_CWORD + 1 )) &amp;&amp; set -- "${@:1:$(($# - 1))}" # process first entry and pipe recursively one=$1 shift __getNode "$one" &lt; /dev/stdin | __subTree "$@" } __getNode() { # all services match a common string in the heredoc [[ "$(command connmanctl services)" =~ $1 ]] &amp;&amp; set -- '@services' # if first line matching $1 is followed by @repeat line, # print only these two; if not, print only lines beginning # with tab, up to the next line not beginning with tab sed -E '/(^| )'"$1"'( |$)/,/^[^\t]/{ /^\t@repeat$/{H;x;p;Q} h /^\t/s/\t//p } d' /dev/stdin } __expandServices() { input=$(&lt; /dev/stdin) case "$input" in [^@]* ) echo "$input" ;; @services* ) command connmanctl services | \ sed -E 's/^[^ ]* *([^ ].*[^ ]) *[^ ]*$/\1/ s/^ *//' ;; # the default case is not needed, as this case # statement is tightly bounded to the heredoc below esac } __dropChildren() { sed '/^\t/d' /dev/stdin } __tree() { # The heredoc below hardcodes connmanctl's completion tree. # The special entry @services refers to when connmanctl # completes with the available services, whereas the # entry @repeat refers to when connmanctl keeps giving # the same alternative completions as the for the last # word. cat &lt;&lt;EOF $main agent on off clock config @services autoconnect domains ipv4 ipv6 mdns nameservers proxy remove timeservers @repeat connect @services disable ethernet offline wifi disconnect @services enable ethernet offline wifi exit help monitor manager on off services on off tech on off vpnconnection on off vpnmanager on off move-after @services move-before @services peer_service peers quit scan ethernet wifi services @services session bearers ctxid ifname srciprule type @repeat state technologies tether ethernet on off wifi on off tethering_clients vpnagent on off vpnconnections EOF } complete -o default -F _ConnMan_completions $main </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T07:19:02.023", "Id": "240257", "Score": "2", "Tags": [ "bash", "sed", "awk", "autocomplete" ], "Title": "Bash wrapper for connmanctl with autocompletion" }
240257
<p>I manage the Python API for the Manganelo (and Mangakalot) sites and I am not fully convinced that the code structure I currently use is the best. (<a href="https://github.com/nixonjoshua98/manganelo" rel="nofollow noreferrer">https://github.com/nixonjoshua98/manganelo</a>)</p> <p>The API has various objects (MangaInfo, SearchManga, DownloadChapter) and an example of the usage are as follows.</p> <pre><code>from manganelo import SearchManga search = SearchManga("Naruto") search.start() for result in search: print(result.title, result.url) </code></pre> <p>~ ~ ~</p> <pre><code>from manganelo import extras search = extras.SearchMangaThread("Naruto") search.start() # Start the search thread # do stuff here while we search in the background search.wait() # Wait for the search to finish if it hasn't already for r in search: print(r) </code></pre> <p>The usage of multiple objects simply feels weird to me, and could be improved upon. The source code of this particular object is below.</p> <pre><code>class SearchManga: def __init__(self, query: str) -&gt; None: """ :param query: Query string to search for, we strip the 'illegal' characters ourselves. """ self.query: str = query self.results: list = [] def __str__(self): """ Return the query string which was passed in at construction. """ return self.query def __enter__(self): """ Context manager entry point. Call .start() before we return the instance. """ self.start() return self def __exit__(self, exc_type, exc_val, exc_tb): """ Context manager exit point """ def __len__(self) -&gt; int: """ Return the length of the internal results list """ return len(self.results) def __getitem__(self, item): """ Index the internal list """ return self.results[item] def __contains__(self, item): """ Check if an item exists in the results """ return item in self.results def __iter__(self): """ Used in loops. Simply return results.__iter__ """ return iter(self.results) def start(self): """ This is where the magic happens. Sends the request and extracts the information we want. """ # Generate the URL, which includes removing 'illegal' characters url = self._generate_url(self.query) # Send the request. Can also raise an exception is the request fails. response = utils.send_request(url) # Entire page soup soup = BeautifulSoup(response.content, "html.parser") # List of the search results results = soup.find_all(class_="search-story-item") # Iterate over the results soup and extract the information we want for i, ele in enumerate(results): manga = utils.find_or_raise(ele, class_="item-img") title = manga.get("title", None) # Manga title link = manga.get("href", None) # Link to the manga 'homepage' r = MangaSearchResult(title=title, url=link) self.results.append(r) def _generate_url(self, query: str) -&gt; str: """ Generate the URL we send the request to, we remove all 'illegal' characters here from the query string. :param str query: THe base query string which we are searching for :return str: Return the formatted URL """ allowed_characters: str = string.ascii_letters + string.digits + "_" query = "".join([char.lower() for char in query.replace(" ", "_") if char in allowed_characters]) return "http://manganelo.com/search/" + query </code></pre> <p>The object above implements majority of the <code>list</code> special methods but forwards them to an internal list since I don't like inheriting from the core types.</p> <p><strong>utils</strong></p> <pre><code>def find_or_raise(soup: BeautifulSoup, *, class_: str) -&gt; Union[bs4.element.Tag, bs4.element.PageElement]: """ Attempts to find a class inside the soup, if the tag cannot be found then raise an exception. :param BeautifulSoup soup: The soup we will try to find the class &lt;class_&gt; in. :param str class_: The class name we are searching for. :return: We return the element which is a bs4 Tag, but PyCharm marks it as a bs4 PageElement so we use a Union and mark it as both types. """ element = soup.find(class_=class_) if element is None: raise TagNotFound(f"Tag not found") return element def send_request(url: str, *, timeout: int = 5) -&gt; requests.Response: """ Send a request to the URL provided :param str url: The URL which we are sending a GET request to. :param timeout: Optional parameter which decides how long we wait before throwing an exception :return: The response object """ default_headers = requests.utils.default_headers() r = requests.get(url, stream=True, timeout=timeout, headers=default_headers) r.raise_for_status() return r </code></pre> <p>~ ~ ~</p> <pre><code>class SearchMangaThread(SearchManga): def __init__(self, query: str): super(SearchMangaThread, self).__init__(query) self._thread = threading.Thread(target=super(SearchMangaThread, self).start) def start(self): self._thread.start() def wait(self): self._thread.join() def done(self): return not self._thread.is_alive() def __enter__(self): self.start() return self </code></pre> <p>Looking for any improvements in the overall usage of the API or the code objects. I can add other object examples from the repo if requested.</p> <p><strong>Updated</strong></p> <pre><code>class SearchManga: def __init__(self, query: str, *, threaded: bool = False) -&gt; None: """ :param query: Query string to search for, we strip the 'illegal' characters ourselves. """ self.query: str = query self._response = None if threaded: self._thread = threading.Thread(target=self._start) self._thread.start() else: self._start() def _start(self): # Generate the URL, which includes removing 'illegal' characters url = self._generate_url(self.query) # Send the request. Can also raise an exception is the request fails. self._response = utils.send_request(url) def results(self): """ This is where the magic happens. Sends the request and extracts the information we want. """ if hasattr(self, "_thread") and self._thread.is_alive(): self._thread.join() # Entire page soup soup = BeautifulSoup(self._response.content, "html.parser") # List of the search results results = soup.find_all(class_="search-story-item") # Iterate over the results soup and extract the information we want for i, ele in enumerate(results): manga = utils.find_or_raise(ele, class_="item-img") title = manga.get("title", None) # Manga title link = manga.get("href", None) # Link to the manga 'homepage' yield MangaSearchResult(title=title, url=link) @staticmethod def _generate_url(query: str) -&gt; str: """ Generate the URL we send the request to, we remove all 'illegal' characters here from the query string. :param str query: THe base query string which we are searching for :return str: Return the formatted URL """ allowed_characters: str = string.ascii_letters + string.digits + "_" query = "".join([char.lower() for char in query.replace(" ", "_") if char in allowed_characters]) return "http://manganelo.com/search/" + query </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T14:48:07.197", "Id": "471259", "Score": "0", "body": "Where is `APIBase` defined?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T14:52:20.653", "Id": "471260", "Score": "0", "body": "@Reinderien I actually removed the base class since posting since it only included two static methods. I have updated the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T18:49:01.350", "Id": "471290", "Score": "0", "body": "Please revert your latest edit and move the new code to a new question." } ]
[ { "body": "<p>In my opinion all of the machinery to make <code>SearchManga</code> iterable is needless. Simply change <code>start</code> to <code>yield</code> its results:</p>\n\n<pre><code> # Iterate over the results soup and extract the information we want\n for i, ele in enumerate(results):\n manga = utils.find_or_raise(ele, class_=\"item-img\")\n\n title = manga.get(\"title\", None) # Manga title\n link = manga.get(\"href\", None) # Link to the manga 'homepage'\n\n yield MangaSearchResult(title=title, url=link)\n</code></pre>\n\n<p>Anything else is overhead. If you really need this to be multi-threaded (which, given your example that simply <code>wait</code>s, you might not), then feed a synchronized <code>queue.Queue</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T17:08:44.813", "Id": "471275", "Score": "0", "body": "Thats a fair enough change. Think I will switch over to a generator" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T17:27:22.783", "Id": "471279", "Score": "0", "body": "I added the updated version to the question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T18:47:10.247", "Id": "471289", "Score": "0", "body": "CR policy is to make a new question rather than updating the existing one. Please do that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T16:16:04.593", "Id": "240290", "ParentId": "240270", "Score": "0" } } ]
{ "AcceptedAnswerId": "240290", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T12:37:18.690", "Id": "240270", "Score": "1", "Tags": [ "python", "web-scraping", "api" ], "Title": "Code structure of website API" }
240270
<p><a href="https://leetcode.com/problems/flood-fill/" rel="nofollow noreferrer">https://leetcode.com/problems/flood-fill/</a></p> <blockquote> <p>An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).</p> <p>Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image.</p> <p>To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.</p> <p>At the end, return the modified image.</p> </blockquote> <pre><code>Example 1: Input: image = [[1,1,1],[1,1,0],[1,0,1]] sr = 1, sc = 1, newColor = 2 Output: [[2,2,2],[2,2,0],[2,0,1]] Explanation: From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected by a path of the same color as the starting pixel are colored with the new color. Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel. Note: The length of image and image[0] will be in the range [1, 50]. The given starting pixel will satisfy 0 &lt;= sr &lt; image.length and 0 &lt;= sc &lt; image[0].length. The value of each color in image[i][j] and newColor will be an integer in [0, 65535]. </code></pre> <p>Please review for performance and coding style.</p> <pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ArrayQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/flood-fill/ /// &lt;/summary&gt; [TestClass] public class FloodFillTest { [TestMethod] public void ExampleTest() { int[][] image = { new[] { 1, 1, 1 }, new[] { 1, 1, 0 }, new[] { 1, 0, 1 } }; int sr = 1; int sc = 1; int newColor = 2; int[][] expected = { new[] { 2, 2, 2 }, new[] { 2, 2, 0 }, new[] { 2, 0, 1 } }; FloodFillDFS dfs = new FloodFillDFS(); dfs.FloodFill(image, sr, sc, newColor); for (int i = 0; i &lt; 3; i++) { CollectionAssert.AreEqual(expected[i],image[i] ); } } } public class FloodFillDFS { public int[][] FloodFill(int[][] image, int sr, int sc, int newColor) { int oldColor = image[sr][sc]; DFS(image, sr, sc, newColor, oldColor); return image; } //make sure to check first the corner cases private void DFS(int[][] image, int sr, int sc, int newColor, int oldColor) { if (sr &lt; 0 || sc &lt; 0 || sr &gt;= image.Length || sc &gt;= image[0].Length || image[sr][sc] == newColor || image[sr][sc] != oldColor) { return; } image[sr][sc] = newColor; DFS(image, sr - 1, sc, newColor, oldColor); DFS(image, sr + 1, sc, newColor, oldColor); DFS(image, sr, sc - 1, newColor, oldColor); DFS(image, sr, sc + 1, newColor, oldColor); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T21:14:21.923", "Id": "471310", "Score": "0", "body": "if you give -1 please explain why, I would like to learn." } ]
[ { "body": "<p>I would split the if to 3 variables and give each a name : out of image, isVisited and isOriginalColor or something similar.</p>\n\n<p>I don't know what sr means, I would use row and col. </p>\n\n<p>FloodFill return image but dfs change the original image, It can confuse the user of the class. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T20:30:51.827", "Id": "471304", "Score": "0", "body": "thanks for the review, FloodFill suppose to change the original image. like when you paint a shape in Paint." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T18:01:44.963", "Id": "240295", "ParentId": "240274", "Score": "2" } } ]
{ "AcceptedAnswerId": "240295", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T13:22:01.177", "Id": "240274", "Score": "1", "Tags": [ "c#", "programming-challenge", "depth-first-search" ], "Title": "LeetCode: FloodFill C#" }
240274
<p>Write and test your own double abc (char * b) function in the program, taking in the form of a string the fractional binary number of the form "1101.101" and returning an equal decimal number (here 1 * 2 ^ 3 + 1 * 2 ^ 2 + 0 * 2 ^ 1 + 1 * 2 ^ 0 + 1 * 2 ^ -1 + 0 * 2 ^ -2 + 1 * 2 ^ -3 = 8 + 4 + 0 + 1 + 0.5 + 0 + 0.125 = 13.625). The function should return the special value -1 if an incorrect fractional binary number is entered (e.g. containing a different digit than 0, 1 or more than one period '.').</p> <p><strong>My solution:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; using namespace std; double abc(char* b); int main() { cout &lt;&lt; abc("1101.101"); return 0; } double abc(char* b){ int i = 0; int a = 0; int dot = 0; double sum=0; int c = 0; do{ if ((b[a]=='1')||(b[a]=='0')||(b[a]=='.')){ a++; if(b[a]=='.'){ dot++; } if(dot==2){ return -1; } } else { return -1; } } while(b[a]!='\0'); while(b[i]!='.'){ i++; } while(i!=0) { if(b[c]=='1'){ sum = sum + pow (2, i-1); } c++; i--; } while(b[i]!='.'){ i++; } if(b[i]=='.'){ int m = 0; while(b[i]!='\0'){ if(b[i]=='1'){ sum = sum + pow (2, m); } m = m - 1; i++; } } return sum; } </code></pre> <p><strong>Problem:</strong> Everything is fine, it gives me 13.625, but there is a lot of code. Is there any faster way to solve this exercise?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T14:00:47.293", "Id": "471255", "Score": "2", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T14:25:11.867", "Id": "471256", "Score": "5", "body": "The title is still useless, all questions on Code Review can be summed up as \"better and faster way to do this\". Your title should explain what \"this\" is. Are you making a website, solving the n queens problem or mutating dna?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T17:11:44.820", "Id": "471667", "Score": "0", "body": "The title is now appropriate. I see no reason to close this." } ]
[ { "body": "<p>Here are some thoughts about your code:</p>\n\n<ul>\n<li><p>Don't use <code>using namespace std</code>. This is considered bad practice and you can find many reasons on the internet why this is the case (for example <a href=\"https://stackoverflow.com/a/1452738\">here</a>). You can, for example write <code>std::cout</code> instead.</p></li>\n<li><p>You should use variable-names that tell the person who reads the code the purpose of the variable.</p></li>\n<li><p>To improve the legibility of your code, you really should use indentation.</p></li>\n<li><p>To further improve legibility, you can leave spaces between operators.</p></li>\n<li><p>I made your code a bit shorter by avoiding redundant code. You could even make it a lot shorter still, but I wanted to maintain your code structure.</p></li>\n<li><p>Finally, you should have a look at edge cases: Empty strings, strings that only contain \".\" and strings that don't have positions after/before the decimal point (for example 101 = 5 or .101 = 0.625).</p></li>\n</ul>\n\n<p>The result looks like this:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;cmath&gt;\n#include &lt;cstring&gt;\n\ndouble abc(char* b);\n\nint main() {\n std::cout &lt;&lt; abc(\".101\") &lt;&lt; \"\\n\";\n return 0;\n}\n\ndouble abc(char* b){\n\n if(strcmp(\"\", b) == 0 || strcmp(\".\", b) == 0) { //Empty String or only \".\"\n return -1;\n }\n\n if(b[0] == '.') { //No positions before the decimal point\n int length = std::strlen(b);\n char* newB = new char[length + 1];\n newB[0] = '0';\n for(int k = 0; k &lt; length; k++) {\n newB[k + 1] = b[k];\n }\n\n b = newB;\n }\n\n int countDots = 0;\n int index = 0;\n int dotIndex = -1;\n do{\n if ((b[index] == '1') || (b[index] == '0') || (b[index] == '.')){\n index++;\n if(b[index] == '.'){\n countDots++;\n dotIndex = index;\n }\n if(countDots == 2){\n return -1;\n }\n } \n else {\n return -1;\n }\n } while(b[index] != '\\0');\n\n if(dotIndex == -1) { //No dot found, but not empty string, so you have a natural number\n int length = std::strlen(b);\n char* newB = new char[length + 2];\n for(int k = 0; k &lt; length; k++) {\n newB[k] = b[k];\n }\n newB[length] = '.';\n newB[length + 1] = '0';\n dotIndex = index;\n b = newB;\n }\n\n double sum = 0;\n index = 0;\n int exponent = dotIndex;\n\n while(exponent != 0) {\n if(b[index] == '1'){\n sum = sum + pow (2, exponent-1);\n }\n index++;\n exponent--;\n }\n\n while(b[index] != '\\0'){\n if(b[index] == '1'){\n sum = sum + pow (2, exponent);\n }\n exponent = exponent - 1;\n index++;\n }\n\n return sum;\n}\n\n</code></pre>\n\n<p>I will leave it to you to comment the code properly.</p>\n\n<p>Please note: The code now is a bit longer than yours, but it is able to handle more things.</p>\n\n<hr>\n\n<p>EDIT:</p>\n\n<p>After one of the comments below, I decided to also show a version without C-style arrays, and without <code>new</code>. This also should solve the problem with possible memory leaks. So all in all, this is the better version (I will leave the old version, because the questioner asked for a function <code>double abc(char* b)</code>):</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;cmath&gt;\n#include &lt;string&gt;\n\ndouble abc(std::string b);\n\nint main() {\n std::cout &lt;&lt; abc(\"1101.101\") &lt;&lt; \"\\n\";\n return 0;\n}\n\ndouble abc(std::string b){\n\n if(b.compare(\"\") == 0 || b.compare(\".\") == 0) { //Empty String or only \".\"\n return -1;\n }\n\n if(b[0] == '.') { //No positions before the decimal point\n b.insert(0, \"0\");\n }\n\n int countDots = 0;\n size_t index = 0;\n int dotIndex = -1;\n do{\n if ((b[index] == '1') || (b[index] == '0') || (b[index] == '.')){\n index++;\n if(b[index] == '.'){\n countDots++;\n dotIndex = index;\n }\n if(countDots == 2){\n return -1;\n }\n } \n else {\n return -1;\n }\n } while(index &lt; b.length());\n\n if(dotIndex == -1) { //No dot found, but not empty string, so you have a natural number\n b.push_back('.');\n b.push_back('0');\n dotIndex = index;\n }\n\n double sum = 0;\n index = 0;\n int exponent = dotIndex;\n\n while(exponent != 0) {\n if(b[index] == '1'){\n sum = sum + pow (2, exponent-1);\n }\n index++;\n exponent--;\n }\n\n while(index &lt; b.length()){\n if(b[index] == '1'){\n sum = sum + pow (2, exponent);\n }\n exponent = exponent - 1;\n index++;\n }\n\n return sum;\n}\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T20:06:35.603", "Id": "471415", "Score": "1", "body": "if(b == \"\" || b == \".\") { //Empty String or only \".\"\n return -1;\n } does not work the way you think it does" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T00:49:03.017", "Id": "471447", "Score": "0", "body": "Thank you. I use strcmp now instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T11:03:37.937", "Id": "471476", "Score": "1", "body": "Instead of promoting the use of C-style arrays and gratuitous usage of `new`, please make proper use of `std::string` and `std::string_view`. The comparison problem is just one demonstration of how error prone C-style arrays are. And it is very easy to leak memory with your implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T13:12:30.997", "Id": "471489", "Score": "0", "body": "xyz9 wrote in his question: \"Write and test your own double abc (char * b) function\", so I thought he has to do it this way. Of course std::string would be the better option. Could you give an example when memory leak happens?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T10:29:15.217", "Id": "471759", "Score": "1", "body": "The new version is better. In the old version, the `new` arrays are leaked (`b = newB` doesn't do what you think it does). For the new version, some points to consider: `string_view`; `a.compare(b) == 0` => `a == b`; `+=`; not using `pow` for integer powers of 2; fewer manual loops if possible (or simplify the control flow); etc." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T16:48:28.463", "Id": "240292", "ParentId": "240276", "Score": "2" } }, { "body": "<p><strong>Code Review</strong> </p>\n\n<p>I suggest using <code>std:string</code> so you can use existing std functions and <code>for each</code> / <code>for</code> instead of <code>do while</code>. </p>\n\n<p>Separate the validation to different function. </p>\n\n<p>Edge cases:</p>\n\n<ul>\n<li>non frictions</li>\n<li>empty string</li>\n<li>\".\" </li>\n</ul>\n\n<p>For those inputs this loop</p>\n\n<p><code>while(b[i]!='.'){ i++; }</code></p>\n\n<p>will cause segmentation fault or infinite loop. </p>\n\n<p><strong>Alternative solution</strong></p>\n\n<p>You wrote </p>\n\n<blockquote>\n <p>Is there any faster way to solve this exercise?</p>\n</blockquote>\n\n<p>So I understand you ask for alternative solution. </p>\n\n<p>Here is my solution, excluding the validation:</p>\n\n<ol>\n<li>split the binary friction to 2 strings</li>\n<li>Convert each part to decimal number.</li>\n<li>Convert the numbers to strings and concat them with '.'</li>\n<li>Parse the string as double</li>\n</ol>\n\n<p>I believe this will be shorter</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T18:20:24.173", "Id": "471286", "Score": "0", "body": "I don't understand the down vote." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T20:07:06.050", "Id": "471298", "Score": "2", "body": "I imagine the downvote(s) are due to your answer being a suggestion for a different solution, and not a review of the OP's solution. This is Code Review, not \"Solve my problem your way\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T20:41:15.003", "Id": "471306", "Score": "1", "body": "But he ask it \"Is there any faster way to solve this exercise?\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T05:07:45.243", "Id": "471338", "Score": "2", "body": "On Code Review, answers are expected to provide at least one observation about the code, not just suggest alternative solutions. See [Why are alternative solutions not welcome?](https://codereview.meta.stackexchange.com/q/8403/188857) for more information." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T16:50:20.213", "Id": "240293", "ParentId": "240276", "Score": "-1" } }, { "body": "<p><strong>Code structure</strong></p>\n\n<p>This problem has three sub-parts, first Check if binary string is valid, second parse integral part and third parse fractional part. So a possible logical structure of code should be</p>\n\n<pre><code>float ConvertToDecimal(const std::string &amp; inputBinaryString)\n{\n int dotIndex;\n if (!FValidBinaryString(inputBinaryString, dotIndex))\n throw std::exception(\"Error: ConvertToDecimal Invalid binary string\");\n\n int integralPart = ParseIntegralPart(inputBinaryString, dotIndex);\n float fractionalPart = ParseFractionalPart(inputBinaryString, dotIndex);\n\n return integralPart + fractionPart;\n}\n</code></pre>\n\n<p>Based on this logical breaking, three functions should be implemented</p>\n\n<pre><code>bool FValidBinaryString(const std::string&amp; input, int&amp; dotIndex) //Out param dotIndex\nint ParseIntegralPart(const std::string&amp; input, int dotIndex)\nfloat ParseFractionalPart(const std::string&amp; input, int dotIndex)\n</code></pre>\n\n<p>Your current code also does similar steps but in monolithic way.</p>\n\n<p><strong>C++ specific comments</strong></p>\n\n<ol>\n<li>Avoid \"using std namespace\". One of the obvious reason is avoiding cases where same name is coming from two different namespaces and creates error and confusion. Common utility functions like min, max are defined in many namespaces. Using full name makes code more readable. If name is getting too long, use aliases.</li>\n<li>Variable and function names are very very important. Be consistent in naming ans use words which convey meaning. One of the very basic rule to start can be \"Functions should start with verbs and variables as noun\"</li>\n<li>Function which parses binary string can not modify input string. So it makes sense to pass by const reference. Passing by pointer is not good idea here. Two reasons, Callee function needs to ensure it is not de-referencing an null pointer, so a null check will be needed, second callee can inadvertently modify input string.</li>\n<li>No need to use pow function in inside loop. You need to just keep doubling (or halving) the place value. So multiplication (or division) by 2 should serve the purpose.</li>\n<li>Use ASCII value of '1', '0', '.' in comparison.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T08:06:25.693", "Id": "240383", "ParentId": "240276", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T13:43:23.877", "Id": "240276", "Score": "1", "Tags": [ "c++", "binary" ], "Title": "Fractional binary number to decimal number" }
240276
<p>I took some time to try and solve a problem. I am building a basic Node + Express API. In the app I have created a models folder and will be adding new models as I continue development. </p> <p>I attempted to write a small autoloader for a directory to automatically load and export my models. This code snippet should work for any modules not just my models folders.</p> <p><strong>See the following code:</strong></p> <p>loader.js</p> <pre><code>const fs = require('fs'); // Autoload modules. module.exports = fs.readdirSync(__dirname) // Ignore current file (loader.js) .filter(f =&gt; !__filename.includes(f)) // Require all files in directory .map(f =&gt; require( `./${f}` )) // Add to final module.exports object using class name .reduce((prev, curr) =&gt; ({...prev, [curr.name]: curr}), {}); </code></pre> <p><strong>My folder structure for the models:</strong></p> <p><a href="https://i.stack.imgur.com/6Yhf3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6Yhf3.png" alt="Structure of my models directory"></a></p> <p><strong>How I import the models into my Routes file:</strong></p> <p>author.route.js</p> <pre><code>const { AppResponse, Author } = require('../models/loader'); </code></pre> <p><strong>The question</strong>: </p> <p>Is this a good idea to do something like this? My reasoning is that it would minimize changes when I commit and not require any modifications to my code should I decide to add new functionality to my routes and models folders. </p> <p>What caveats are there to doing this and would there be a better approach?</p> <p>Thanks for taking the time to look at this!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T16:48:29.403", "Id": "471274", "Score": "3", "body": "I appreciate critisism but perhaps explain the downvote? I would gladly ammend my question should it not have sufficiant information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T19:13:24.133", "Id": "471292", "Score": "4", "body": "You need to supply more of your code for it to be reviewable; small excerpts are not reviewable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T06:32:55.340", "Id": "471340", "Score": "0", "body": "@Reinderien This is clearly a Node.js design pattern in itself and not an “excerpt”" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T12:35:04.510", "Id": "471369", "Score": "0", "body": "@Reinderien I've added more detail. Hopefully it helps" } ]
[ { "body": "<p><strong>tl;dr</strong></p>\n\n<p>The major reason for not doing this is that dynamically requiring modules breaks static analysis.</p>\n\n<p>In a pure Node.js project, this does not have major repercussions aside from breaking IDE's autocompletion. Everything else will still work as expected.</p>\n\n<p><strong>diving deeper</strong></p>\n\n<p>Should this pattern be used in a webpack project for instance (targetting server or client), it would fail, as bundlers need to <a href=\"https://webpack.js.org/guides/dependency-management/#require-with-expression\" rel=\"nofollow noreferrer\">statically compute</a> the dependency tree at compile-time.</p>\n\n<p>The <code>require()</code> function (<a href=\"https://requirejs.org/docs/node.html\" rel=\"nofollow noreferrer\">CommonJS</a>) was implemented in Node because, at the time, the core Javascript language didn't have the concept of modules. However this has changed, as <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import\" rel=\"nofollow noreferrer\">ES modules</a> are now available in all evergreen browsers, and in Node 13.x <a href=\"https://nodejs.org/api/esm.html\" rel=\"nofollow noreferrer\">without a feature flag</a>.</p>\n\n<p>The new keywords <code>import</code> and <code>export</code> do not support variable interpolation for the purpose of static analysis, and are even required to be declared on top of the module. In practice, this makes the patterns <code>if (dev) { require('debug') }</code> or <code>require(name)</code> unusable, once adapted to ES modules.</p>\n\n<p><strong>recommendation</strong></p>\n\n<p>In my opinion, this is a case where anything “clever” you try to make will just make the code harder to read and maintain. I've been down that path too, and I can tell you that the long-term costs are not worth the 2 seconds it will take you to add manual exports to your files. In my experience, reading code is 10 times more costly than writing it.</p>\n\n<p>You also don't even have to create <code>index.js</code> loaders; you can require the files directly. Ryan Dahl, creator of Node, <a href=\"https://drive.google.com/viewerng/viewer?url=http://tinyclouds.org/jsconf2018.pdf\" rel=\"nofollow noreferrer\">even said at JSConf 2018</a> that he considered the addition of <code>index.js</code> a mistake because <em>“it needlessly complicated the module loading system.”</em></p>\n\n<p>Good luck, and be kind to future-you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T09:44:24.877", "Id": "471360", "Score": "1", "body": "Thanks for this great answer. I have not considered the impact of bundlers at all! Clearly this approach would then not be \"Future proof\" when switching to ES modules." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T06:18:12.057", "Id": "240321", "ParentId": "240280", "Score": "2" } } ]
{ "AcceptedAnswerId": "240321", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T14:50:58.587", "Id": "240280", "Score": "0", "Tags": [ "javascript", "node.js", "express.js", "modules" ], "Title": "NodeJS - Auto Module Loader" }
240280
<p>I have the following snippet:</p> <pre><code>import datetime as dt end_date = dt.datetime(2020,04,12,10,30,0,0) current_date = dt.datetime(2020,04,10,0,0,0,0) diff = end_date - current_date days = diff.days + (1 if diff.seconds &gt; 0 and diff.days &gt; 0 else 0) </code></pre> <p>I need 0 when day is the same and 1 or more when day &gt; 1.</p> <p>Examples:</p> <blockquote> <p>time difference is 2 days and 4H: should give 3</p> <p>time difference is 0 days and 4H: should give 0</p> </blockquote> <p>How can can improve the following?</p> <pre><code>days = diff.days + (1 if diff.seconds &gt; 0 and diff.days &gt; 0 else 0) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T19:26:27.023", "Id": "471294", "Score": "2", "body": "Does this work as intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T13:28:29.040", "Id": "471379", "Score": "1", "body": "In the code provided, both dates are the same. This is not going to do much good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T15:05:48.163", "Id": "471793", "Score": "0", "body": "@Peilonrayz yes it is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T23:07:02.970", "Id": "471835", "Score": "0", "body": "Why `current_date`? Why not `start_date`, just like you got `end_date`?" } ]
[ { "body": "<p>Looks good to me. You can split calculating the days to two lines if you think it's more readable that way.</p>\n\n<pre><code># Calculate full day difference\n# Assuming negative difference should be 0\ndays = diff.days if diff.days &gt; 0 else 0\n# Add one if not exactly the same clock\ndays += 1 if diff.seconds &gt; 0 else 0\n# Or a little bit shorter\ndays += 1 if diff.seconds else 0\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T15:24:44.650", "Id": "240283", "ParentId": "240281", "Score": "2" } }, { "body": "<p>Since it is required to have difference based on days I solved by removing time on dates and calculating difference by days count:</p>\n\n<pre><code>end_date = end_date.date()\ncurrent_date = dt.date.today()\ndiff = (end_date - current_date).days\ndays_left = diff if diff &gt; 0 else 0\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T17:11:32.777", "Id": "240516", "ParentId": "240281", "Score": "1" } } ]
{ "AcceptedAnswerId": "240283", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T14:55:13.983", "Id": "240281", "Score": "-2", "Tags": [ "python", "datetime" ], "Title": "Time diff in days" }
240281
<p>I have written below code to create/get a dict with n number of key, value pairs. Main idea is to use the same instantiated class object across my code and play around with k/v pairs.</p> <p>Current implementation:</p> <pre><code>class DataForm: def __init__(self): self.data_dict = dict() def create_key_value_pair(self, key, value): self.data_dict[key] = value def get_dict(self): return self.data_dict ob1 = DataForm() ob1.create_key_value_pair("Jon", 28) ob1.get_dict() </code></pre> <p>I was trying to understand and implement the above work(with some data validation) using getter/setter in Python.</p> <pre><code>class DataFormNew: def __init__(self): self._curr_dict = dict() @property def curr_dict(self): return self._curr_dict @curr_dict.setter def curr_dict(self, args): key, val = args if 0 &lt; val &lt; 100: self._curr_dict[key] = val else: raise ValueError("Value is not in range") ob2 = DataFormNew() ob2.curr_dict ob2.curr_dict = ('Jack', 10) </code></pre> <p>Few points on which I would need clarification?</p> <hr> <ol> <li>Which approach is better? </li> <li>Am I trying to complicate a simple job by using python @property (getter/setter) ?</li> <li>In which scenario we should choose to implement our class with getter/setter?</li> </ol> <hr> <p>PS: Actually it's not just about dict creation. I'm running my code on AWS EC2 server where for every task, there can be n number of files to read and write them in DB. For every file, there is going to be unique id which i'm storing in dict dynamically. Each of (filename, unique id) creates a key,value pair. Later, I have queries to update DB based on this unique id against every file. I'm using object oriented approach to simplify the task.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T15:37:26.160", "Id": "471265", "Score": "1", "body": "Why is `obj = {}` `obj[\"Jon\"] = 28` `obj` not ok?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T15:47:06.023", "Id": "471268", "Score": "0", "body": "@Peilonrayz: Actually it's not just about dict creation. I'm running my code on AWS EC2 server where for every task, there can be n number of files to read and write them in DB. For every file, there is going to be unique id which i'm storing in dict dynamically. Each of (filename, unique id) creates a key,value pair. Later, I' have queries to update DB based on this unique id against every file. \nI'm not sure if i'm making much of a sense here!" } ]
[ { "body": "<p>Comparing the two, unless there is an outstanding reason to switch that I'm not seeing, I would keep using the first one. Not only is it more easily readable it falls under the principal of K.I.S.S. (keep it stupid simple).</p>\n\n<p>A note on the first implimentation, did you mean for get_dict to return the entire dict?\nOr did you mean to do something like this, that returns the value for the specified key.</p>\n\n<pre><code>class DataForm:\n\n def __init__(self):\n self.data_dict = dict()\n\n def create_key_value_pair(self, key, value):\n self.data_dict[key] = value\n\n def get_dict(self, key):\n return self.data_dict.get(key)\n\nob1 = DataForm()\nob1.create_key_value_pair(\"Jon\", 28)\nob1.create_key_value_pair(\"tim\", 28)\nprint(ob1.get_dict('tim'))\n\n`\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T22:25:29.933", "Id": "471316", "Score": "0", "body": "Welcome to Code Review. Whilst of the two solutions provided your answer is correct, I stand by my comment to the question that a plain old dictionary would be best. It would also better follow KISS. I suggest not answering questions with a negative score as you're likely to have a worse experience then if you were to answer a question with a positive score. Historically questions like this have lead to combative OPs. And some users, like myself, may downvote or not vote on an answer to an off-topic question. Thank you for the good answer, I hope to see you around. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T22:39:52.590", "Id": "471318", "Score": "0", "body": "I didn't even think about it like that a plain dict would be the most simple, for some reason I had it in my head that it need to be a part of a class. As for answering negative questions I'm more or less just trying to answer what I can and try to help out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T00:04:23.920", "Id": "471323", "Score": "0", "body": "It's all good Joe ^^" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T06:55:22.220", "Id": "471460", "Score": "0", "body": "@JoeSmith: Thanks Joe for your valuable feedback!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T06:59:49.200", "Id": "471461", "Score": "0", "body": "@Peilonrayz: Thanks for the downvote. As I'm new to this platform, I was not aware of so called \"Posting Questions guidelines\" . Rest, be assured that it's not a hypothetical question which I have asked. Somehow, I do not have authority to post code's outside office space. Hence, I tried to ask in best possible way. Added to that a further PS had been added in question, to give an high level idea of task which includes similar piece of code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T12:23:15.413", "Id": "471481", "Score": "0", "body": "@Sumit Please post comments under the post they are related to. Your and my comments are needlessly pinging Joe Smith. Whilst I can't speak on Joe's behalf, I know many users are not a fan of unrelated pings. Given that you believe that speculation equates to proof, and is worthy of open hostility I don't wish to engage with you. If you disagree with the closure then you can [post on meta](https://codereview.meta.stackexchange.com/)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T21:12:47.740", "Id": "240308", "ParentId": "240285", "Score": "2" } } ]
{ "AcceptedAnswerId": "240308", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T15:35:31.170", "Id": "240285", "Score": "-2", "Tags": [ "python", "python-3.x", "object-oriented" ], "Title": "Using Python's getter/setter" }
240285
<p>I want to define the XML schema for an XML representation of shopping order data. </p> <blockquote> <p>See following requirements</p> </blockquote> <ul> <li>The XML representation of order should contain order id, description, request date, and many line item</li> <li>Each line item element should contain book, quantity, and price. Price (which is price per book) should be restricted to values greater than 0</li> <li>Each book should contain book id, book name, genre, publish date, and many authors. Genre should be restricted so that it may contain only the following values {science-fiction, mystery, thriller, drama}</li> <li>Each author should contain bio,last name, first name, and optional pen name.</li> </ul> <blockquote> <p>Evaluation Criteria</p> </blockquote> <ul> <li>allows many line items </li> <li>allows many authors for a book and have an OPTIONAL pen name </li> <li>allows to specify price and restricts to values greater than 0</li> <li>allows to specify genre but restricts the list of values to be EXACTLY that state above. Please someone help me figure out XML definition for this type of nested requirements.</li> </ul> <p>here's my code </p> <blockquote> <h1>XML</h1> </blockquote> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;orders&gt; &lt;order id="1"&gt; &lt;description&gt;first order of the day&lt;/description&gt; &lt;req_date&gt;9-4-2020&lt;/req_date&gt; &lt;line_items&gt; &lt;book&gt; &lt;id&gt;1&lt;/id&gt; &lt;name&gt;Book1&lt;/name&gt; &lt;publish_date&gt;12-2-2010&lt;/publish_date&gt; &lt;genre&gt;science-fiction&lt;/genre&gt; &lt;authors&gt; &lt;author id="120"&gt; &lt;bio&gt; description about author120&lt;/bio&gt; &lt;first_name&gt;George&lt;/first_name&gt; &lt;last_name&gt;Smith&lt;/last_name&gt; &lt;pen_name&gt;pen name &lt;/pen_name&gt; &lt;/author&gt; &lt;author id="122"&gt; &lt;bio&gt; description about author122&lt;/bio&gt; &lt;first_name&gt;George&lt;/first_name&gt; &lt;last_name&gt;Smith&lt;/last_name&gt; &lt;/author&gt; &lt;/authors&gt; &lt;/book&gt; &lt;book&gt; &lt;id&gt;1&lt;/id&gt; &lt;name&gt;Book2&lt;/name&gt; &lt;publish_date&gt;12-2-2010&lt;/publish_date&gt; &lt;genre&gt;science-fiction&lt;/genre&gt; &lt;authors&gt; &lt;author id="120"&gt; &lt;bio&gt; description about author120&lt;/bio&gt; &lt;first_name&gt;George&lt;/first_name&gt; &lt;last_name&gt;Smith&lt;/last_name&gt; &lt;pen_name&gt;pen name &lt;/pen_name&gt; &lt;/author&gt; &lt;/authors&gt; &lt;/book&gt; &lt;quantity&gt;1&lt;/quantity&gt; &lt;price&gt;20&lt;/price&gt; &lt;/line_items&gt; &lt;/order&gt; &lt;/orders&gt; </code></pre> <blockquote> <h1>XSD</h1> </blockquote> <pre><code>&lt;xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt; &lt;xs:element name="orders"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="order"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element type="xs:string" name="description" /&gt; &lt;xs:element type="xs:string" name="req_date" /&gt; &lt;!-- criteria 1 --&gt; &lt;xs:element name="line_items" minOccurs="1" maxOccurs="unbounded"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="book" maxOccurs="unbounded" minOccurs="0"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element type="xs:byte" name="id" /&gt; &lt;xs:element type="xs:string" name="name" /&gt; &lt;xs:element type="xs:string" name="publish_date" /&gt; &lt;xs:element name="genre" &gt; &lt;xs:simpleType&gt; &lt;xs:restriction base="xs:string"&gt; &lt;xs:enumeration value="science-fiction"/&gt; &lt;xs:enumeration value="mystery" /&gt; &lt;xs:enumeration value="thriller" /&gt; &lt;xs:enumeration value="drama" /&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; &lt;/xs:element&gt; &lt;!-- criteria 2 --&gt; &lt;xs:element name="authors" minOccurs="1" maxOccurs="unbounded"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="author" maxOccurs="unbounded" minOccurs="0"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element type="xs:string" name="bio" /&gt; &lt;xs:element type="xs:string" name="first_name" /&gt; &lt;xs:element type="xs:string" name="last_name" /&gt; &lt;!-- make a pen name optional --&gt; &lt;xs:element type="xs:string" name="pen_name" minOccurs="0" /&gt; &lt;/xs:sequence&gt; &lt;xs:attribute type="xs:byte" name="id" use="optional" /&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:element type="xs:byte" name="quantity" /&gt; &lt;!-- price criteria --&gt; &lt;xs:element name="price"&gt; &lt;xs:simpleType&gt; &lt;xs:restriction base="xs:integer"&gt; &lt;xs:minInclusive value="0"/&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;xs:attribute type="xs:byte" name="id" /&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:schema&gt; </code></pre> <p>I want review on accuracy , efficient schema design according to the criterias.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T18:35:43.297", "Id": "471408", "Score": "1", "body": "Congratulations! https://www.freeformatter.com/xml-validator-xsd.html didn't find any issues." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T18:37:17.997", "Id": "471409", "Score": "1", "body": "http://www.utilities-online.info/xsdvalidation/ likewise has not found any issue in terms of your documents being well-formed, and the XML adhering to the XSD." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T16:03:47.253", "Id": "240288", "Score": "1", "Tags": [ "xml", "xsd" ], "Title": "XML and XML schema definition" }
240288
<p>Im looking for some help on improving my code which visualizes path-finding algorithms. The code is working however I know it can be improved. Any suggestions would be appreciated.</p> <p>Github code - <a href="https://github.com/James-Charles-Robinson/Path-Finding-Visualisation-with-Pygame" rel="nofollow noreferrer">https://github.com/James-Charles-Robinson/Path-Finding-Visualisation-with-Pygame</a></p> <p>Code</p> <pre><code>import pygame import random # class for the gui of the application class Gui(): def __init__(self, coords): # gui variables self.fps = 60 self.width = 800 self.gridSize = 20 self.boxWidth = self.width/self.gridSize self.coords = coords self.placingWalls = False self.removingWalls = False self.animationSpeed = 10 self.coords.maze = [[0 for x in range(self.gridSize)] for x in range(self.gridSize)] # start pygame application pygame.init() self.win = pygame.display.set_mode((self.width, self.width)) self.clock = pygame.time.Clock() pygame.display.set_caption("Pathfinding Algorithms - James Robinson") # main function for gui def main(self, running=False): self.clock.tick(self.fps) self.mouseX, self.mouseY = pygame.mouse.get_pos() # if the mouse button was pressed down continue placing walls if self.placingWalls == True and running == False: self.placeWall() elif self.removingWalls == True and running == False: self.remove() # get mouse and key presses self.eventHandle(running) # redraw and update the display self.redraw() pygame.display.update() # handles key and mouse presses def eventHandle(self, running): # gets key presses for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() # key presses elif event.type == pygame.KEYDOWN: key = event.key # run algorithm if key == 113 or key == 119 or key == 101 or key == 114 and running == False: # q, w, e and r self.runAlgorithm(key) # clear the whole board elif key == 120 and running == False: # x self.coords.removeAll() # remove everything except the things placed by the user elif key == 122 and running == False: # z self.coords.removeLast() # place checkpoints with number keys elif (key &gt; 48 and key &lt; 58) and running == False: # 1-9 self.placeCheckPoint(key-48) # increase speed of the pathfinding elif key == 61 and self.animationSpeed &gt; 0: # + key if self.animationSpeed &lt;= 2: self.animationSpeed = 1 else: self.animationSpeed = int(self.animationSpeed * 0.5) + 1 # decrease speed of pathfinding elif key == 45: # - key self.animationSpeed = int(self.animationSpeed * 2) + 1 elif key == 32: # space self.coords.generateRandomMaze(gui) # mouse button down elif event.type == pygame.MOUSEBUTTONDOWN: # place walls if event.button == 1 and running == False: # left down self.placingWalls = True # remove walls elif event.button == 3 and running == False: # right down self.removingWalls = True # zoom in if event.button == 4: # scroll up self.gridSize -= 1 self.boxWidth = self.width/self.gridSize # zoom out elif event.button == 5: # scroll down self.gridSize += 1 self.boxWidth = self.width/self.gridSize # mouse button up elif event.type == pygame.MOUSEBUTTONUP: # stop placing walls if event.button == 1: # left up self.placingWalls = False # stop removing walls elif event.button == 3: # right up self.removingWalls = False # redraws the gui def redraw(self): self.win.fill((255,255,255)) self.drawPoints() self.drawGrid() # draw the grid lines def drawGrid(self): for i in range(self.gridSize-1): pygame.draw.rect(self.win, (0, 0, 0), (((i+1)*self.boxWidth)-2, 0, 4, self.width)) pygame.draw.rect(self.win, (0, 0, 0), (0, ((i+1)*self.boxWidth)-2, self.width, 4)) # draws all the squares for the walls, checkpoints ect def drawPoints(self): for node in self.coords.openList: self.drawBox(node.position, (0, 255, 0)) for node in self.coords.closedList: self.drawBox(node.position, (0, 0, 255)) for wall in self.coords.finalPath: self.drawBox(wall, (255, 0, 255)) for wall in self.coords.walls: self.drawBox(wall, (0, 0, 0)) for i,point in enumerate(self.coords.checkPoints): if point != "None": self.drawBox(point, (255, 30, 30)) self.displayText(str(i+1), (255, 255, 255), self.boxCenter(point), int(self.boxWidth)) if self.coords.start != None: self.drawBox(self.coords.start, (255, 0, 0)) self.displayText("S", (255, 255, 255), self.boxCenter(self.coords.start), int(self.boxWidth)) if self.coords.end != None: self.drawBox(self.coords.end, (255, 0, 0)) self.displayText("E", (255, 255, 255), self.boxCenter(self.coords.end), int(self.boxWidth)) # gets the center point of a node def boxCenter(self, box): boxX, boxY = box center = ((boxX*self.boxWidth+(self.boxWidth/2)), (boxY*self.boxWidth+(self.boxWidth/2))) return center # used to draw the boxed given colours and position def drawBox(self, box, colour): boxX, boxY = box pygame.draw.rect(self.win, colour, (boxX*self.boxWidth, boxY*self.boxWidth, self.boxWidth, self.boxWidth)) # gets the box coordinates given a mouse position def getBoxCoords(self): boxX = int((self.mouseX + 2) / self.boxWidth) boxY = int((self.mouseY + 2) / self.boxWidth) return (boxX, boxY) # placing checkpoints def placeCheckPoint(self, index): coords = self.getBoxCoords() if coords != self.coords.start and coords != self.coords.end and coords not in self.coords.walls and coords not in self.coords.checkPoints: while len(self.coords.checkPoints) &lt;= index-1: self.coords.checkPoints.append("None") self.coords.checkPoints[index-1] = coords # placing walls def placeWall(self): coords = self.getBoxCoords() if coords != self.coords.start and coords != self.coords.end and coords not in self.coords.walls and coords not in self.coords.checkPoints: self.coords.walls.append(coords) # removing nodes such as walls checkpoints ect def remove(self): coords = self.getBoxCoords() if coords in self.coords.walls: self.coords.walls.remove(coords) elif coords in self.coords.checkPoints: self.coords.checkPoints.remove(coords) elif coords == self.coords.start: self.coords.start = None elif coords == self.coords.end: self.coords.end = None # function that prepares for a pathfind and runs pathfind function def runAlgorithm(self, key): self.placingWalls == False self.removingWalls == False coords.removeLast() # if we have 2 or more checkpoints if len(self.coords.checkPoints) &gt; 1: # create the maze array and remove missed checkpoint numbers self.coords.createMaze(gui) checkPoints = self.coords.checkPoints[:] checkPoints = [point for point in checkPoints if point != "None"] # iterate through every checkpoint and pathfind to it for i,point in enumerate(checkPoints): if i != len(checkPoints)-1: start = point end = checkPoints[i+1] newPath = pathfind(self.coords.maze, start, end, self, self.coords, key) if newPath == None: newPath = [] self.coords.finalPath.extend(newPath) # displays text given text, colour and position/size def displayText(self, txt, colour, center, size): font = pygame.font.Font(None, size) textSurf = font.render(txt, True, colour) textRect = textSurf.get_rect() textRect.center = (center) self.win.blit(textSurf, textRect) # class containing all coordinates and functions for calculations todo with them class CoOrdinates(): def __init__(self): self.removeAll() def removeAll(self): self.start = None self.end = None self.walls = [] self.maze = [] self.openList = [] self.closedList = [] self.finalPath = [] self.checkPoints = [] def removeLast(self): self.maze = [] self.openList = [] self.closedList = [] self.finalPath = [] # gets the furthest distance of a node from the (0, 0) def largestDistance(self): largest = 0 for wall in self.walls: if wall[0] &gt; largest: largest = wall[0] if wall[1] &gt; largest: largest = wall[1] for point in self.checkPoints: if point[0] &gt; largest: largest = point[0] if point[1] &gt; largest: largest = point[1] return largest + 1 # creates a 2d array of the maze and its walls def createMaze(self, giu): largestDistance = self.largestDistance() # makes sure the size of the maze if either the size of the gui # or the size of the maze made using the walls and checkpoints if gui.gridSize &gt; largestDistance: largest = gui.gridSize else: largest = largestDistance self.maze = [[0 for x in range(largest)] for x in range(largest)] for wall in self.walls: try: wallX, wallY = wall self.maze[wallX][wallY] = 1 except: pass # creates a random maze def generateRandomMaze(self, gui): self.walls = [] for i in range(gui.gridSize*gui.gridSize): if random.random() &gt; 0.6: wall = (random.randint(0, gui.gridSize-1), random.randint(0, gui.gridSize-1)) if wall not in self.walls: self.walls.append(wall) # function for pathfinding using dfs, bfs, dijkstra and astar # Returns a list of tuples as a path from the given start to the given end in the given maze def pathfind(maze, start, end, gui, coords, key): # Create start and end node startNode = Node(None, start) startNode.g = startNode.h = startNode.f = 0 endNode = Node(None, end) endNode.g = endNode.h = endNode.f = 0 # Initialize both open and closed list openList = [] closedList = [] # Add the start node openList.append(startNode) count = 0 # Loop until you find the end while len(openList) &gt; 0: # skip pathfinding to create a wait effect. Ajustable speed if count &gt;= gui.animationSpeed: count = 0 # Get the current node if key == 113: # dfs, get the latest node currentNode = openList[-1] currentIndex = len(openList)-1 elif key == 119: # bfs, get the newest node currentNode = openList[0] currentIndex = 0 elif key == 114: # a*, get the node with the lowest f value currentNode = openList[0] currentIndex = 0 for index, item in enumerate(openList): if item.f &lt; currentNode.f: currentNode = item currentIndex = index elif key == 101: # dijkstra, get the node with the lowest g value currentNode = openList[0] currentIndex = 0 for index, item in enumerate(openList): if item.g &lt; currentNode.g: currentNode = item currentIndex = index # Pop current off open list, add to closed list openList.pop(currentIndex) closedList.append(currentNode) # Found the goal if currentNode == endNode: path = [] current = currentNode while current is not None: path.append(current.position) current = current.parent coords.openList = openList coords.closedList = closedList return path # Return path # Generate children # left, down, right, up. Which makes dfs go in up, right, down, left order for newPosition in [(-1, 0), (0, 1), (1, 0), (0, -1)]: # Adjacent squares # Get node position nodePosition = (currentNode.position[0] + newPosition[0], currentNode.position[1] + newPosition[1]) # Make sure within range if nodePosition[0] &gt; (len(maze) - 1) or nodePosition[0] &lt; 0 or nodePosition[1] &gt; (len(maze[len(maze)-1]) -1) or nodePosition[1] &lt; 0: continue # Make sure walkable terrain if maze[nodePosition[0]][nodePosition[1]] != 0: continue if Node(currentNode, nodePosition) in closedList: continue # Create new node child = Node(currentNode, nodePosition) # Child is on the closed list passList = [False for closedChild in closedList if child == closedChild] if False in passList: continue # for dfs and bfs we dont add anything to the node values if key == 101: # dijkstra, add one to g value child.g = currentNode.g + 1 elif key == 114: # a*, calculate f value child.g = currentNode.g + 1 # distance to end point # the reason the h distance is powered by 0.6 is because it makes it prioritse diagonal paths over straight ones # even though they are technically the same g distance, this makes a* look better child.h = ((abs(child.position[0] - endNode.position[0]) ** 2) + (abs(child.position[1] - endNode.position[1]) ** 2)) ** 0.6 child.f = child.g + child.h # Child is already in the open list for openNode in openList: # check if the new path to children is worst or equal # than one already in the openList (by measuring g) if child == openNode and child.g &gt;= openNode.g: break else: # Add the child to the open list openList.append(child) # if skipped just update the gui else: coords.openList = openList coords.closedList = closedList gui.main(True) count += 1 # node class for containing position, parent and costs class Node(): def __init__(self, parent, position): self.parent = parent self.position = position self.g = 0 self.h = 0 self.f = 0 def __eq__(self, other): return self.position == other.position # main loop if __name__ == "__main__": coords = CoOrdinates() gui = Gui(coords) while True: gui.main() </code></pre>
[]
[ { "body": "<p>Welcome to Code Review, and thanks for posting! Here are some random suggestions:</p>\n\n<h2>Type hints</h2>\n\n<p>Looking at <code>Gui.__init__</code>, I can only guess that <code>coords</code> is some class instance. So this should probably be</p>\n\n<pre><code>def __init__(self, coords: CoOrdinates):\n</code></pre>\n\n<h2>Bare class declaration</h2>\n\n<pre><code># class for the gui of the application\nclass Gui():\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>class Gui:\n \"\"\"\n Class for the GUI of the application\n \"\"\"\n</code></pre>\n\n<h2>lower_camel_case</h2>\n\n<p>For variables and functions - such as <code>placing_walls</code>, <code>removing_walls</code>, etc.</p>\n\n<h2>Generator variables</h2>\n\n<p>This:</p>\n\n<pre><code> self.coords.maze = [[0 for x in range(self.gridSize)] for x in range(self.gridSize)]\n</code></pre>\n\n<p>surprises me that it actually works. You shouldn't reuse <code>x</code>; instead, you probably want</p>\n\n<pre><code> self.coords.maze = [[0 for x in range(self.grid_size)] for y in range(self.grid_size)]\n</code></pre>\n\n<h2>Constants</h2>\n\n<p>These are probably constants, so belong in class scope:</p>\n\n<pre><code>class Gui:\n FPS = 60\n WIDTH = 800\n GRID_SIZE = 20\n ANIMATION_SPEED = 10\n</code></pre>\n\n<h2>Boolean simplification</h2>\n\n<pre><code> if self.placingWalls == True and running == False:\n self.placeWall()\n elif self.removingWalls == True and running == False:\n self.remove()\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>if not running:\n if self.placing_walls:\n self.place_wall()\n elif self.removing_walls:\n self.remove_wall()\n</code></pre>\n\n<h2>Key constants</h2>\n\n<p>These:</p>\n\n<pre><code> if key == 113 or key == 119 or key == 101 or key == 114 and running == False: # q, w, e and r\n</code></pre>\n\n<p>should not use numeric. Instead, call <code>ord('q')</code>, etc. Further, they should be in a set for efficiency:</p>\n\n<pre><code>run_keys = {ord(c) for c in 'qwer'}\n# ...\nif key in run_keys:\n</code></pre>\n\n<h2>Variable names</h2>\n\n<p>This needs some love:</p>\n\n<pre><code> self.g = 0\n self.h = 0\n self.f = 0\n</code></pre>\n\n<p>because it's incomprehensible.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T23:18:01.597", "Id": "471322", "Score": "0", "body": "Thanks so much for the reply, means a lot you put in all this effort.\nI definitely agree with all your edits and will adjust my code to match them.\nBecause 90% of my learning is self taught it can be hard to know what is wrong or right so this helps a lot, thanks again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T00:39:09.120", "Id": "471326", "Score": "0", "body": "I have made most of the changes and have updated my Github if you want to take a look" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T17:21:22.493", "Id": "471403", "Score": "0", "body": "If you're looking for another review iteration, the better thing to do is open a new question with your updated code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T19:08:37.987", "Id": "240301", "ParentId": "240289", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T16:14:32.033", "Id": "240289", "Score": "4", "Tags": [ "python", "pathfinding", "pygame", "data-visualization" ], "Title": "Advice on path-finding visualisation program" }
240289
<p>I'm currently trying to learn how to OOP in JavaScript by making use of ES6 classes. As an example I created this Slider using classes. I didn't find any class example where the DOM is highly involved</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>class Slider { constructor(_options, _className) { this.options = _options; this.container = document.getElementsByClassName(_className)[0]; this.slider = new SliderBackground(this.container.getElementsByClassName("slider-background")[0]); this.minThumb = new Thumb(this.container.getElementsByClassName("slider-min")[0]); this.maxThumb = new Thumb(this.container.getElementsByClassName("slider-max")[0]); this.minLabel = this.container.getElementsByClassName("input-min")[0]; this.maxLabel = this.container.getElementsByClassName("input-max")[0]; this.minDragged = false; this.maxDragged = false; this.setup(); } setup() { this.setStartValues(); this.assignEvents(); } setStartValues() { const minValue = this.options.defaultValue[0] &gt; this.options.range[0] ? this.options.defaultValue[0] : this.options.range[0]; const maxValue = this.options.defaultValue[1] &gt; this.options.range[1] ? this.options.defaultValue[1] : this.options.range[1]; const minValuePercent = this.getValueToPercent(minValue); const maxValuePercent = this.getValueToPercent(maxValue); this.minThumb.position = minValuePercent; this.maxThumb.position = maxValuePercent; this.minLabel.value = minValue; this.maxLabel.value = maxValue; this.slider.setBackground(minValuePercent, maxValuePercent); if (this.options.prefix !== "" &amp;&amp; this.options.prefix !== undefined &amp;&amp; this.options.prefix !== null) { let inputs = this.container.getElementsByClassName("input-value"); for (let i = 0; i &lt; inputs.length; i++) { let prefix = document.createElement("span"); prefix.className = "slider-input-prefix"; prefix.innerHTML = this.options.prefix; inputs[i].parentNode.insertBefore(prefix, inputs[i]); } } } assignEvents() { this.minThumb.element.addEventListener("mousedown", (e) =&gt; this.mouseDown(e)); this.maxThumb.element.addEventListener("mousedown", (e) =&gt; this.mouseDown(e)); this.minLabel.addEventListener("input", (e) =&gt; this.changeInputValue(e)); this.maxLabel.addEventListener("input", (e) =&gt; this.changeInputValue(e)); this.minLabel.addEventListener("focusout", (e) =&gt; this.formatInput(e)); this.maxLabel.addEventListener("focusout", (e) =&gt; this.formatInput(e)); window.addEventListener("mouseup", () =&gt; this.mouseUp()); window.addEventListener("mousemove", (e) =&gt; this.mouseMove(e)); } mouseDown(e) { if (e.target === this.minThumb.element) { e.preventDefault(); this.minDragged = true; this.setActive(this.maxThumb.element, this.minThumb.element); } else if (e.target === this.maxThumb.element) { e.preventDefault(); this.maxDragged = true; this.setActive(this.minThumb.element, this.maxThumb.element); } } mouseUp() { this.minDragged = false; this.maxDragged = false; } mouseMove(e) { if (this.minDragged || this.maxDragged) { e.preventDefault(); let input = this.minDragged ? this.minLabel : this.maxLabel; const newValue = this.setPositions(this.getXToPercent(e.clientX), this.minDragged); if (newValue != null) input.value = Math.round(this.getPercentToValue(newValue)); } } changeInputValue(e) { const valueInput = parseFloat(e.target.value); const value = this.getValueToPercent(valueInput); const minActive = e.target.className.includes("min"); this.setPositions(value, minActive); this.setActive(this.container.getElementsByClassName("active")[0], this.container.querySelector(".slider-btn:not(.active)")); } setPositions(inputValue, minActive) { const percentPosMin = this.getXToPercent(this.minThumb.position); const percentPosMax = this.getXToPercent(this.maxThumb.position); let value; if (minActive) { if (inputValue &gt;= 0 &amp;&amp; inputValue &lt;= percentPosMax) value = inputValue; else if (inputValue &lt; 0) value = 0; else if (inputValue &gt; percentPosMax) value = percentPosMax; } else if (!minActive) { if (inputValue &lt;= 100 &amp;&amp; inputValue &gt;= percentPosMin) value = inputValue; else if (inputValue &gt; 100) value = 100; else if (inputValue &lt; percentPosMin) value = percentPosMin; } else return; let thumb = minActive ? this.minThumb : this.maxThumb; thumb.position = value; this.slider.setBackground(minActive ? value : percentPosMin, minActive ? percentPosMax : value); return value; } formatInput(e) { const minValue = this.minLabel.value; const maxValue = this.maxLabel.value; if (maxValue &lt; minValue) this.maxLabel.value = minValue; else if (minValue &gt; maxValue) this.minLabel.value = maxValue; } getXToPercent(elmX) { const slider = this.slider.bounding; return (elmX - slider.left) / slider.width * 100; } getPercentToValue(percent) { return (percent * (this.options.range[1] - this.options.range[0]) * 0.01 + this.options.range[0]); } getValueToPercent(value) { return (value - this.options.range[0]) / (this.options.range[1] - this.options.range[0]) * 100; } setActive(curActiveElement, newActiveElement) { curActiveElement.classList.remove("active"); newActiveElement.className += " active"; } } class Thumb { constructor(_element) { this.element = _element; } get bounding() { return this.element.getBoundingClientRect(); } get x() { return this.element.getBoundingClientRect().x; } get position() { let bounding = this.bounding; return (bounding.x + bounding.width / 2); } set position(value) { this.element.style.left = "calc(" + value + "% - " + this.bounding.width / 2 + "px)"; } } class SliderBackground { constructor(_element) { this.element = _element; } get bounding() { return this.element.getBoundingClientRect(); } setBackground(min, max) { this.element.style.background = "linear-gradient(to right, var(--primary-color) " + min + "%, var(--primary-focus-color) " + min + "%, var(--primary-focus-color) " + max + "%, var(--primary-color) " + max + "%)"; } } let options = { range: [0, 15000], defaultValue: [0, 15000], prefix: "€" }; let slider = new Slider(options, "container-slider");</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>html { --border-radius: 7px; --border-radius-small: 3px; --default-shadow: -3px 5px 15px 6px rgba(0, 0, 0, .35); --btn-shadow: -1px 1px 10px 1px rgba(0, 0, 0, .35); --hover-time: 0.2s; --bg-color: #1F1B24; --sf-color: #332940; --sf2-color: #332940; --primary-color: #1f2d82; --primary-hover-color: #243394; --primary-focus-color: #2E41BD; --header-bg-color: #2C2735; --primary-font-color: white; --primary-font-hover-color: #BABABA; } body { background-color: grey; } .flex { width: 60%; margin-left: 20%; margin-top: 20%; } .container-slider { width: 100%; margin-top: 0.5em !important; } .slider-background { width: 100%; height: 5px; position: relative; display: flex; align-items: center; background-color: yellow; } .slider-btn { cursor: pointer; width: 20px; height: 20px; border-radius: 50%; background-color: var(--primary-font-color); display: inline-block; position: absolute; left: 0; } .slider-btn.active { z-index: 99; } .slider-labels { margin-top: 1em; width: 100%; color: var(--primary-font-color); display: flex; justify-content: space-between; } .prefix_and_input { position: relative; display: inline-block; color: var(--primary-font-color); } .input-value { width: 4em; background: none; border: none; outline: none; color: var(--primary-font-color); font-size: 1em; text-align: center; border-bottom: 1px solid var(--primary-font-color); } .underline-outer { display: flex; justify-content: center; bottom: 0; left: 0; position: absolute; width: 100%; height: 2px; background-color: #64e4fe; } .underline-inner { transition: transform 0.15s ease-out; width: 100%; transform: scale(0, 1); background-color: #1F1B24; height: 100%; } .prefix_and_input&gt;.input-value:focus+.underline-outer&gt;.underline-inner { transform: scale(1); } input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } input[type=number] { -moz-appearance: textfield; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="flex"&gt; &lt;div class="container-slider"&gt; &lt;div class="slider-background"&gt; &lt;span class="slider-btn slider-min active"&gt;&lt;/span&gt; &lt;span class="slider-btn slider-max"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class="slider-labels"&gt; &lt;div class="min-label_and_input"&gt; &lt;label class="label-value label-min" for="input-min"&gt;Min: &lt;/label&gt; &lt;div class="prefix_and_input"&gt; &lt;input type="number" step="1" id="input-min" class="input-value input-min"&gt; &lt;div class="underline-outer"&gt; &lt;div class="underline-inner"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="max-label_and_input"&gt; &lt;label class="label-value label-max" for="input-max"&gt;Max: &lt;/label&gt; &lt;div class="prefix_and_input"&gt; &lt;input type="number" step="1" id="input-max" class="input-value input-max"&gt; &lt;div class="underline-outer"&gt; &lt;div class="underline-inner"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><strong>Problem/Question:</strong> Am I doing OOP in Javascript right? Anything else I'm doing wrong in JS?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T03:09:03.090", "Id": "471329", "Score": "1", "body": "This is not very OOP from the looks of it. It's using classes as namespaces basically. Many of your functions don't return anything and look more procedural. OOP is mostly about composition and encapsulation. There is some encapsulation going on in your code, but not much composition. Nevertheless, your code looks clean and well organized." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T08:57:25.590", "Id": "471352", "Score": "0", "body": "@elclanrs Alright thanks for the info I'll try to take care of composition and encapsulation in my next project :)" } ]
[ { "body": "<p>While your Thumb and SliderBackground classes look fine from an OOP perspective, your Slider, where the bulk of the logic is, has a decent amount of repetitive code in long-ish methods. Many of these can be split apart to into smaller, more abstract methods, which are then more readily understandable from a high level when there's an action to be performed. See the bottom of the answer for a full snippet.</p>\n\n<p>If all you're interested in doing is selecting the first element which matches a selector, the best method is to use <code>querySelector</code>. (<code>getElementsByClassName</code> returns a collection, which means you have to extract the first element of the collection first, which is a bit ugly to do every time you want to get an element). Also, <code>minLabel</code> and <code>maxLabel</code> aren't actually <code>&lt;label&gt;</code>s - they're inputs. Maybe call them <code>minInput</code> and <code>maxInput</code> instead. You can change the lines that are like</p>\n\n<pre><code>this.minLabel = this.container.getElementsByClassName(\"input-min\")[0];\n</code></pre>\n\n<p>to</p>\n\n<pre><code>this.minInput = this.container.querySelector(\".input-min\");\n</code></pre>\n\n<p>Rather than using the conditional operator to determine the maximum and minimum:</p>\n\n<pre><code>const minValue = this.options.defaultValue[0] &gt; this.options.range[0] ? this.options.defaultValue[0] : this.options.range[0];\nconst maxValue = this.options.defaultValue[1] &gt; this.options.range[1] ? this.options.defaultValue[1] : this.options.range[1];\n</code></pre>\n\n<p>You could consider using <code>Math.max</code> and <code>Math.min</code>. Also, since <code>defaultValue</code> is an array, not a single value, maybe call it <code>defaultValues</code>:</p>\n\n<pre><code>const { defaultValues, range, prefix } = this.options;\nconst minValue = Math.min(defaultValues[0], range[0]);\nconst maxValue = Math.max(defaultValues[1], range[1]);\n</code></pre>\n\n<p>The prefix setter is a bit verbose:</p>\n\n<pre><code>if (this.options.prefix !== \"\" &amp;&amp; this.options.prefix !== undefined &amp;&amp; this.options.prefix !== null) {\n let inputs = this.container.getElementsByClassName(\"input-value\");\n for (let i = 0; i &lt; inputs.length; i++) {\n let prefix = document.createElement(\"span\");\n prefix.className = \"slider-input-prefix\";\n prefix.innerHTML = this.options.prefix;\n inputs[i].parentNode.insertBefore(prefix, inputs[i]);\n }\n}\n</code></pre>\n\n<p>You can simplify the <code>if</code> condition to a truthy check, and use the <code>prefix</code> property destructured earlier. I'd call the created span <code>prefixSpan</code> to distinguish it. Conventional <code>for</code> loops are pretty verbose, require manual iteration, and have no abstraction. Since you're using ES6, consider <code>for..of</code> instead. Assigning to <code>innerHTML</code> can result in unexpected elements being created and unexepcted (possibly malicious) scripts being run - use <code>textContent</code> instead, it's safer and faster.</p>\n\n<pre><code>if (this.options.prefix) {\n for (const input of this.container.getElementsByClassName(\"input-value\")) {\n const prefixSpan = document.createElement('span');\n prefixSpan.className = 'slider-input-prefix';\n prefixSpan.textContent = prefix;\n input.parentElement.insertBefore(prefixSpan, input);\n }\n}\n</code></pre>\n\n<p>(also make sure to always use <code>const</code> whenever possible - <code>let</code> <a href=\"https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75\" rel=\"nofollow noreferrer\">warns readers of the code</a> that you may reassign the variable later, leading to more cognitive overhead)</p>\n\n<p>Your <code>assignEvents</code> has <em>eight</em> anonymous functions that call class methods:</p>\n\n<pre><code>assignEvents() {\n this.minThumb.element.addEventListener(\"mousedown\", (e) =&gt; this.mouseDown(e));\n // ...\n}\n</code></pre>\n\n<p>Consider using class field syntax to define the methods instead, then just pass the method name:</p>\n\n<pre><code>mouseDown = (e) =&gt; {\n // ...\n}\n// ...\nassignEvents() {\n this.minThumb.element.addEventListener(\"mousedown\", this.assignEvents);\n</code></pre>\n\n<p>This is pretty new syntax, but it's the cleanest modern way of making sure <code>this</code> refers to what you want it to in a method. (As always, if you're afraid of old browsers being incompatible with modern syntax, use <a href=\"https://babeljs.io/\" rel=\"nofollow noreferrer\">Babel</a> to transpile to ES5 for production)</p>\n\n<p>When your <code>setActive</code> is called, it always has to be called with both the element getting the <code>active</code> class and the element to remove the <code>active</code> class from. It would probably be easier if <code>setActive</code> itself checked for an <code>active</code> class, removed it, then set <code>active</code> on the first (and only) argument. This way the removal logic is encapsulated inside <code>setActive</code>, rather than having the consumer have to figure it out.</p>\n\n<pre><code>setActive(newActiveElement) {\n this.container.querySelector('.active').classList.remove(\"active\");\n newActiveElement.classList.add('active');\n}\n</code></pre>\n\n<p>You currently have both a <code>minDragged</code> and a <code>maxDragged</code> property, but both can't be active at the same time. Rather than having two separate properties that do something very similar, maybe have a single <code>dragged</code> property instead, that you assign <code>min</code> or <code>max</code> to?</p>\n\n<pre><code>mouseDown = (e) =&gt; {\n this.setActive(e.target);\n this.dragged = e.target === this.minThumb.element ? 'min' : 'max';\n}\n</code></pre>\n\n<p>There are a bunch of places in the code where the thumb positions need to be set, given one or both of the inputs, and the slider background needs to be set, given the inputs. These both require a bit of calculations. How about <code>setSliderBackground</code> and <code>updateThumbPositions</code> methods, as well as an <code>updateUI</code> method which calls both? Then you just need to call <code>updateUI</code> when something needs to be updated.</p>\n\n<pre><code>setSliderBackground() {\n this.slider.setBackground(\n this.getXToPercent(this.minThumb.position),\n this.getXToPercent(this.maxThumb.position)\n );\n}\nupdateThumbPositions() {\n this.minThumb.position = this.getValueToPercent(this.minInput.value);\n this.maxThumb.position = this.getValueToPercent(this.maxInput.value);\n}\nupdateUI() {\n this.setSliderBackground();\n this.updateThumbPositions();\n}\n</code></pre>\n\n<p>Your <code>setPositions</code> function has a <em>lot</em> of blocks that may reassign <code>value</code> depending on the range and other slider. Another issue is that the user is permitted to input numbers that are out of range, or have leading zeros, or are empty strings. The slider line currently disappears when an input goes blank. Rather than leaving the possibly-invalid values as is, you could sanitize the inputs to make sure they're within the required range with <code>Math.min</code> and <code>Math.max</code> beforehand - not only when interpreting the values, but also display the sanitized values to the user so they can clearly see what's going on.</p>\n\n<pre><code>sanitizeInput(input) {\n const { range: [low, high] } = this.options;\n // Make sure value is in range of slider:\n const valueInRange = Math.round(Math.max(Math.min(input.value || 0, high), low));\n // Make sure lower value is below or equal to higher:\n input.value = input === this.minInput\n ? Math.min(valueInRange, this.maxInput.value)\n : Math.max(valueInRange, this.minInput.value);\n}\n</code></pre>\n\n<p>There now isn't any need for the <code>setPositions</code> method - it wasn't very abstract anyway. Instead, you can call <code>sanitizeInput</code> and then <code>updateUI</code>.</p>\n\n<p>Instead of</p>\n\n<pre><code>this.element.style.background = \"linear-gradient(to right, var(--primary-color) \" + min + \"%, var(--primary-focus-color) \" + min + \"%, var(--primary-focus-color) \" + max + \"%, var(--primary-color) \" + max + \"%)\";\n</code></pre>\n\n<p>You can consider using template literals to make interpolation much easier, as well as permitting an easy-to-read multiline format:</p>\n\n<pre><code>setBackground(min, max) {\n this.element.style.background = `\n linear-gradient(\n to right,\n var(--primary-color) ${min}%,\n var(--primary-focus-color) ${min}%,\n var(--primary-focus-color) ${max}%,\n var(--primary-color) ${max}%\n )\n `;\n}\n</code></pre>\n\n<p>In full:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>'use strict';\n\nclass Slider {\n constructor(_options, _className) {\n this.options = _options;\n this.container = document.querySelector('.' + _className);\n this.slider = new SliderBackground(this.container.querySelector(\".slider-background\"));\n this.minThumb = new Thumb(this.container.querySelector(\".slider-min\"));\n this.maxThumb = new Thumb(this.container.querySelector(\".slider-max\"));\n this.minInput = this.container.querySelector(\".input-min\");\n this.maxInput = this.container.querySelector(\".input-max\");\n this.dragged = null;\n this.setup();\n }\n setup() {\n this.setStartValues();\n this.assignEvents();\n }\n setStartValues() {\n const { defaultValues, range, prefix } = this.options;\n this.minInput.value = Math.min(defaultValues[0], range[0]);\n this.maxInput.value = Math.max(defaultValues[1], range[1]);\n this.updateUI();\n if (this.options.prefix) {\n for (const input of this.container.getElementsByClassName(\"input-value\")) {\n const prefixSpan = document.createElement('span');\n prefixSpan.className = 'slider-input-prefix';\n prefixSpan.textContent = prefix;\n input.parentElement.insertBefore(prefixSpan, input);\n }\n }\n }\n assignEvents() {\n this.minThumb.element.addEventListener(\"mousedown\", this.mouseDown);\n this.maxThumb.element.addEventListener(\"mousedown\", this.mouseDown);\n this.minInput.addEventListener(\"input\", this.changeInputValue);\n this.maxInput.addEventListener(\"input\", this.changeInputValue);\n window.addEventListener(\"mouseup\", this.mouseUp);\n window.addEventListener(\"mousemove\", this.mouseMove);\n }\n mouseDown = (e) =&gt; {\n e.preventDefault();\n this.setActive(e.target);\n this.dragged = e.target === this.minThumb.element ? 'min' : 'max';\n }\n mouseUp = () =&gt; {\n this.dragged = null;\n }\n mouseMove = (e) =&gt; {\n const { dragged } = this;\n if (!dragged) {\n return;\n }\n e.preventDefault();\n const input = dragged === 'min' ? this.minInput : this.maxInput;\n const { range: [low, high] } = this.options;\n const percent = this.getXToPercent(e.clientX);\n input.value = low + (percent / 100) * (high - low);\n this.sanitizeInput(input);\n this.updateUI();\n }\n sanitizeInput(input) {\n const { range: [low, high] } = this.options;\n // Make sure value is in range of slider:\n const valueInRange = Math.round(Math.max(Math.min(input.value || 0, high), low));\n // Make sure lower value is below or equal to higher:\n input.value = input === this.minInput\n ? Math.min(valueInRange, this.maxInput.value)\n : Math.max(valueInRange, this.minInput.value);\n }\n changeInputValue = (e) =&gt; {\n this.sanitizeInput(e.target);\n this.updateUI();\n this.setActive(this.container.querySelector(\".slider-btn:not(.active)\"));\n }\n setSliderBackground() {\n this.slider.setBackground(\n this.getXToPercent(this.minThumb.position),\n this.getXToPercent(this.maxThumb.position)\n );\n }\n updateThumbPositions() {\n this.minThumb.position = this.getValueToPercent(this.minInput.value);\n this.maxThumb.position = this.getValueToPercent(this.maxInput.value);\n }\n updateUI() {\n this.updateThumbPositions();\n this.setSliderBackground();\n }\n getXToPercent(elmX) {\n const slider = this.slider.bounding;\n return (elmX - slider.left) / slider.width * 100;\n }\n getPercentToValue(percent) {\n return (percent * (this.options.range[1] - this.options.range[0]) * 0.01 + this.options.range[0]);\n }\n getValueToPercent(value) {\n return (value - this.options.range[0]) / (this.options.range[1] - this.options.range[0]) * 100;\n }\n setActive(newActiveElement) {\n this.container.querySelector('.active').classList.remove(\"active\");\n newActiveElement.classList.add('active');\n }\n}\n\nclass Thumb {\n constructor(_element) {\n this.element = _element;\n }\n get bounding() {\n return this.element.getBoundingClientRect();\n }\n get x() {\n return this.element.getBoundingClientRect().x;\n }\n get position() {\n const { bounding } = this;\n return (bounding.x + bounding.width / 2);\n }\n set position(value) {\n this.element.style.left = `calc(${value}% - ${this.bounding.width / 2}px)`;\n }\n}\n\nclass SliderBackground {\n constructor(_element) {\n this.element = _element;\n }\n get bounding() {\n return this.element.getBoundingClientRect();\n }\n setBackground(min, max) {\n this.element.style.background = `\n linear-gradient(\n to right,\n var(--primary-color) ${min}%,\n var(--primary-focus-color) ${min}%,\n var(--primary-focus-color) ${max}%,\n var(--primary-color) ${max}%\n )\n `;\n }\n}\n\nconst options = {\n range: [0, 15000],\n defaultValues: [0, 15000],\n prefix: \"€\"\n};\nconst slider = new Slider(options, \"container-slider\");</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html {\n --border-radius: 7px;\n --border-radius-small: 3px;\n --default-shadow: -3px 5px 15px 6px rgba(0, 0, 0, .35);\n --btn-shadow: -1px 1px 10px 1px rgba(0, 0, 0, .35);\n --hover-time: 0.2s;\n --bg-color: #1F1B24;\n --sf-color: #332940;\n --sf2-color: #332940;\n --primary-color: #1f2d82;\n --primary-hover-color: #243394;\n --primary-focus-color: #2E41BD;\n --header-bg-color: #2C2735;\n --primary-font-color: white;\n --primary-font-hover-color: #BABABA;\n}\n\nbody {\n background-color: grey;\n}\n\n.flex {\n width: 60%;\n margin-left: 20%;\n margin-top: 20%;\n}\n\n.container-slider {\n width: 100%;\n margin-top: 0.5em !important;\n}\n\n.slider-background {\n width: 100%;\n height: 5px;\n position: relative;\n display: flex;\n align-items: center;\n background-color: yellow;\n}\n\n.slider-btn {\n cursor: pointer;\n width: 20px;\n height: 20px;\n border-radius: 50%;\n background-color: var(--primary-font-color);\n display: inline-block;\n position: absolute;\n left: 0;\n}\n\n.slider-btn.active {\n z-index: 99;\n}\n\n.slider-labels {\n margin-top: 1em;\n width: 100%;\n color: var(--primary-font-color);\n display: flex;\n justify-content: space-between;\n}\n\n.prefix_and_input {\n position: relative;\n display: inline-block;\n color: var(--primary-font-color);\n}\n\n.input-value {\n width: 4em;\n background: none;\n border: none;\n outline: none;\n color: var(--primary-font-color);\n font-size: 1em;\n text-align: center;\n border-bottom: 1px solid var(--primary-font-color);\n}\n\n.underline-outer {\n display: flex;\n justify-content: center;\n bottom: 0;\n left: 0;\n position: absolute;\n width: 100%;\n height: 2px;\n background-color: #64e4fe;\n}\n\n.underline-inner {\n transition: transform 0.15s ease-out;\n width: 100%;\n transform: scale(0, 1);\n background-color: #1F1B24;\n height: 100%;\n}\n\n.prefix_and_input&gt;.input-value:focus+.underline-outer&gt;.underline-inner {\n transform: scale(1);\n}\n\ninput::-webkit-outer-spin-button,\ninput::-webkit-inner-spin-button {\n -webkit-appearance: none;\n margin: 0;\n}\n\ninput[type=number] {\n -moz-appearance: textfield;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"flex\"&gt;\n &lt;div class=\"container-slider\"&gt;\n &lt;div class=\"slider-background\"&gt;\n &lt;span class=\"slider-btn slider-min active\"&gt;&lt;/span&gt;\n &lt;span class=\"slider-btn slider-max\"&gt;&lt;/span&gt;\n &lt;/div&gt;\n &lt;div class=\"slider-labels\"&gt;\n &lt;div class=\"min-label_and_input\"&gt;\n &lt;label class=\"label-value label-min\" for=\"input-min\"&gt;Min: &lt;/label&gt;\n &lt;div class=\"prefix_and_input\"&gt;\n &lt;input type=\"number\" step=\"1\" id=\"input-min\" class=\"input-value input-min\"&gt;\n &lt;div class=\"underline-outer\"&gt;\n &lt;div class=\"underline-inner\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"max-label_and_input\"&gt;\n &lt;label class=\"label-value label-max\" for=\"input-max\"&gt;Max: &lt;/label&gt;\n &lt;div class=\"prefix_and_input\"&gt;\n &lt;input type=\"number\" step=\"1\" id=\"input-max\" class=\"input-value input-max\"&gt;\n &lt;div class=\"underline-outer\"&gt;\n &lt;div class=\"underline-inner\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T04:17:16.983", "Id": "240319", "ParentId": "240294", "Score": "1" } } ]
{ "AcceptedAnswerId": "240319", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T17:55:38.587", "Id": "240294", "Score": "5", "Tags": [ "javascript", "object-oriented", "ecmascript-6" ], "Title": "OOP pure JS two Roint Range Slider" }
240294
<p>New to Python and recently turned in an assignment that, in the grading, was reviewed as 'very bad' and 'doesn't use sets' with no further elaboration. Wondering what I can do to improve this code.</p> <p>The assignment instructions and restrictions were as follows:</p> <blockquote> <p><strong>Problem : Card Collections (cards.py)</strong>:</p> </blockquote> <blockquote> <p>In class we talked about collecting packs of cards which form a set. For the purposes of this problem, the full set of cards is numbered 0 to n-1. In addition, each card has a value, in cents. Cards may have different values. Each pack of cards has k cards, some of which may be duplicates. Since we only care about new cards, we immediately give all duplicates away.</p> </blockquote> <blockquote> <p>Write a program that reads in from the user the number of baseball cards in the set (n), the values of each of those n cards, and the contents of three packs of cards.</p> </blockquote> <blockquote> <p>Your program should make the following computations:</p> </blockquote> <blockquote> <p>(1) Calculate the total value of all the unique cards in the three packs all together.</p> </blockquote> <blockquote> <p>(2) Determine which two packs of the three, taken together, create the most value, and print out that value. Implementation Restrictions In order to earn full credit, you must store each pack as its own set.</p> </blockquote> <blockquote> <p>Furthermore, you must write a function that takes in both a set of cards and a full list of the values of all cards, and returns the total value of the set. Here is the function protocol:</p> </blockquote> <blockquote> <p><strong>Pre-condition:</strong> <code>setOfCards</code> is a set of integers in between 0 and n-1, where n is the length of the list <code>listOfCardValues</code>, and <code>listOfCardValues[i]</code> is the value of card number <code>i</code>.</p> </blockquote> <blockquote> <p><strong>Post-condition:</strong> Returns the total value of the cards specified by the set <code>setOfCards</code>. <code>def totalValue(setOfCards, listOfCardValues)</code>:</p> </blockquote> <blockquote> <p>And here is my submission(<strong>please be critical</strong> but explain the issues in my code as I am looking to improve as much as possible):</p> </blockquote> <pre><code># Note: I have some testing print statements in the code if you want to activate them to check out the set structure. # I made significant structure changes. First, I dedicate the data structuring to the first function, cardData() # Additionally, I had cardData() return a list of lists to leave the totalValue() parameters the same as in the prompt. # Another adjustment I made was in the way I called cardData() and other variables to eliminate code bloat. def main(): # This function takes in card data and returns setOfCards list and listOfCardValues list. def cardData(): # These are the first two sets we will build so I've initialized them here. setOfCards = [] listOfCardValues = [] # This is a grab for the top value of our loop. total_cards_in_set = int(input(&quot;How many total cards in the set?\n&gt; &quot;)) # Now we ask the real question, using the stop value from the previous question. print(&quot;List the value, in cents, of each card.\n&quot;) # This is the starting value for the 'set_of_cards' indexing set. index = 0 # Setting only the stop value ensures it is n-1. for card in range(total_cards_in_set): setOfCards.append(index) value = int(input(&quot;&gt; &quot;)) listOfCardValues.append(value) # appends the current card no. to the setOfCards set. index += 1 # This shows specifically what cardData() yields before the return of list of lists. # print(setOfCards, listOfCardValues) return [setOfCards, listOfCardValues] # This function takes in 2 parameter lists and returns user values. def totalValue(setOfCards, listOfCardValues): # print(f&quot;The card index set: {setOfCards}&quot;) # print(f&quot;The card value set: {listOfCardValues}&quot;) # Here we initialize the sets that contain the values of the respective cards. pack1Cards = [] pack2Cards = [] pack3Cards = [] # This variable gives the stop for each sub loop when we are filling each pack#_cards set. cards_in_pack = int(input(&quot;How many cards in a pack?\n&gt; &quot;)) for packNum in range(0, 3): print(f&quot;Input the card values in pack {packNum + 1}&quot;) if packNum == 0: for cardVal in range(0, cards_in_pack): pack1Input = int(input(&quot;&gt; &quot;)) pack1Cards.append(pack1Input) elif packNum == 1: for cardVal in range(0, cards_in_pack): pack2Input = int(input(&quot;&gt; &quot;)) pack2Cards.append(pack2Input) else: for cardVal in range(0, cards_in_pack): pack3Input = int(input(&quot;&gt; &quot;)) pack3Cards.append(pack3Input) # print(f&quot;The card values in set 1: {pack1_cards}&quot;) # print(f&quot;The card values in set 2: {pack2_cards}&quot;) # print(f&quot;The card values in set 3: {pack3_cards}&quot;) # We init a dict for all the sums that we're going to play with. packValues = { 'sum1': sum(pack1Cards), 'sum2': sum(pack2Cards), 'sum3': sum(pack3Cards), } # Initialize the output sets. bestValueNamed = [] bestValue = [] # Check for order of magnitude then append as the sudoku puzzle fills itself. if packValues['sum1'] &gt; packValues['sum2'] or packValues['sum1'] &gt; packValues['sum3']: bestValueNamed.append('pack 1') bestValue.append(packValues['sum1']) # Must nest if statement so that best_value_named set will be ordinal, else output could be 'pack 3 and pack 1'. if packValues['sum2'] &gt; packValues['sum3']: bestValueNamed.append('pack 2') bestValue.append(packValues['sum2']) else: bestValueNamed.append('pack 3') bestValue.append(packValues['sum3']) else: bestValueNamed.extend(['pack 2', 'pack 3']) bestValue.extend([packValues['sum2'], packValues['sum3']]) # print(f&quot;Sum of pack 1: {pack_values['sum1']}&quot;) # print(f&quot;Sum of pack 2: {pack_values['sum2']}&quot;) # print(f&quot;Sum of pack 3: {pack_values['sum3']}&quot;) print(f&quot;The total value of all three packs is {sum(listOfCardValues)}.&quot;) print(f&quot;The two packs with most value are {bestValueNamed[0]} and {bestValueNamed[1]} &quot; f&quot;worth {sum(bestValue)} cents.&quot;) tempArray = cardData() setOfCards = tempArray[0] listOfCardValues = tempArray[1] # print(tempArray) # this array will show the list of lists used to scale totalValue parameters. totalValue(setOfCards, listOfCardValues) main() </code></pre>
[]
[ { "body": "<p>Just right off the bat, you describe lists about your cards as sets. </p>\n\n<p>Lists are different than sets. That's why your teacher is saying you didn't use sets. Sets are created with <code>{}</code> curly brackets, not <code>[]</code> square brackets. What's what is, of course, asked &amp; answered on <a href=\"https://stackoverflow.com/a/4407915/1188513\">Stack Overflow</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T19:00:26.547", "Id": "471291", "Score": "1", "body": "Perfect, thanks! Found a good resource that explained the difference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T04:48:39.017", "Id": "471334", "Score": "2", "body": "This answer isn't quite correct; `tuples` are created with parentheses `('a', 'b', 'c')`, while sets are created with curly braces `{'a', 'b', 'c'}`. However, this is rare to see (in my experience) as they're normally associated with `dict`s `{'a':1, 'b':2}`. Therefore it's normally clearest to specify the type `foo = set()`, passing an iterable (perhaps a tuple) as the first arg or adding values as you go." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T04:49:40.463", "Id": "471335", "Score": "1", "body": "Oh hey that’s totally right. Sleepy brain. Editing, thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T04:49:43.800", "Id": "471336", "Score": "1", "body": "@Jcode94 could you add a link to the resource here? It could be of use to others!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T10:54:52.283", "Id": "471365", "Score": "2", "body": "One problem is that 'set' has two different meanings. In programming and math it refers to a specific kind of collection in which there are no duplicates. In collectable card trading it can refer to a specific group of cards which were printed together. For example, in the early days of Magic the Gathering, there were multiple sets, each of which had different cards. Examples might be Unlimited, Arabian Nights, Artifacts, etc. If the teacher had not been teachings sets before this assignment, I might have misunderstood." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T21:27:54.783", "Id": "471422", "Score": "0", "body": "The resource I found/like was: https://realpython.com/python-sets/\n\nIt goes over the math description of sets, how they work in Python as well as some specific uses. Thanks for the elaboration, also, y'all." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T18:45:29.447", "Id": "240298", "ParentId": "240296", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T18:14:11.413", "Id": "240296", "Score": "5", "Tags": [ "python", "performance" ], "Title": "3 Pack Collectible Card Sorter, High-Value Return" }
240296