body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I created a backup script in bash to basically backup my webservers using cron commands.</p> <p>The script reads one or multiple config file(s), downloads a target directory, and can send by mail the rsync log. It can also keep a number of backup increments.</p> <blockquote> <p><a href="https://github.com/kokmok/my-simple-backup" rel="nofollow noreferrer">https://github.com/kokmok/my-simple-backup</a></p> </blockquote> <pre><code>#!/bin/bash SCRIPT_DIR=&quot;$( cd &quot;$( dirname &quot;${BASH_SOURCE[0]}&quot; )&quot; &amp;&gt; /dev/null &amp;&amp; pwd )&quot; CONFIG_DIR=&quot;$SCRIPT_DIR/config.d&quot; CONFIG_FILES=$(ls &quot;$CONFIG_DIR&quot;/*) CONFIG_NAME_REGEX='backup_name[[:space:]]([a-zA-Z0-9_./\/-]+)' CONFIG_REPORTING='mail_report[[:space:]](YES|NO)' CONFIG_REPORTING_ADDRESS='mail_report_address[[:space:]]([a-zA-Z0-9_./\/-]+@[a-zA-Z0-9_./\/-]+)' USER_REGEX='user[[:space:]]([a-zA-Z0-9_-]+)' HOST_REGEX='host[[:space:]]([a-zA-Z0-9_.-]+)' SOURCE_REGEX='source_folder[[:space:]]([a-zA-Z0-9_./\/-]+)' DEST_REGEX='dest_folder[[:space:]]([a-zA-Z0-9_./\/-]+)' LIMIT_BACKUP_NUMBER_REGEX='limit_backup_number[[:space:]]([0-9]+)' COMPRESS_REGEX='compress_backup[[:space:]](YES|NO)' RSYNC_ERROR_REGEX='rsync[[:space:]]error' get_config_part() { if [[ &quot;$1&quot; =~ $2 ]] then local value=&quot;${BASH_REMATCH[1]}&quot; echo &quot;$value&quot; fi } run_config() { content=$(cat &quot;$1&quot;) configName=$(get_config_part &quot;$content&quot; &quot;$CONFIG_NAME_REGEX&quot;) reporting=$(get_config_part &quot;$content&quot; &quot;$CONFIG_REPORTING&quot;) if [[ $reporting == &quot;YES&quot; ]] then reporting_address=$(get_config_part &quot;$content&quot; &quot;$CONFIG_REPORTING_ADDRESS&quot;) fi user=$(get_config_part &quot;$content&quot; &quot;$USER_REGEX&quot;) host=$(get_config_part &quot;$content&quot; &quot;$HOST_REGEX&quot;) source=$(get_config_part &quot;$content&quot; &quot;$SOURCE_REGEX&quot;) dest=$(get_config_part &quot;$content&quot; &quot;$DEST_REGEX&quot;) limit_backup_number=$(get_config_part &quot;$content&quot; &quot;$LIMIT_BACKUP_NUMBER_REGEX&quot;) compress=$(get_config_part &quot;$content&quot; &quot;$COMPRESS_REGEX&quot;) if [[ ! -d &quot;$SCRIPT_DIR/results&quot; ]] then eval &quot;mkdir $SCRIPT_DIR/results&quot; fi result_file=&quot;$SCRIPT_DIR/results/result_$configName&quot; if [[ ! -f &quot;$result_file&quot; ]] then eval &quot;touch $result_file&quot; fi eval &quot;&gt; $result_file&quot; if [[ ${#user} == 0 || ${#host} == 0 || ${#source} == 0 || ${#dest} == 0 ]] then eval &quot;echo \&quot;[ERROR] bad configuration\&quot; &gt; $result_file&quot; exit 1 fi # If not exist try to create it if [[ ! -d &quot;$dest&quot; ]] then eval &quot;mkdir $dest &gt; $result_file&quot; fi # if still not exists, exit if [[ ! -d &quot;$dest&quot; ]] then eval &quot;echo \&quot;[ERROR] bad configuration: dest directory not exists\&quot; &gt; $result_file&quot; exit 1 fi bkpFolderDate=$(date +&quot;%Y-%m-%d-%H-%M-%S&quot;) eval &quot;mkdir $dest/$bkpFolderDate &gt; $result_file&quot; command=&quot;rsync -avve ssh $user@$host:$source $dest/$bkpFolderDate --log-file=$result_file --timeout=10&quot; eval &quot;$command&quot; if [[ $reporting == &quot;YES&quot; ]] then eval &quot;cat $result_file | mail -s \&quot;backup status of $configName\&quot; $reporting_address&quot; fi if [[ $compress == &quot;YES&quot; ]] then eval &quot;tar -zcf $dest/$bkpFolderDate.tgz $dest/$bkpFolderDate&quot; eval &quot;rm -r $dest/$bkpFolderDate&quot; fi if [[ $(cat &quot;$result_file&quot;) =~ $RSYNC_ERROR_REGEX ]] then echo &quot;rsync failed&quot; eval &quot;rm $dest/$bkpFolderDate -r&quot; else echo &quot;rsync succeeded&quot; limit_backup_number=$((limit_backup_number+1)) eval &quot;(cd $dest &amp;&amp; ls -tp | tail -n +$limit_backup_number | xargs -I {} rm -r -- {})&quot; fi } if [[ $1 != &quot;&quot; ]] then echo &quot;running configuration of $1&quot; run_config &quot;$CONFIG_DIR/$1&quot; else for entry in $CONFIG_FILES do if [[ &quot;$entry&quot; =~ 'sample' ]] then continue fi run_config $entry done fi </code></pre> <p>I'm not really used to bash scripting, so what do you think about mine? Less syntactic, do you observe some <em>weakness</em> or missing points in this script?</p> <p>Personally I don't like having dependencies to services the script cannot manage like <code>msmtp</code> but I don't know how I can manage that.</p>
[]
[ { "body": "<p>Unfortunately, because it is rather difficult for anyone else other than you to actually execute this code and test it, much of my advice will be cursory observations.</p>\n<p>The first thing that catches my eye are the many if/then checks to see if certain files or directories exist. With directories, you can just use <code>mkdir -p &lt;dir&gt;</code>, which will handle that check. With files, you could use <code>test -f</code>.</p>\n<p>The next thing is a minor stylistic choice, but most bash scripters prefer the <code>if &lt;&gt;; then</code> syntax style rather than having <code>then</code> on a new line.</p>\n<p>Lastly, the biggest problem with this program would be the <code>eval</code> statements. Security concerns aside, you could just do <code>touch &quot;$result_file&quot;</code> instead of <code>eval &quot;touch $result_file&quot;</code> for example. Again, I'd use <code>test</code> here instead. Most of your variables are strings, so encapsulating variables in double quotes everywhere shouldn't be necessary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T06:42:56.867", "Id": "515575", "Score": "0", "body": "I'm not convinced that _most_ authors join `if` and `then` onto one line. If it's a majority, then probably only a small majority rather than an overwhelming one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T06:45:24.010", "Id": "515576", "Score": "1", "body": "Yes, the `eval`s are actively harmful, in that they remove a layer of quoting. You'd need `eval \"touch '${result_file//'/\\\\'}'\"`, for example, to deal with arguments properly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T01:46:51.733", "Id": "261262", "ParentId": "261240", "Score": "2" } }, { "body": "<p>As <a href=\"/a/261262/75307\">T145 says</a>, fix the avoidable <code>if</code> tests and <code>eval</code>s first.</p>\n<hr />\n<blockquote>\n<pre><code>CONFIG_FILES=$(ls &quot;$CONFIG_DIR&quot;/*)\n</code></pre>\n</blockquote>\n<p>This won't work correctly when any of the file names contain whitespace. Since we're using Bash, we can expand into an array variable instead:</p>\n<pre><code>CONFIG_FILES=(&quot;$CONFIG_DIR&quot;/*)\n</code></pre>\n<p>We then use it as</p>\n<pre><code>for entry in &quot;${CONFIG_FILES[@]}&quot;\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>if [[ ${#user} == 0 || ${#host} == 0 || ${#source} == 0 || ${#dest} == 0 ]]\nthen\n eval &quot;echo \\&quot;[ERROR] bad configuration\\&quot; &gt; $result_file&quot;\n exit 1\nfi\n</code></pre>\n</blockquote>\n<p>It's good to see configuration checking, and correct use of non-zero exit status. We could improve this by being more specific, and saying <em>which</em> value was wrong. Users would also expect the error message on standard output rather than (or as well as) having to rummage in the result file:</p>\n<pre><code>for v in user host source dest\ndo\n if [ -z &quot;${!v}&quot; ]\n then\n printf '[ERROR] configuration missing value for &quot;%s&quot;\\n' &quot;$v&quot; |\n tee &quot;$result_file&quot; &gt;&amp;2\n exit 1\n fi\ndone\n</code></pre>\n<p>We could be even kinder, and build up a list of missing values, and print them all before we exit:</p>\n<pre><code>missing=()\nfor v in user host source dest\ndo test &quot;${!v}&quot; || missing+=(&quot;$v&quot;)\ndone\nif [ &quot;${missing[*]}&quot; ]\nthen\n printf '[ERROR] configuration missing value for &quot;%s&quot;\\n' &quot;${missing[@]}&quot; |\n tee &quot;$result_file&quot; &gt;&amp;2\n exit 1\nfi\n</code></pre>\n<hr />\n<p>We can simplify this:</p>\n<blockquote>\n<pre><code> do\n if [[ &quot;$entry&quot; =~ 'sample' ]]\n then\n continue\n fi\n run_config $entry\n done\n</code></pre>\n</blockquote>\n<p>Instead of using <code>if</code> and <code>continue</code>, we could just join the test to the single command with <code>||</code>:</p>\n<pre><code> do\n [[ &quot;$entry&quot; =~ 'sample' ]] || run_config $entry\n done\n</code></pre>\n<hr />\n<p>Minor (style): choose an indent level, and stick with it throughout. At present, some regions are indented by 4 characters and others by just 2 - sometimes in the same block, which is very hard to read.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T07:12:11.830", "Id": "261266", "ParentId": "261240", "Score": "1" } }, { "body": "<p>Following all advices I edited my script. I removed all <code>eval</code>; removed a lot of <code>if</code> statements and fix my indent issue.</p>\n<p>I also added some feature like the size of the transfert and the error status in the mail subject.</p>\n<pre><code>#!/bin/bash\nSCRIPT_DIR=&quot;$( cd &quot;$( dirname &quot;${BASH_SOURCE[0]}&quot; )&quot; &amp;&gt; /dev/null &amp;&amp; pwd )&quot;\n\n\nCONFIG_DIR=&quot;$SCRIPT_DIR/config.d&quot;\nCONFIG_FILES=(&quot;$CONFIG_DIR&quot;/*)\nCONFIG_NAME_REGEX='backup_name[[:space:]]([a-zA-Z0-9_./\\/-]+)'\nCONFIG_REPORTING='mail_report[[:space:]](YES|NO)'\nCONFIG_REPORTING_ADDRESS='mail_report_address[[:space:]]([a-zA-Z0-9_./\\/-]+@[a-zA-Z0-9_./\\/-]+)'\nUSER_REGEX='user[[:space:]]([a-zA-Z0-9_-]+)'\nHOST_REGEX='host[[:space:]]([a-zA-Z0-9_.-]+)'\nSOURCE_REGEX='source_folder[[:space:]]([a-zA-Z0-9_./\\/-]+)'\nDEST_REGEX='dest_folder[[:space:]]([a-zA-Z0-9_./\\/-]+)'\nLIMIT_BACKUP_NUMBER_REGEX='limit_backup_number[[:space:]]([0-9]+)'\nCOMPRESS_REGEX='compress_backup[[:space:]](YES|NO)'\nRSYNC_ERROR_REGEX='rsync[[:space:]]error'\nRECEIVED_REGEX='received[[:space:]]([0-9,]+)[[:space:]]bytes'\nERROR=false\n\nget_config_part() {\n if [[ &quot;$1&quot; =~ $2 ]]\n then\n local value=&quot;${BASH_REMATCH[1]}&quot;\n echo &quot;$value&quot;\n fi\n}\n\nrun_config() {\n content=$(cat &quot;$1&quot;)\n configName=$(get_config_part &quot;$content&quot; &quot;$CONFIG_NAME_REGEX&quot;)\n reporting=$(get_config_part &quot;$content&quot; &quot;$CONFIG_REPORTING&quot;)\n if [[ $reporting == &quot;YES&quot; ]]\n then\n reporting_address=$(get_config_part &quot;$content&quot; &quot;$CONFIG_REPORTING_ADDRESS&quot;)\n fi\n user=$(get_config_part &quot;$content&quot; &quot;$USER_REGEX&quot;)\n host=$(get_config_part &quot;$content&quot; &quot;$HOST_REGEX&quot;)\n source=$(get_config_part &quot;$content&quot; &quot;$SOURCE_REGEX&quot;)\n dest=$(get_config_part &quot;$content&quot; &quot;$DEST_REGEX&quot;)\n limit_backup_number=$(get_config_part &quot;$content&quot; &quot;$LIMIT_BACKUP_NUMBER_REGEX&quot;)\n compress=$(get_config_part &quot;$content&quot; &quot;$COMPRESS_REGEX&quot;)\n\n mkdir -p &quot;$SCRIPT_DIR/results&quot;\n\n result_file=&quot;$SCRIPT_DIR/results/result_$configName&quot;\n\n if [ ! -f &quot;$result_file&quot; ]; then touch &quot;$result_file&quot;; fi\n echo &quot;&quot; &gt; &quot;$result_file&quot;\n\n missing_config_values=()\n for config_values in user host source dest\n do test &quot;${!config_values}&quot; || missing_config_values+=(&quot;$config_values&quot;)\n done\n if [ &quot;${missing_config_values[*]}&quot; ]\n then\n printf '[ERROR] configuration missing value for &quot;%s&quot;\\n' &quot;${missing_config_values[@]}&quot; |\n tee &quot;$result_file&quot; &gt;&amp;2\n exit 1\n fi\n\n# If not exist try to create it\n mkdir -p &quot;$SCRIPT_DIR/results&quot;\n mkdir -p &quot;$dest&quot;\n\n if [[ ! -d &quot;$dest&quot; ]]\n then\n echo &quot;[ERROR] bad configuration: dest directory does not exists and cannot be created&quot; | tee &quot;$result_file&quot; &gt;&amp;2\n exit 1\n fi\n\n bkpFolderDate=$(date +&quot;%Y-%m-%d-%H-%M-%S&quot;)\n mkdir &quot;$dest/$bkpFolderDate&quot; &gt; &quot;$result_file&quot; #not sure it returns something\n\n rsync -avve ssh &quot;$user&quot;@&quot;$host&quot;:&quot;$source&quot; &quot;$dest&quot;/&quot;$bkpFolderDate&quot; --log-file=&quot;$result_file&quot; --timeout=10\n\n if [ $compress == &quot;YES&quot; ]\n then\n tar -zcf &quot;$dest/$bkpFolderDate.tgz $dest/$bkpFolderDate&quot;\n rm -r &quot;$dest/$bkpFolderDate&quot;\n fi\n\n if [[ $(cat &quot;$result_file&quot;) =~ $RSYNC_ERROR_REGEX ]]\n then\n echo &quot;rsync failed&quot;\n rm -r &quot;$dest/$bkpFolderDate&quot;\n ERROR=true\n else\n echo &quot;rsync succeeded&quot;\n limit_backup_number=$((limit_backup_number+1))\n cd &quot;$dest&quot; &amp;&amp; ls -tp | tail -n +&quot;$limit_backup_number&quot; | xargs -I {} rm -r -- {}\n fi\n\n if [ $reporting == &quot;YES&quot; ]\n then\n if [ $ERROR == true ];then error_title=&quot;[ERROR]&quot;;else error_title=&quot;&quot;;fi\n if [[ $(cat &quot;$result_file&quot;) =~ $RECEIVED_REGEX ]];then received=&quot;${BASH_REMATCH[1]}&quot;;else received=&quot;0&quot;;fi\n received=$(echo &quot;$received&quot; | sed 's/,//g')\n receivedInMo=$((received/1048576))\n cat &quot;$result_file&quot; | mail -s &quot;$error_title backup status of $configName ($receivedInMo Mo)&quot; &quot;$reporting_address&quot;\n fi\n}\n\nif [[ $1 != &quot;&quot; ]]\nthen\n echo &quot;running configuration of $1&quot;\n run_config &quot;$CONFIG_DIR/$1&quot;\nelse\n for entry in &quot;${CONFIG_FILES[@]}&quot;\n do\n [[ &quot;$entry&quot; =~ 'sample' ]] || run_config $entry\n done\nfi\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T13:26:20.947", "Id": "261544", "ParentId": "261240", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-26T13:06:11.823", "Id": "261240", "Score": "3", "Tags": [ "bash" ], "Title": "Bash script using rsync to backup (another one)" }
261240
<p>This is code for a caesar cipher that I wrote, I would love for anyone who can to offer any improvements/corrections/more efficient methods they can think of. Thanks.</p> <pre class="lang-py prettyprint-override"><code>alphabet=[&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;,&quot;F&quot;,&quot;G&quot;,&quot;H&quot;,&quot;I&quot;,&quot;J&quot;,&quot;K&quot;,&quot;L&quot;,&quot;M&quot;,&quot;N&quot;,&quot;O&quot;,&quot;P&quot;,&quot;Q&quot;,&quot;R&quot;,&quot;S&quot;,&quot;T&quot;,&quot;U&quot;,&quot;V&quot;,&quot;W&quot;,&quot;X&quot;,&quot;Y&quot;,&quot;Z&quot;,&quot; &quot;,&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;,&quot;0&quot;,&quot;,&quot;,&quot;.&quot;] enc_text=[] dec_text=[] def number_check(a): valid=False while valid==False: try: number=int(a) valid=True except ValueError: print(&quot;Invalid entry, You must enter a number.&quot;) a=input(&quot;please enter a number.\n&quot;) return number def encrypt(): for x in org_text: index=alphabet.index(x) enc_letter=(index+int(enc_key))%39 new_let=alphabet[enc_letter] enc_text.append(new_let) return enc_text def decipher(): for x in message: index=alphabet.index(x) dec_letter=(index-int(enc_key))%39 new_let=alphabet[dec_letter] dec_text.append(new_let) return dec_text enc_key=number_check(input(&quot;Please enter your encryption key:\n&quot;)) org_text=input(&quot;please enter the message you would like encrypted:\n&quot;).upper() message=encrypt() message1=&quot;&quot;.join(message) print(message1) decode=decipher() decode1=&quot;&quot;.join(decode) print(decode1) </code></pre>
[]
[ { "body": "<h1>PEP-8</h1>\n<p>White space! Your code needs more white space! The <a href=\"https://pep8.org/\" rel=\"noreferrer\">Style Guide for Python Code</a> enumerates many coding conventions Python programs should follow. One is binary operators (like <code>=</code>, <code>==</code>, <code>+</code>, <code>%</code> should have one space character before and after the operator.</p>\n<p><code>alphabet</code> is a constant. It never changes. PEP-8 would recommend you changing the name to <code>ALPHABET</code> to indicate it is a constant.</p>\n<h1>List of characters</h1>\n<p>A string is essentially just a list of characters. Moreover, it will behave exactly as if it is list of characters.</p>\n<pre class=\"lang-py prettyprint-override\"><code>alphabet=[&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;,&quot;F&quot;,&quot;G&quot;,&quot;H&quot;,&quot;I&quot;,&quot;J&quot;,&quot;K&quot;,&quot;L&quot;,&quot;M&quot;,&quot;N&quot;,&quot;O&quot;,&quot;P&quot;,&quot;Q&quot;,&quot;R&quot;,&quot;S&quot;,&quot;T&quot;,&quot;U&quot;,&quot;V&quot;,&quot;W&quot;,&quot;X&quot;,&quot;Y&quot;,&quot;Z&quot;,&quot; &quot;,&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;,&quot;0&quot;,&quot;,&quot;,&quot;.&quot;]\n</code></pre>\n<p>could be replaced with the much less verbose ...</p>\n<pre class=\"lang-py prettyprint-override\"><code>alphabet = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890,.&quot;\n</code></pre>\n<p>... with no other changes required in your program.</p>\n<h1>One source of truth</h1>\n<p>How many characters are in your alphabet? Did you count? 39? Are you sure? Great! What if you added an apostrophe to the alphabet. The 39 would become 40, and you'd have to change both occurrences of <code>39</code> in your code to <code>40</code>.</p>\n<p>Why are we counting and risking making a mistake? Computers are much better at counting!</p>\n<pre class=\"lang-py prettyprint-override\"><code>ALPHABET_LENGTH = len(alphabet)\n...\n enc_letter = (index + int(enc_key)) % ALPHABET_LENGTH\n...\n dec_letter = (index - int(enc_key)) % ALPHABET_LENGTH\n</code></pre>\n<p>Now if you decide additional letters should be included in the alphabet, you just add them; no other change would be required.</p>\n<h1>Global variables</h1>\n<p><code>alphabet</code> is a global constant. It never changes. In contrast to that, <code>enc_text</code>, <code>dec_text</code>, <code>org_text</code> and <code>message</code> are global variables. They are mutated by the program.</p>\n<p>Avoid global variables. They make the code harder to understand, and harder to maintain.</p>\n<p>Consider <code>encrypt()</code>. You call it and <code>org_text</code> is processed, encrypted and added to the <code>enc_text</code> list. What happens if you change <code>org_text</code> and call <code>encrypt()</code> again? The new text gets <strong><em>added</em></strong> to <code>enc_text</code>.</p>\n<p>Was that expected?</p>\n<p>If <code>enc_text</code> was removed from global scope, and defined inside the <code>encrypt()</code> function, this unexpected behaviour would not happen. Same with <code>dec_text</code>.</p>\n<p>Additionally, global variables should not be used to pass the text to be encrypted/decrypted into the functions; these should be passed as parameters.</p>\n<h1>Bug</h1>\n<p>If you encrypt the message <code>&quot;This fails!&quot;</code>, the program crashes with the exception <code>ValueError: '!' is not in list</code>.</p>\n<p>This is another reason to use an alphabet string instead of a list of characters: strings have another method, <code>.find()</code>, which will return <code>-1</code> if the target isn't found. A <code>list</code> has no such method, forcing you to use <code>try: ... except: ...</code> to catch the exception.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T18:00:52.160", "Id": "515643", "Score": "0", "body": "Thanks @AJNeufeld, incredible feedback." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-26T16:04:01.513", "Id": "261249", "ParentId": "261241", "Score": "6" } }, { "body": "<p>If you look at your <code>encrypt()</code> and <code>decrypt()</code> you might notice that they are mirror images of each other based on <code>key</code>. This might allow us to base them both on a common function that does the rotation for us.</p>\n<p>Let's try this via a closure. Since we have a closure, this will also provide us an opportunity to remove most of the global junk.</p>\n<p>Remember that there is still the &quot;invalid character&quot; issue to deal with though when using this code.</p>\n<pre><code>## --------------------------\n## Calling this closure returns a pair of function that can be used\n## encrypt and decrypt plain text messages.\n## Note that decryption is a mirror of encryption.\n## --------------------------\ndef make_crypt():\n ## remove alphabet from our global context.\n alpha = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890,.&quot;\n len_alpha = len(alpha)\n\n ## this *might* be faster than using alpha.index(letter)\n alpha_index = {letter: index for index, letter in enumerate(alpha)}\n\n ## --------------------------\n ## a function to do rotation based on a key with\n ## a direction.\n ## --------------------------\n def crypt(text_in, key):\n return &quot;&quot;.join([\n alpha[ (alpha_index[letter] + key) % len_alpha ]\n for letter in text_in\n ])\n ## --------------------------\n\n ## --------------------------\n ## return a pair of functions that we can use\n ## --------------------------\n return (\n lambda text, key: crypt(text, key),\n lambda text, key: crypt(text, -key)\n )\n ## --------------------------\n\nencrypt, decrypt = make_crypt()\n## --------------------------\n\n## --------------------------\n## Get our encryption key and ensure that it is an int\n## --------------------------\ndef get_key():\n try:\n return int(input(&quot;Please enter your integer encryption key:\\n&quot;))\n except ValueError:\n print(&quot;Invalid entry, encryption key must enter an integer.&quot;)\n return get_key()\n## --------------------------\n\nenc_key = get_key()\norg_text = input(&quot;please enter the message you would like encrypted:\\n&quot;).upper()\n\nsecret_message = encrypt(org_text, enc_key)\nprint(secret_message)\n\ndecoded_message = decrypt(secret_message, enc_key)\nprint(decoded_message)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:51:21.757", "Id": "262632", "ParentId": "261241", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-26T13:22:47.867", "Id": "261241", "Score": "5", "Tags": [ "python", "python-3.x", "caesar-cipher" ], "Title": "A caesar cipher code" }
261241
<p>A few weeks ago, I developed a terminal game that increases your typing speed. The game is all about typing, providing difficulty levels from easy to hard. I feel like this terminal game won't become as popular as my others, so I need tips on how I could improve this code to make it shorter, easier to run, and more entertaining.</p> <p>Here is the code developed by me, <code>PYWPM</code>:</p> <pre class="lang-py prettyprint-override"><code>import time import random logo = ''' _____ __ _______ __ __ | __ \ \ \ / / __ \| \/ | | |__) | \ \ /\ / /| |__) | \ / | | ___/ | | \ \/ \/ / | ___/| |\/| | | | | |_| |\ /\ / | | | | | | |_| \__, | \/ \/ |_| |_| |_| __/ | |___/ ''' print(logo) print(&quot; &quot;) difficulty = input(&quot;Enter difficulty level (easy/hard): &quot;) if difficulty == &quot;easy&quot;: openPlz = open('easywordbank.txt','r') readPlz = openPlz.read() wordBank = readPlz.split() elif difficulty == &quot;hard&quot;: openPlz = open('hardwordbank.txt','r') readPlz = openPlz.read() wordBank = readPlz.split() open2 = open('highscore.txt','r+') open2lst = open2.readlines() stat = True strike = 0 score = 0 def gameMain(wordBank): #Primary game loop. Returns a lst: #lst[0] = added points, lst[1] = added strikes lst = [0,0] start = time.time() wordQuiz = wordBank[random.randint(0,(len(wordBank)-1))] wordType = input('Enter the word, '+ wordQuiz + ' : ') if wordType == wordQuiz and time.time()-start &lt; 3: lst[0] += 1 elif time.time()-start &gt;= 3: print('STRIKE! Too Slow! ') lst[1] += 1 else: print('STRIKE! Watch your spelling. Be careful with strikes!') lst[1] += 1 return lst def highScore(name,score,highScoreLst,zFile): for line in highScoreLst: if score &gt;= int(line[-3:-1]): highScoreLst.insert(highScoreLst.index(line),name+'-'+str(score)+'\n') highScoreLst.pop() zFile.seek(0,0) zFile.writelines(highScoreLst) break def rsg(): print('Ready?') time.sleep(1) print('Set?') time.sleep(1) print('Go!') time.sleep(1) name = input('Enter a username for this session: ') print(&quot;Type the word then press enter in under 3 seconds!&quot;) time.sleep(2) rsg() #MainState while stat == True: lst = gameMain(wordBank) score += lst[0] strike += lst[1] if strike == 3: time.sleep(.5) print('Game Over! The game has ended..!\n') time.sleep(2) print('Your Typing &amp; Accuracy Score: ' + str(score)) highScore(name,score,open2lst,open2) time.sleep(2) break print('\nHighscores for PyWPM:') time.sleep(2) for line in open2lst: print(line, end='') time.sleep(1.5) time.sleep(5) openPlz.close() open2.close() </code></pre> <ol> <li>Yes, this game includes a word bank that randomizes words.</li> <li>The high scores aren't global.</li> </ol> <p>How could I make this better?</p>
[]
[ { "body": "<p>I made some changes to your code, here's the description:</p>\n<ul>\n<li>Indentation correction;</li>\n<li>Removal of possible spaces in user input;</li>\n<li>Change of <code>While stat ==. True</code> for <code>While stat</code>. It's the same thing;</li>\n<li>PEP8 (and good practices) use 1 blank space after a comma and 2 line breaks before and after the functions;</li>\n<li>You can also simplify the import of packages by specifying exactly what you are going to use: I did it in the code below;</li>\n<li>Finally, the documentation always provides for an empty line break at the end of the code.</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>from time import time, sleep\nfrom random import randint\n\nlogo = '''\n _____ __ _______ __ __ \n | __ \\ \\ \\ / / __ \\| \\/ |\n | |__) | \\ \\ /\\ / /| |__) | \\ / |\n | ___/ | | \\ \\/ \\/ / | ___/| |\\/| |\n | | | |_| |\\ /\\ / | | | | | |\n |_| \\__, | \\/ \\/ |_| |_| |_|\n __/ | \n |___/ \n'''\nprint(logo)\nprint(&quot; &quot;)\ndifficulty = input(&quot;Enter difficulty level (easy/hard): &quot;).strip\nif difficulty == &quot;easy&quot;:\n openPlz = open('easywordbank.txt', 'r')\n readPlz = openPlz.read()\n wordBank = readPlz.split()\nelif difficulty == &quot;hard&quot;:\n openPlz = open('hardwordbank.txt', 'r')\n readPlz = openPlz.read()\n wordBank = readPlz.split()\n\nopen2 = open('highscore.txt', 'r+')\nopen2lst = open2.readlines()\n\nstat = True\nstrike = 0\nscore = 0\n\n\ndef gameMain(wordBank):\n &quot;&quot;&quot;\n Primary game loop. Returns a lst:\n #lst[0] = added points, lst[1] = added strikes\n :param wordBank:\n :return:\n &quot;&quot;&quot;\n lst = [0, 0]\n start = time()\n wordQuiz = wordBank[randint(0,(len(wordBank)-1))]\n wordType = input('Enter the word, '+ wordQuiz + ' : ')\n if wordType == wordQuiz and time()-start &lt; 3:\n lst[0] += 1\n elif time()-start &gt;= 3:\n print('STRIKE! Too Slow! ')\n lst[1] += 1\n else:\n print('STRIKE! Watch your spelling. Be careful with strikes!')\n lst[1] += 1\n return lst\n\n\ndef highScore(name, score, highScoreLst, zFile):\n for line in highScoreLst:\n if score &gt;= int(line[-3:-1]):\n highScoreLst.insert(highScoreLst.index(line), name+'-'+str(score)+'\\n')\n highScoreLst.pop()\n zFile.seek(0, 0)\n zFile.writelines(highScoreLst)\n break\n\n\ndef rsg():\n print('Ready?')\n sleep(1)\n print('Set?')\n sleep(1)\n print('Go!')\n sleep(1)\n\n\nname = input('Enter a username for this session: ')\nprint(&quot;Type the word then press enter in under 3 seconds!&quot;)\nsleep(2)\nrsg()\n\n# MainState\nwhile stat:\n lst = gameMain(wordBank)\n score += lst[0]\n strike += lst[1]\n if strike == 3:\n sleep(.5)\n print('Game Over! The game has ended..!\\n')\n sleep(2)\n print('Your Typing &amp; Accuracy Score: ' + str(score))\n highScore(name, score, open2lst, open2)\n sleep(2)\n break\nprint('\\nHighscores for PyWPM:')\nsleep(2)\nfor line in open2lst:\n print(line, end='')\n sleep(1.5)\nsleep(5)\n\nopenPlz.close()\nopen2.close()\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-26T17:41:55.360", "Id": "261254", "ParentId": "261247", "Score": "4" } }, { "body": "<p>There's a lot.</p>\n<ul>\n<li><code>logo</code> should be <code>LOGO</code> since it's a constant. The other global code, such as acquiring the difficulty, should be moved into functions</li>\n<li>Consider generating the difficulty list based off of a file glob from your actual dictionaries</li>\n<li><code>openPlz</code> is not a great variable name; consider <code>word_bank_file</code></li>\n<li><code>stat</code> is wholly unneeded and you only need a <code>while True</code>; or better yet a loop whose predicate checks the number of strikes</li>\n<li>Use <code>monotonic</code> instead of <code>time</code>; the latter will fail in weird and wonderful ways on some time edge cases</li>\n<li>Save 3 to a global constant</li>\n<li>Consider adding a maximum number of saved high scores</li>\n<li>Doing a simple <code>sort</code> will reduce complexity in <code>highScore</code></li>\n<li><code>highScore</code> should be named <code>high_score</code> by PEP8</li>\n<li><code>rsg</code> is a poor function name; consider <code>countdown</code></li>\n<li>Do not return a list from <code>gameMain</code>; instead return a tuple of two integers, which is more standard</li>\n<li>Call <code>random.choice</code> instead of juggling list indices</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>from time import sleep, monotonic\nimport random\nfrom pathlib import Path\nfrom typing import List, Tuple, TextIO, Iterable, Sequence\n\nLOGO = '''\n _____ __ _______ __ __ \n | __ \\ \\ \\ / / __ \\| \\/ |\n | |__) | \\ \\ /\\ / /| |__) | \\ / |\n | ___/ | | \\ \\/ \\/ / | ___/| |\\/| |\n | | | |_| |\\ /\\ / | | | | | |\n |_| \\__, | \\/ \\/ |_| |_| |_|\n __/ | \n |___/ \n\n'''\n\nTIMEOUT = 3\nMAX_SCORES = 10\n\n\ndef load_words(bank_dir: Path) -&gt; List[str]:\n &quot;&quot;&quot;\n Pulled from:\n https://simple.wikipedia.org/wiki/Wikipedia:List_of_1000_basic_words\n https://raw.githubusercontent.com/dwyl/english-words/master/words.txt\n &quot;&quot;&quot;\n paths = tuple(bank_dir.glob('*-word-bank.txt'))\n stems = {p.stem.split('-', 1)[0].lower(): p for p in paths}\n diffs = '/'.join(stems.keys())\n prompt = f'Enter difficulty level ({diffs}): '\n\n while True:\n diff = input(prompt)\n path = stems.get(diff.lower())\n if path is None:\n print('Invalid difficulty')\n else:\n break\n\n with path.open() as f:\n return [line.rstrip() for line in f]\n\n\ndef countdown() -&gt; None:\n for msg in ('Ready?', 'Set?', 'Go!'):\n sleep(1)\n print(msg, end=' ')\n print()\n\n\ndef game_main(word_bank: Sequence[str]) -&gt; Tuple[\n int, # added points\n int, # added strikes\n]:\n start = monotonic()\n request = random.choice(word_bank)\n answer = input(f'Enter the word - {request} : ')\n\n if monotonic() - start &gt;= TIMEOUT:\n print('STRIKE! Too Slow!')\n return 0, 1\n if request == answer:\n return 1, 0\n\n print('STRIKE! Watch your spelling. Be careful with strikes!')\n return 0, 1\n\n\ndef update_high_scores(name: str, score: int, file: TextIO) -&gt; List[Tuple[int, str]]:\n file.seek(0)\n scores = [(score, name)]\n for line in file:\n name, score = line.rsplit(' - ', 1)\n scores.append((int(score), name))\n\n scores.sort(reverse=True)\n scores = scores[:MAX_SCORES]\n file.truncate(0)\n for score, name in scores:\n file.write(f'{name} - {score}\\n')\n\n return scores\n\n\ndef print_high_scores(scores: Iterable[Tuple[int, str]]) -&gt; None:\n print('Highscores for PyWPM:')\n for score, name in scores:\n print(f'{name} - {score}')\n sleep(0.5)\n\n\ndef main() -&gt; None:\n print(LOGO)\n\n word_bank = load_words(Path('.'))\n\n name = input('Enter a username for this session: ')\n print(f&quot;Type the word then press enter in under {TIMEOUT} seconds!&quot;)\n countdown()\n\n strike, score = 0, 0\n while strike &lt; 3:\n score_addend, strike_addend = game_main(word_bank)\n score += score_addend\n strike += strike_addend\n\n print(\n 'Game Over! The game has ended..!\\n'\n f'Your Typing &amp; Accuracy Score: {score}'\n )\n with open('highscore.txt', 'a+') as highscore_file:\n scores = update_high_scores(name, score, highscore_file)\n\n print_high_scores(scores)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-26T23:43:58.187", "Id": "261259", "ParentId": "261247", "Score": "5" } } ]
{ "AcceptedAnswerId": "261254", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-26T15:51:45.943", "Id": "261247", "Score": "9", "Tags": [ "python", "game", "console" ], "Title": "Terminal Typing Game" }
261247
<p>I’m working with the Google Books API and I’m not so sure about the way I’m going to get the search data and return it to the user. I will describe the path here and I would like to know if you would do something different.</p> <p>First, I receive a search request from the user via a form inside <code>index.html</code>:</p> <pre class="lang-html prettyprint-override"><code>&lt;form action='/lookup' method=&quot;post&quot;&gt; &lt;input type=&quot;text&quot; name=&quot;search&quot; placeholder=&quot;Search by title, author, publisher, release, ISBN ...&quot;&gt; &lt;button type=&quot;submit&quot;&gt;Buscar&lt;/button&gt; {% block search %}{% endblock %} &lt;/form&gt; </code></pre> <p>So in an <code>app.py</code> I get this request like this:</p> <pre class="lang-py prettyprint-override"><code>@app.route(&quot;/lookup&quot;, methods=[&quot;GET&quot;, &quot;POST&quot;]) @login_required def search(): &quot;&quot;&quot;Get book search.&quot;&quot;&quot; if request.method == &quot;POST&quot;: result_check = is_provided(&quot;search&quot;) if result_check is not None: return result_check search = request.form.get(&quot;search&quot;).upper() search = lookup(search) if search is None: return &quot;Invalid Search&quot; return render_template(&quot;search.html&quot;, search={ 'totalItems': search['totalItems'], 'title': search['title'], 'authors': search['authors'] }) else: return render_template(&quot;/&quot;) </code></pre> <p>Next, I access a lookup function in <code>helpers.py</code>:</p> <pre class="lang-py prettyprint-override"><code>def lookup(search): &quot;&quot;&quot;Look up search for books.&quot;&quot;&quot; # Contact API try: url = f'https://www.googleapis.com/books/v1/volumes?q={search}&amp;key=MYAPIKEY' response = requests.get(url) response.raise_for_status() except requests.RequestException: return None # Parse response try: search = response.json() return { &quot;totalItems&quot;: int(search[&quot;totalItems&quot;]), &quot;items&quot;: search[&quot;items&quot;] } except (KeyError, TypeError, ValueError): return None </code></pre> <p>To return the results to the user I have a <code>search.html</code> that is still under construction:</p> <pre class="lang-html prettyprint-override"><code>{% extends &quot;index.html&quot; %} {% block search %} &lt;p&gt;Total Items: {{search['totalItems']}}&lt;/p&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;img src=&quot;{{search['items'][0]['volumeInfo']['imageLinks']['thumbnail']}}&quot;&gt; &lt;p&gt;Título: {{search['items'][0]['volumeInfo']['title']}}&lt;/p&gt; &lt;p&gt;Autor(a): {{search['items'][0]['volumeInfo']['authors']}}&lt;/p&gt; &lt;/td&gt; &lt;td&gt; &lt;img src=&quot;{{search['items'][2]['volumeInfo']['imageLinks']['thumbnail']}}&quot;&gt; &lt;p&gt;Título: {{search['items'][2]['volumeInfo']['title']}}&lt;/p&gt; &lt;p&gt;Autor(a): {{search['items'][2]['volumeInfo']['authors']}}&lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; {% endblock %} </code></pre> <p>Finally, my question: is this path I am following to access the API and return the data to the user the most recommended? Would you do anything other than that?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T05:49:26.660", "Id": "515574", "Score": "1", "body": "Could you clarify what Python framework you are using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T12:02:27.073", "Id": "515596", "Score": "1", "body": "Hi, It is pure Python. I am only using the package Flask." } ]
[ { "body": "<p>Split <code>search()</code> up into two functions, each accepting only one method, and dispose of your <code>if</code>.</p>\n<p>There's a little bit of religion around this, but HTML5 accepts both &quot;naive HTML&quot; and XHTML-compatible tag closure, so this:</p>\n<pre><code>&lt;input type=&quot;text&quot; name=&quot;search&quot;&gt;\n</code></pre>\n<p>is also accepted as</p>\n<pre><code>&lt;input type=&quot;text&quot; name=&quot;search&quot; /&gt;\n</code></pre>\n<p>and the latter is (1) more explicit on where the tag ends and (2) is more broadly compatible.</p>\n<p>This:</p>\n<pre><code>request.form.get(&quot;search&quot;).upper()\n</code></pre>\n<p>does not benefit from <code>get</code>, because you don't provide a default. Either allow the crash on a missing parameter, i.e. <code>request.form['search']</code>, or provide a default to <code>get</code>, likely the empty string.</p>\n<p>This:</p>\n<pre><code>search = lookup(search)\n</code></pre>\n<p>is ill-advised, because it swaps types on the same symbol. The input is a string and the output is a dictionary.</p>\n<p>This:</p>\n<pre><code>url = f'https://www.googleapis.com/books/v1/volumes?q={search}&amp;key=MYAPIKEY'\n \n</code></pre>\n<p>first should not hard-code your API key directly into the string, and second should not format <em>any</em> query parameters into the string. Instead, pass <code>params={...}</code> into <code>get()</code>.</p>\n<p>This:</p>\n<pre><code>except requests.RequestException:\n return None\n</code></pre>\n<p>is fairly catastrophic for the application's ability to tell maintainers and users what went wrong. You're going to want to log the exception, and translate it into an appropriate failure message returned to your own caller.</p>\n<p>This:</p>\n<pre><code>requests.get(url)\n</code></pre>\n<p>should use the response in a <code>with</code>.</p>\n<p>Your <code>search.html</code> template is deeply bizarre. Where I would expect to see a <code>for</code>, you've only shown the first and third items?</p>\n<p>Ensure that you're <a href=\"https://www.w3.org/International/questions/qa-html-language-declarations\" rel=\"nofollow noreferrer\">telling the browser</a> that your content is in Spanish.</p>\n<p>This:</p>\n<pre><code>action='/lookup'\n</code></pre>\n<p>needs to use double quotes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-26T23:23:45.570", "Id": "515571", "Score": "1", "body": "Thanks @Reinderien! You helped me a lot!! As I told, the `search.html` is under construction. I really appreciate your help!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-26T20:35:58.100", "Id": "261257", "ParentId": "261253", "Score": "3" } } ]
{ "AcceptedAnswerId": "261257", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-26T17:23:58.443", "Id": "261253", "Score": "1", "Tags": [ "python", "json", "formatting", "api", "flask" ], "Title": "Read and display JSON results from Google Books API" }
261253
<p>The following code is working as expected but I'm wondering if there's a way to use <code>Object.assign</code>, or some other approach, to build the <code>derivedData</code> object so that it doesn't need to be initialized as an empty object and then populated in a subsequent step.</p> <pre><code>const data = [ {&quot;period&quot;: &quot;2021-05-01&quot;, &quot;quantity&quot;: &quot;28&quot;}, {&quot;period&quot;: &quot;2021-06-01&quot;, &quot;quantity&quot;: &quot;42&quot;}, {&quot;period&quot;: &quot;2021-07-01&quot;, &quot;quantity&quot;: &quot;66&quot;} ]; const derivedData = {}; data.forEach(o =&gt; { derivedData[o.period] = o.quantity }); console.log(data); console.log(derivedData); </code></pre> <p>Expected output of <code>derivedData</code>:</p> <pre><code>{ &quot;2021-05-01&quot;: &quot;28&quot;, &quot;2021-06-01&quot;: &quot;42&quot;, &quot;2021-07-01&quot;: &quot;66&quot; } </code></pre>
[]
[ { "body": "<p>While it technically still would initialize it as an empty object, one could build <code>derivedData</code> with one call to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"nofollow noreferrer\"><code>Array.prototype.reduce()</code></a>. It is similar to <code>forEach()</code> except that the first argument of the callback function is an accumulator variable, that needs to be returned at the end of the function. See the snippet below for a demonstration.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const data = [\n {\"period\": \"2021-05-01\", \"quantity\": \"28\"},\n {\"period\": \"2021-06-01\", \"quantity\": \"42\"},\n {\"period\": \"2021-07-01\", \"quantity\": \"66\"}\n];\n\nconst derivedData = data.reduce((accumulator, o) =&gt; {\n accumulator[o.period] = o.quantity;\n return accumulator;\n}, {});\n\nconsole.log('derivedData: ', derivedData);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>You may find <a href=\"http://reactivex.io/learnrx/\" rel=\"nofollow noreferrer\">these functional exercises</a> interesting.</p>\n<p>Good job using <code>const</code> for variables that don't need to be re-assigned, and using common spacing conventions for modern JavaScript.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-26T20:47:06.173", "Id": "261258", "ParentId": "261256", "Score": "4" } }, { "body": "<p>This can be achieved by using the handy <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries\" rel=\"noreferrer\">Object.fromEntries()</a> function. It takes a list of key-value pairs and constructs an object from the list. For example:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>&gt; Object.fromEntries([['a', 1], ['b', 2]])\n{ a: 1, b: 2 }\n</code></pre>\n<p>In your scenario, we can construct these key-value pairs by simply doing using array.map() on your data. This is what a complete solution looks like:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const data = [\n {\"period\": \"2021-05-01\", \"quantity\": \"28\"},\n {\"period\": \"2021-06-01\", \"quantity\": \"42\"},\n {\"period\": \"2021-07-01\", \"quantity\": \"66\"}\n];\n\nconst derivedData = Object.fromEntries(\n data.map(({ period, quantity }) =&gt; [period, quantity])\n);\n\nconsole.log(data);\nconsole.log(derivedData);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T03:43:04.407", "Id": "261319", "ParentId": "261256", "Score": "5" } } ]
{ "AcceptedAnswerId": "261319", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-26T20:26:37.840", "Id": "261256", "Score": "3", "Tags": [ "javascript", "ecmascript-6", "iteration" ], "Title": "concise way to build an object from an array of objects" }
261256
<p>It is quite long so I'm not sure I can ask you to review my code. But I have no choice indeed.</p> <p>What I'm doing is analyzing the Korean language. To do this, first I collect data and loaded the data via <code>pd.DataFrame</code>. Then, I chunk the text data ('contents' column in the dataframe) into morpheme units by using <code>TextAnalyzer</code>. The below is an example of the process so far:</p> <pre class="lang-py prettyprint-override"><code>data = [document1, document2, ...] # dataframe.loc[:, 'contents'] tokenizer = TextAnalyzer() for item in data: tokenizer.ma.analyze_wordform_parsed(item) # get sentences in the document, and split the sentence into morphemes # results [[(morpheme1 of sentence1, pos1 of sentence1), ..], [(morpheme1 of sentence2, pos1 of sentence2), ...] # for 1 document </code></pre> <p>Now I have morphemes and their corresponding part of speech. And I need this information to get the original word so I made a dictionary for saving the information into <code>M2W</code>.</p> <p>For the collected documents, what I want to do is extracting keywords and sentiment words. For the collection of the morphemes, I need to find sentiment words. Therefore, I also split the sentiment words into their corresponding morphemes. The sentiment words are saved in <code>POS_DICT</code>, <code>NEU_DICT</code> and <code>NEG_DICT</code>. The sentiment morphemes and their corresponding POS are:</p> <pre class="lang-py prettyprint-override"><code>[[(sentiment morpheme1, POS1), (sentiment morepheme2, POS2), ...), ...], ...] # the inside list representing morephemes/POS for a sentiment word </code></pre> <p>So I used the Boyer Moore algorithm to find the patterns which are the sentiment words. The work has proceeded through <a href="https://github.com/xieqihui/pandas-multiprocess" rel="nofollow noreferrer">pandas-multiprocess</a>. Below is the entire code of the process and I made it as a class.</p> <pre class="lang-py prettyprint-override"><code>class KeywordAnalyzer: def __init__(self, morph_path: str=&quot;../rsc/resource/NULL/&quot;, sent_dict: str=&quot;../rsc/sentiment_dict/&quot;) -&gt; None: self.sent_dict = sent_dict self.tokenizer = TextAnalyzer(dict_path=morph_path) self.init_sent_dict(self.sent_dict) # keyword list self.KEYWORDS_POS = {&quot;NNIN1&quot;, # 고유명사 &quot;NNIN2&quot;, # 일반명사 &quot;NPR&quot; # 술어명사 } # POS for part of speech self.init_sent_dict(sent_dict) def init_sent_dict(self, sent_dict: str): self.POS_DICT = set() # POS for positive self.NEG_DICT = set() self.NEU_DICT = set() self.M2W = dict() # Morph to Word def get_morphs(file): words = [item.strip() for item in file] morphs = [tuple(self.tokenizer.ma.analyze_wordform_parsed(item)[0]) for item in words] return words, morphs for item in Path(sent_dict).glob(&quot;*&quot;): with open(item) as f: if item.name.split('_')[1] == &quot;POSITIVE&quot;: words, morphs = get_morphs(f) self.POS_DICT.update(morphs) elif item.name.split('_')[1] == &quot;NEUTRALITY&quot;: words, morphs = get_morphs(f) self.NEU_DICT.update(morphs) elif item.name.split('_')[1] == &quot;NEGATIVE&quot;: words, morphs = get_morphs(f) self.NEG_DICT.update(morphs) temp_dict = {morph:word for word, morph in zip(words, morphs)} self.M2W.update(temp_dict) def get_keywords(self, data: pd.Series) -&gt; Tuple[List[str], List[str], List[str], List[str]]: # make tokens tokens = self.tokenizer.morpheme_analyzer(data.loc['contents']) pos_words = [] neu_words = [] neg_words = [] rels = [] for item in tokens: sentence = list(itertools.chain(*item)) pos_words.extend(self._get_pos_words(sentence)) neu_words.extend(self._get_neu_words(sentence)) neg_words.extend(self._get_neg_words(sentence)) rels.extend(self._get_rel_words(sentence)) return pos_words, neu_words, neg_words, rels # Tuple[[sents_1, ...], [rels_1, ...]] def _get_pos_words(self, sentence: List[Tuple[str, str]]) -&gt; List[str]: words = [self.M2W[sent_morph] for sent_morph in self.POS_DICT if self._boyer_moore(sent_morph, sentence)] return words def _get_neu_words(self, sentence: List[Tuple[str, str]]) -&gt; List[str]: words = [self.M2W[sent_morph] for sent_morph in self.NEU_DICT if self._boyer_moore(sent_morph, sentence)] return words def _get_neg_words(self, sentence: List[Tuple[str, str]]) -&gt; List[str]: words = [self.M2W[sent_morph] for sent_morph in self.NEG_DICT if self._boyer_moore(sent_morph, sentence)] return words def _get_rel_words(self, sentence: List[Tuple[str, str]]) -&gt; List[str]: keywords = [morph for morph, pos in sentence if pos in self.KEYWORDS_POS] return keywords def _boyer_moore(self, pattern: Iterable, text: Iterable) -&gt; bool: def find(pattern, char): for i in range(len(pattern) -2, -1, -1): if pattern[i] == char: return len(pattern) - i - 1 return len(pattern) M = len(pattern) N = len(text) i = 0 while i &lt;= N - M: j = M - 1 while j &gt;= 0: if pattern[j] != text[i + j]: move = find(pattern, text[i + M - 1]) break j = j - 1 if j == -1: return True else: i += move return False </code></pre> <p>I'm not sure the explanation is straightforward but the code convention and the variable names are pretty clear. If you don't understand the process, please check the entire code.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T01:11:16.797", "Id": "261260", "Score": "3", "Tags": [ "python", "performance", "algorithm", "pandas" ], "Title": "Extracting Korean text for sentiment analysis" }
261260
<p>One of my main goals regarding <a href="https://codereview.stackexchange.com/questions/261199/the-blacklist-follow-up">this script</a> has been to figure out a way to use the &quot;adblock.sources&quot; file available on its main repository and not my fork. That version has some syntax issues with its JSON, preventing it from being directly piped into <code>jq</code>.</p> <p>After some research, I came across the <code>jq -n -f {file}</code> command that successfully read in the ill-formatted JSON! I have a couple questions on this feature and one on the <code>sed</code> command.</p> <ol> <li>Is <code>jq -n -f {file}</code> being used properly?</li> <li>Can the two <code>jq</code> commands be blended into one command?</li> <li>Can the two <code>sed</code> parameters be blended into one parameter?</li> </ol> <pre class="lang-sh prettyprint-override"><code>#!/bin/sh set -eu sources=$(mktemp) trap 'rm &quot;$sources&quot;' EXIT curl -s -o &quot;$sources&quot; https://raw.githubusercontent.com/openwrt/packages/master/net/adblock/files/adblock.sources jq -n -f &quot;$sources&quot; | jq -r 'keys[] as $k | [$k, .[$k].url, .[$k].rule] | @tsv' | while IFS=$'\t' read key url rule; do case $key in gaming | oisd_basic | yoyo ) # Ignore these sources: # &quot;gaming&quot; blocks virtually all gaming servers # &quot;oisd_basic&quot; is included in &quot;oisd_full&quot; # &quot;yoyo&quot; is included in &quot;stevenblack&quot; ;; * ) curl -s &quot;$url&quot; | case $url in *.tar.gz) tar -xOzf - ;; *) cat ;; esac | gawk --sandbox -- &quot;$rule&quot; ;; esac done | sed -e 's/\r//g' -e 's/^/0.0.0.0 /' | sort -u &gt;| the_blacklist.txt # use sort over gawk to merge sort multiple temp files instead of using up limited memory </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T01:12:51.583", "Id": "261261", "Score": "2", "Tags": [ "linux", "shell", "sh" ], "Title": "The Blacklist -- Follow-Up 2: Electric Boogaloo" }
261261
<p>I was wondering if it's possible to simplify this regex string (JS):</p> <pre><code>function validateDateString(date){ const regex = /[0-1][0-9]-[0-3][0-9]-[0-9]{4} [0-2][0-9]:[0-5][0-9] [A|P][M]/; return regex.test(date) } </code></pre> <p>It is supposed to validate a string in the following format: <code>MM-DD-YYYY hh:mm A</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T04:29:28.573", "Id": "515573", "Score": "1", "body": "I'm not sure I understand the point of this regex. This accepts invalid dates and substrings like `\"blah blah 19-39-0000 29:00 AM foobar\"`. What is being validated exactly? What application context this is being used in? Thanks for clarifying." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T22:21:37.910", "Id": "515655", "Score": "0", "body": "right, thanks, this is wrong, I have to rewrite" } ]
[ { "body": "<p>Some minor tips:</p>\n<ul>\n<li>Add &quot;^&quot; and &quot;$&quot; to your regex to ensure your input string doesn't contain anything but a date</li>\n<li>No brackets are needed around the <code>[M]</code> - A simple <code>M</code> means the same thing</li>\n<li>Instead of checking for AM/PM with <code>[A|P][M]</code>, keep the AM/PM characters together, like this: <code>(AM|PM)</code> - it makes it much more readable.</li>\n<li>Since it's impossible to accurately test numeric ranges of a date-string in regex, I wouldn't even attempt it. If you really want to ensure the numbers fall into a valid range, do so after the fact, outside of the regex. Inside the regex, you can simply use <code>\\d</code> to match any digit.</li>\n</ul>\n<p>After applying these tips, you'll be left with a pretty simple regex that looks like this:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>/^\\d\\d-\\d\\d-\\d\\d\\d\\d \\d\\d:\\d\\d (AM|PM)$/\n</code></pre>\n<p>As an aside, you might notice it's possible to remove a little repetition in the regex with <code>\\d{2}</code> or <code>\\d{4}</code>, but don't bother. There's not really a lot of repetition, and the <code>{2}</code>/<code>{4}</code> will just obfuscate what you're trying to accomplish here.</p>\n<p>Depending on your use case, simply using the above regex might be good enough, but if you also want to ensure the numbers fall into a valid range, I would actually parse the numbers out of the date-string, feed them into Javascript's Date class, and verify the numbers using the date instance. Relying on the built-in Date class will help with edge cases, such as leap years. In the below code snippet I am assuming that these date-strings are in UTC</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function validateDateString(dateStr) {\n const regex = /^(\\d\\d)-(\\d\\d)-(\\d\\d\\d\\d) (\\d\\d):(\\d\\d) (?:AM|PM)$/;\n const match = regex.exec(dateStr);\n if (!match) return false;\n\n const [month, day, year, hr, min] = match.slice(1).map(Number);\n const date = new Date(Date.UTC(year, month-1, day, hr, min));\n return (\n year === date.getUTCFullYear() &amp;&amp;\n month === date.getUTCMonth() + 1 &amp;&amp;\n day === date.getUTCDate() &amp;&amp;\n hr === date.getUTCHours() &amp;&amp;\n min === date.getUTCMinutes()\n );\n}\n\nconsole.assert(validateDateString('11-30-1999 12:34 AM'));\nconsole.assert(!validateDateString('13-30-1999 12:34 AM'));\nconsole.assert(!validateDateString('1x-30-1999 12:34 AM'));\nconsole.log('Done')</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The important thing to understanding how the above code snippet works, is to understand what happens when you give <code>new Date()</code> (or in this case, <code>date.UTC()</code>) a too-big number. If, for example, you passed in <code>5</code> for the hours and <code>70</code> for the minutes, then it'll normalize the values by moving an hour worth of time from the minutes to the hours, leaving it with <code>6</code> as the hours and <code>10</code> as the minutes.</p>\n<p>Here's what this looks like in action:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>&gt; const d = new Date(0, 0, 0, 5 /* hours */, 70 /* minutes */)\n&gt; d.getHours()\n6\n&gt; d.getMinutes()\n10\n</code></pre>\n<p>In the above example, it's easy enough to test that a numeric overflow happened, we just need to compare our input numbers with our outputs. We can quickly see that <code>5 !== 6</code> and <code>70 !== 10</code>, so some sort of overflow must have happened, which means our date string was not valid. This is the same principle being used in the above code snippet - we just test each input with each output to ensure nothing overflowed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T03:32:50.640", "Id": "261318", "ParentId": "261263", "Score": "2" } } ]
{ "AcceptedAnswerId": "261318", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T02:35:39.260", "Id": "261263", "Score": "1", "Tags": [ "javascript", "regex" ], "Title": "simplifying regex expression for timestamp" }
261263
<p>I made a small rust snake game in order to teach myself rust. I would like to know what I am doing well and poorly, and how to improve my rust code</p> <h1>Cargo.toml</h1> <pre><code>[package] name = &quot;snake-rs&quot; version = &quot;0.1.0&quot; authors = [&quot;Hurricane996 &lt;levijwillrich@gmail.com&gt;&quot;] edition = &quot;2018&quot; # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] sdl2 = &quot;0.34&quot; rand = &quot;0.8&quot; [profile.release] lto = true </code></pre> <h1>src/main.rs</h1> <pre><code>extern crate sdl2; extern crate rand; mod constants; mod fruit; mod snake; mod vector2; use constants::BOARD_WIDTH; use constants::BOARD_HEIGHT; use constants::CELL_SIZE; use fruit::Fruit; use snake::Snake; use vector2::Vector2; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use std::collections::VecDeque; use std::time::Duration; fn main() { let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let window = video_subsystem.window(&quot;Rust Snake&quot;, BOARD_WIDTH*CELL_SIZE, BOARD_HEIGHT*CELL_SIZE) .position_centered() .build() .unwrap(); let mut canvas = window.into_canvas().build().unwrap(); let mut event_pump = sdl_context.event_pump().unwrap(); let mut rng = rand::thread_rng(); let mut snake = Snake::new(); let mut fruit = Fruit::new(); let mut frame_counter = 0; let mut input_stack = VecDeque::&lt;Vector2&gt;::with_capacity(32); fruit.mv(&amp;mut rng); 'running: loop { for event in event_pump.poll_iter() { match event { Event::Quit {..} =&gt; { break 'running; }, Event::KeyDown {keycode,..} =&gt; { match keycode.expect(&quot;&quot;) { Keycode::Up | Keycode:: W =&gt; { input_stack.push_front(-Vector2::J); } Keycode::Down | Keycode:: S =&gt; { input_stack.push_front(Vector2::J); } Keycode::Left | Keycode:: A =&gt; { input_stack.push_front(-Vector2::I); } Keycode::Right | Keycode:: D =&gt; { input_stack.push_front(Vector2::I); } _ =&gt; {} } } _ =&gt; {} } } frame_counter+=1; if frame_counter &gt; Snake::SPEED { frame_counter = 0; snake.mv(&amp;mut input_stack, &amp;fruit); if !snake.safe() {break 'running; } if snake.is_eating_fruit(&amp;fruit) { fruit.mv(&amp;mut rng); } } canvas.set_draw_color(Color::BLACK); canvas.clear(); snake.draw(&amp;mut canvas); fruit.draw(&amp;mut canvas); canvas.present(); std::thread::sleep(Duration::new(0, 1_000_000_000u32 / 60)); } } </code></pre> <h1>src/fruit.rs</h1> <pre><code>use crate::constants::BOARD_WIDTH; use crate::constants::BOARD_HEIGHT; use crate::constants::CELL_SIZE; use crate::vector2::Vector2; use rand::Rng; use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::render::Canvas; use sdl2::render::RenderTarget; pub struct Fruit(pub Vector2); impl Fruit { pub fn new() -&gt; Self { Fruit ( Vector2 { x: 0, y: 0 }) } pub fn mv&lt;R: Rng&gt;(&amp;mut self, rng: &amp;mut R ) { self.0.x = rng.gen_range(0..BOARD_WIDTH) as i32; self.0.y = rng.gen_range(0..BOARD_HEIGHT) as i32; } pub fn draw&lt;T: RenderTarget&gt;(&amp;mut self, canvas: &amp;mut Canvas&lt;T&gt;) { canvas.set_draw_color(Color::RED); canvas.fill_rect(Rect::new(self.0.x * CELL_SIZE as i32, self.0.y * CELL_SIZE as i32, CELL_SIZE, CELL_SIZE)).unwrap(); } } </code></pre> <h1>src/snake.rs</h1> <pre><code>use crate::constants::BOARD_HEIGHT; use crate::constants::BOARD_WIDTH; use crate::constants::CELL_SIZE; use crate::fruit::Fruit; use crate::vector2::Vector2; use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::render::Canvas; use sdl2::render::RenderTarget; use std::collections::VecDeque; pub struct Snake { direction: Vector2, head: Vector2, body: VecDeque::&lt;Vector2&gt; } impl Snake { pub fn new() -&gt; Self { let mut s = Snake { head: Vector2::new((BOARD_WIDTH/2) as i32, (BOARD_HEIGHT/2) as i32), direction: Vector2::I, body: VecDeque::&lt;Vector2&gt;::with_capacity((BOARD_WIDTH*BOARD_HEIGHT) as usize), }; for i in 1..(Self::INITIAL_SIZE) { let i = i as i32; s.body.push_back(Vector2::new(s.head.x - i, s.head.y)) } return s; } pub fn mv(&amp;mut self, input_stack: &amp;mut VecDeque::&lt;Vector2&gt;, fruit: &amp;Fruit) { //this pushes the old head, so the body does not contain the head. self.body.push_front(self.head); 'process_input: loop { let maybe_input = input_stack.pop_back(); match maybe_input { Some(input) =&gt; { if input != self.direction &amp;&amp; input != -self.direction { self.direction = input; break 'process_input; } } None =&gt; { break 'process_input; } } } self.head = self.head + self.direction; if self.head != fruit.0 { self.body.pop_back(); } } pub fn is_eating_fruit(&amp;self, fruit: &amp;Fruit) -&gt; bool { self.head == fruit.0 || self.body.iter().any(|&amp;i|i==fruit.0) } pub fn safe(&amp;self) -&gt; bool { !( self.body.iter().any(|&amp;i|i==self.head) || self.head.x &lt; 0|| self.head.y &lt; 0 || self.head.x &gt;= BOARD_WIDTH as i32 || self.head.y &gt;= BOARD_HEIGHT as i32 ) } pub fn draw&lt;T: RenderTarget&gt;(&amp;self, canvas: &amp;mut Canvas&lt;T&gt;) { canvas.set_draw_color(Color::GREEN); canvas.fill_rect(Rect::new(self.head.x * CELL_SIZE as i32, self.head.y * CELL_SIZE as i32, CELL_SIZE, CELL_SIZE)).unwrap(); for segment in &amp;self.body { canvas.fill_rect(Rect::new(segment.x * CELL_SIZE as i32, segment.y * CELL_SIZE as i32, CELL_SIZE, CELL_SIZE )).unwrap(); } } pub const SPEED: u32 = 15; const INITIAL_SIZE: u32 = 3; } </code></pre> <h1>src/Vector2.rs</h1> <pre><code>use std::ops; #[derive(Copy,Clone,PartialEq)] pub struct Vector2 { pub x: i32, pub y: i32 } impl Vector2 { pub fn new(x: i32, y: i32) -&gt; Vector2 { Vector2 { x: x, y: y } } pub const I : Vector2 = Vector2 {x: 1,y: 0}; pub const J : Vector2 = Vector2 {x: 0,y: 1}; } impl ops::Add&lt;Vector2&gt; for Vector2 { type Output = Self; fn add(self, rhs: Self) -&gt; Self::Output { Vector2 { x: self.x + rhs.x, y: self.y + rhs.y } } } impl ops::Neg for Vector2 { type Output = Self; fn neg(self) -&gt; Self::Output { Vector2 { x: -self.x, y: -self.y } } } </code></pre> <h1>src/constants.rs</h1> <pre><code>pub const BOARD_HEIGHT: u32 = 16; pub const BOARD_WIDTH: u32 = 16; pub const CELL_SIZE: u32 = 32; </code></pre>
[]
[ { "body": "<p>First of all, there are some quick things I'd change. <code>extern crate [crate name];</code> is not needed in the 2018 edition of rust, and as such can be removed. Running <code>clippy</code> also shows some easy changes - firstly, in the <code>Vector2::new</code> function, you can change <code>Vector2 { x: x, y: y }</code> to <code>Vector2 { x, y }</code>. You can also replace the <code>return s;</code> with just <code>s</code> in <code>Snake::new</code>, as if a semicolon is omitted on the last line of a block, the value is returned.</p>\n<p>There are also some style decisions I would personally change. Firstly, running <code>cargo fmt</code> can clean up a lot of minor issues (such as no spaces between items in the derive macros). Another is your using statements - you can replace</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use constants::BOARD_HEIGHT;\nuse constants::BOARD_WIDTH;\nuse constants::CELL_SIZE;\n</code></pre>\n<p>with</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use constants::{BOARD_HEIGHT, BOARD_WIDTH, CELL_SIZE};\n</code></pre>\n<p>which personally I prefer, but it is up to you. Similar things can be done with the other blocks, such as</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::collections::VecDeque;\nuse std::time::Duration;\n</code></pre>\n<p>to</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::{collections::VecDeque, time::Duration};\n</code></pre>\n<p>Now for code changes:</p>\n<ul>\n<li>The <code>'running</code> label in <code>main</code> and the <code>'process_input</code> in <code>Snake::mv</code> should be removed as there are no nested loops, so a normal <code>break</code> works fine. In general, you only want to use labels for situations like wanting to break out of an outer loop while in an inner loop.</li>\n<li>The <code>.unwrap()</code> calls can be replaced with <code>.expect([error message])</code> calls if you still want to panic on failures, but using expect will give more information. This will make it easier to spot what is actually going wrong.</li>\n<li>Functions and structs should have doc comments explaining what they're doing. For example, <code>Vector2::I</code> could be commented as follows to better explain it. This is not strictly necessary, but most editors will show the text when function calls/constants/structs are hovered over, so it can help a lot with understanding what programs are doing.</li>\n</ul>\n<pre class=\"lang-rust prettyprint-override\"><code>/// The unit vector representing (1, 0).\npub const I: Vector2 = Vector2 { x: 1, y: 0 };\n</code></pre>\n<ul>\n<li>Type annotations on <code>input_stack</code> in <code>main</code> and <code>body</code> in <code>Snake::new</code> for <code>VecDeque::&lt;Vector2&gt;</code> can be removed - so</li>\n</ul>\n<pre class=\"lang-rust prettyprint-override\"><code>let mut input_stack = VecDeque::&lt;Vector2&gt;::with_capacity(32);\n</code></pre>\n<p>would become</p>\n<pre class=\"lang-rust prettyprint-override\"><code>let mut input_stack = VecDeque::with_capacity(32);\n</code></pre>\n<p>And for what you've done well:</p>\n<ul>\n<li>Using traits for operations such as <code>Add</code> is a very good habit.</li>\n<li>Good use of iterators in functions like <code>Snake::safe</code>. Iterators are almost always more idiomatic than alternatives, so it is a good idea to get comfortable to using them (as well as methods like <code>map</code> and <code>fold</code>).</li>\n<li>Initializing vectors with a given capacity is very handy for reducing the number of re-allocations, and this is a perfect use case for them - since you know the upper bound of how many items will ever be in the vector.</li>\n<li>Using constants throughout your code (such as <code>Snake::SPEED</code>), compared to the alternative of littering magic numbers throughout your code.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T12:57:15.857", "Id": "261376", "ParentId": "261265", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T06:13:18.413", "Id": "261265", "Score": "4", "Tags": [ "game", "rust", "sdl" ], "Title": "Snake game in rust" }
261265
<p>This code was written to capture extracted text from emails and store those details in a database.</p> <p>I would like to reduce the amount of code, improve simplicity and reduce the duplication of my code. The code has become very large because of copy-pasting; 90% of the code is copy-pasted instead of using any logic. Now I need help in building a logic to get rid of the copy pasted code to improve it.</p> <pre><code>class SubmissionFieldsSerializer(serializers.ModelSerializer): class Meta: model = submissionfields fields = '__all__' def update(self, instance, validated_data): instance.email_id = validated_data.get('email_id', instance.email_id) instance.email_ml_recommendation = validated_data.get('email_ml_recommendation', instance.email_ml_recommendation) instance.ef_insured_name = validated_data.get('ef_insured_name', instance.ef_insured_name) instance.ef_broker_name = validated_data.get('ef_broker_name', instance.ef_broker_name) instance.ef_obligor_name = validated_data.get('ef_obligor_name', instance.ef_obligor_name) instance.ef_guarantor_third_party = validated_data.get('ef_guarantor_third_party', instance.ef_guarantor_third_party) instance.ef_coverage = validated_data.get('ef_coverage', instance.ef_coverage) instance.ef_financials = validated_data.get('ef_financials', instance.ef_financials) instance.ef_commercial_brokerage = validated_data.get('ef_commercial_brokerage', instance.ef_commercial_brokerage) # fixing bug of pipeline instance.ef_underwriter_decision = validated_data.get('ef_underwriter_decision', instance.ef_underwriter_decision) instance.ef_decision_nty_fields = validated_data.get('ef_decision_nty_fields', instance.ef_decision_nty_fields) instance.ef_feedback = validated_data.get('ef_feedback', instance.ef_feedback) # instance.ef_feedback = validated_data.get('ef_feedback', instance.ef_feedback) instance.relation_id = validated_data.get('relation_id', instance.relation_id) instance.email_outlook_date = validated_data.get('email_outlook_date', instance.email_outlook_date) instance.ef_decision_nty_fields = validated_data.get('ef_decision_nty_fields', instance.ef_decision_nty_fields) instance.ef_pl_est_premium_income = validated_data.get('ef_pl_est_premium_income', instance.ef_pl_est_premium_income) instance.ef_pl_prob_closing = validated_data.get('ef_pl_prob_closing', instance.ef_pl_prob_closing) instance.ef_pl_time_line = validated_data.get('ef_pl_time_line', instance.ef_pl_time_line) instance.ef_pipeline = validated_data.get('ef_pipeline', instance.ef_pipeline) instance.el_insured_margin = validated_data.get('el_insured_margin', instance.el_insured_margin) instance.ef_last_updated = validated_data.get('ef_last_updated', instance.ef_last_updated) instance.relation_id = validated_data.get('relation_id', instance.relation_id) # CR3.2 Primium and basis point addition instance.broker_email_id = validated_data.get('broker_email_id', instance.broker_email_id) instance.premium = validated_data.get('premium', instance.premium) instance.basis_points = validated_data.get('basis_points', instance.basis_points) instance.basis_points_decision = validated_data.get('basis_points_decision', instance.basis_points_decision) embedded_json = validated_data.get('email_embedd', instance.email_embedd) instance.email_embedd = json.dumps(embedded_json) # # if instance.ef_underwriter_decision == 'not_taken': # instance.ef_underwriter_decision = validated_data.get('ef_underwriter_decision', # instance.ef_underwriter_decision) # instance.ef_feedback = validated_data.get('ef_feedback', instance.ef_feedback) # NBI USE CASE if instance.ef_underwriter_decision == configur.get('decisions', 'non_binding_indication'): # enquiry Log dict_obj = temp_dict() # Update Submission table based on underwriter decision submission.objects.filter(email_id=instance.email_id).update(email_status='active') submission.objects.filter(email_id=instance.email_id).update( email_uwriter_decision=instance.ef_underwriter_decision) submission.objects.filter(email_id=instance.email_id).update( email_today_mail=configur.get('mailstatus', 'nbi_mail_type')) instance.email_today_mail = configur.get('mailstatus', 'nbi_mail_type') # setting email_today maio to 0 for submission fields # CR7.1 Changes (FROM COMPLETED TAB TO PROCESSED TAB) submission.objects.filter(email_id=instance.email_id).update( email_deleted=configur.get('mailstatus', 'nbi_mail_type')) temp_email_table = submission.objects.filter(email_id=instance.email_id).values( 'email_id', 'enquiry_id', 'email_sender', 'email_subject', 'email_broker', 'email_outlook_date', 'email_today_mail', 'email_assigned_user', 'email_deleted') for today in temp_email_table: for t in today: dict_obj.add(t, today[t]) if len(validated_data.get('ef_insured_name', instance.ef_insured_name)['name']) == 0: dict_obj.add('ef_insured_name', &quot;not available&quot;) else: dict_obj.add('ef_insured_name', validated_data.get('ef_insured_name', instance.ef_insured_name)['name']) if len(validated_data.get('ef_obligor_name', instance.ef_obligor_name)['name']) == 0: dict_obj.add('ef_obligor_name', &quot;not available&quot;) else: dict_obj.add('ef_obligor_name', validated_data.get('ef_obligor_name', instance.ef_obligor_name)['name']) if len(validated_data.get('ef_obligor_name', instance.ef_obligor_name)['country']) == 0: dict_obj.add('el_country_name', &quot;not available&quot;) else: dict_obj.add('el_country_name', validated_data.get('ef_obligor_name', instance.ef_obligor_name)['country']) dict_obj.add('enquirylog_limit', validated_data.get('ef_financials', instance.ef_financials)['limit']) dict_obj.add('ef_underwriter_decision', validated_data.get('ef_underwriter_decision', instance.ef_underwriter_decision)) dict_obj.add('ef_decision_nty_fields', validated_data.get('ef_decision_nty_fields', instance.ef_decision_nty_fields)) dict_obj.add('ef_feedback', validated_data.get('ef_feedback', instance.ef_feedback)) dict_obj.add('relation_id', validated_data.get('relation_id', instance.relation_id)) dict_obj.add('enquirylog_status', 'active') dict_obj.add('enquirylog_pipeline', validated_data.get('ef_pipeline', instance.ef_pipeline)) # CR3.2 Primium and basis point addition dict_obj.add('broker_email_id', validated_data.get('broker_email_id', instance.broker_email_id)) dict_obj.add('premium', validated_data.get('premium', instance.premium)) dict_obj.add('basis_points_decision', validated_data.get('basis_points_decision', instance.basis_points_decision)) dict_obj.add('basis_points', validated_data.get('basis_points', instance.basis_points)) dict_obj.add('coverage', validated_data.get('ef_coverage', instance.ef_coverage)['coverage']) dict_obj.add('tenor', validated_data.get('ef_coverage', instance.ef_coverage)['tenor']) enquiry = enquirylog(email_id=dict_obj['email_id'], enquiry_id=dict_obj['enquiry_id'], coverage=dict_obj['coverage'], tenor=dict_obj['tenor'], email_subject=dict_obj['email_subject'], relation_id=dict_obj['relation_id'], email_broker=dict_obj['email_broker'], email_outlook_date=dict_obj['email_outlook_date'], enquirylog_limit=dict_obj['enquirylog_limit'], email_assigned_user=dict_obj['email_assigned_user'], email_today_mail=dict_obj['email_today_mail'], ef_insured_name=dict_obj['ef_insured_name'], ef_obligor_name=dict_obj['ef_obligor_name'], el_country_name=dict_obj['el_country_name'], ef_underwriter_decision=dict_obj['ef_underwriter_decision'], ef_decision_nty_fields=dict_obj['ef_decision_nty_fields'], ef_feedback=dict_obj['ef_feedback'], enquirylog_status=dict_obj['enquirylog_status'], enquirylog_pipeline=dict_obj['enquirylog_pipeline'], email_deleted=dict_obj['email_deleted'], premium=dict_obj['premium'], basis_points=dict_obj['basis_points'], basis_points_decision=dict_obj['basis_points_decision'], broker_email_id=dict_obj['broker_email_id'] ) enquiry.save() # Pipeline Enquiry Log do_pipeline_entry = validated_data.get('ef_pipeline', instance.ef_pipeline) if do_pipeline_entry: dict_obj = temp_dict() submission.objects.filter(email_id=instance.email_id).update( email_uwriter_decision=instance.ef_underwriter_decision) submission.objects.filter(email_id=instance.email_id).update( email_today_mail=configur.get('mailstatus', 'minfo_mail_type')) instance.email_today_mail = configur.get('mailstatus', 'minfo_mail_type') temp_email_table = submission.objects.filter(email_id=instance.email_id).values( 'email_id', 'enquiry_id', 'email_sender', 'email_outlook_date', 'email_assigned_user', 'email_deleted') for today in temp_email_table: for t in today: dict_obj.add(t, today[t]) if len(validated_data.get('ef_insured_name', instance.ef_insured_name)['name']) == 0: dict_obj.add('ef_insured_name', not_avbl) else: dict_obj.add('ef_insured_name', validated_data.get('ef_insured_name', instance.ef_insured_name)['name']) if len(validated_data.get('ef_obligor_name', instance.ef_obligor_name)['name']) == 0: dict_obj.add('ef_obligor_name', not_avbl) else: dict_obj.add('ef_obligor_name', validated_data.get('ef_obligor_name', instance.ef_obligor_name)['name']) if len(validated_data.get('ef_obligor_name', instance.ef_obligor_name)['country']) == 0: dict_obj.add('el_country_name', not_avbl) else: dict_obj.add('el_country_name', validated_data.get('ef_obligor_name', instance.ef_obligor_name) ['country']) dict_obj.add('el_line_usd', validated_data.get('ef_financials', instance.ef_financials) ['limit']) dict_obj.add('el_tenor', validated_data.get('ef_coverage', instance.ef_coverage) ['tenor']) dict_obj.add('ef_pl_est_premium_income', validated_data.get('ef_pl_est_premium_income', instance.ef_pl_est_premium_income)) dict_obj.add('el_insured_margin', validated_data.get('el_insured_margin', instance.el_insured_margin)) dict_obj.add('ef_pl_prob_closing', validated_data.get('ef_pl_prob_closing', instance.ef_pl_prob_closing)) dict_obj.add('ef_pl_time_line', validated_data.get('ef_pl_time_line', instance.ef_pl_time_line)) dict_obj.add('ef_feedback', validated_data.get('ef_feedback', instance.ef_feedback)) dict_obj.add('relation_id', validated_data.get('relation_id', instance.relation_id)) dict_obj.add('ef_created', validated_data.get('ef_created', instance.ef_created)) dict_obj.add('is_pipeline', &quot;1&quot;) # CR3.2 Primium and basis addition dict_obj.add('premium', validated_data.get('premium', instance.premium)) dict_obj.add('basis_points_decision', validated_data.get('basis_points_decision', instance.basis_points_decision)) dict_obj.add('basis_points', validated_data.get('basis_points', instance.basis_points)) dict_obj.add('coverage', validated_data.get('ef_coverage', instance.ef_coverage) ['coverage']) dict_obj.add('tenor', validated_data.get('ef_coverage', instance.ef_coverage)['tenor']) st = pipelineenquirylog.objects.filter(email_id=instance.email_id).count() if st == 1: # Creating object of query set inorder to update udateed field time inst = pipelineenquirylog.objects.get(email_id=instance.email_id) inst.enquiry_id = dict_obj['enquiry_id'] inst.coverage = dict_obj['coverage'] inst.tenor = dict_obj['tenor'] inst.email_assigned_user = dict_obj['email_assigned_user'] inst.ef_insured_name = dict_obj['ef_insured_name'] inst.ef_obligor_name = dict_obj['ef_obligor_name'] inst.el_country_name = dict_obj['el_country_name'] inst.el_line_usd = dict_obj['el_line_usd'] inst.el_tenor = dict_obj['el_tenor'] inst.ef_pl_est_premium_income = dict_obj['ef_pl_est_premium_income'] inst.el_insured_margin = dict_obj['el_insured_margin'] inst.ef_pl_prob_closing = dict_obj['ef_pl_prob_closing'] inst.ef_pl_time_line = instance.ef_pl_time_line inst.ef_feedback = dict_obj['ef_feedback'] inst.is_pipeline = '1' inst.email_deleted = dict_obj['email_deleted'] # CR3.2 Primium and basis point addition inst.premium = dict_obj['premium'] inst.basis_points = dict_obj['basis_points'] inst.basis_points_decision = dict_obj['basis_points_decision'] inst.save() else: print(&quot;doing new entry for pipeline as no previous entry 123&quot;) print('pipeline value is : ', dict_obj['is_pipeline']) print(dict_obj) pipeline1 = pipelineenquirylog(email_outlook_date=dict_obj['email_outlook_date'], email_id=dict_obj['email_id'], enquiry_id=dict_obj['enquiry_id'], coverage=dict_obj['coverage'], tenor=dict_obj['tenor'], relation_id=dict_obj['relation_id'], email_assigned_user=dict_obj['email_assigned_user'], ef_insured_name=dict_obj['ef_insured_name'], ef_obligor_name=dict_obj['ef_obligor_name'], el_country_name=dict_obj['el_country_name'], el_line_usd=dict_obj['el_line_usd'], el_tenor=dict_obj['el_tenor'], ef_pl_est_premium_income=dict_obj['ef_pl_est_premium_income'], el_insured_margin=dict_obj['el_insured_margin'], ef_pl_prob_closing=dict_obj['ef_pl_prob_closing'], ef_pl_time_line=dict_obj['ef_pl_time_line'], ef_feedback=dict_obj['ef_feedback'], is_pipeline=dict_obj['is_pipeline'], email_deleted=dict_obj['email_deleted'], # CR3.2 Primium and basis point addition premium=dict_obj['premium'], basis_points=dict_obj['basis_points'], basis_points_decision=dict_obj['basis_points_decision'] ) pipeline1.save() else: st = pipelineenquirylog.objects.filter(email_id=instance.email_id).count() print(cnt, st) if st == 1: print(inside) pipelineenquirylog.objects.filter(email_id=instance.email_id).update(is_pipeline='0') enquirylog.objects.filter(email_id=instance.email_id).update(enquirylog_pipeline='False') else: print(no_sub) # NTY USE CASE elif instance.ef_underwriter_decision == configur.get('decisions', 'no_thankyou'): dict_obj = temp_dict() submission.objects.filter(email_id=instance.email_id).update(email_status='active') submission.objects.filter(email_id=instance.email_id).update( email_uwriter_decision=instance.ef_underwriter_decision) submission.objects.filter(email_id=instance.email_id).update( email_today_mail=configur.get('mailstatus', 'nty_mail_type')) instance.email_today_mail = configur.get('mailstatus', 'nty_mail_type') # CR7.1 submission.objects.filter(email_id=instance.email_id).update( email_deleted=configur.get('mailstatus', 'set_status_as_completed')) temp_email_table = submission.objects.filter(email_id=instance.email_id).values( 'email_id', 'enquiry_id', 'email_subject', 'email_broker', 'email_outlook_date', 'email_today_mail', 'email_assigned_user' ) for today in temp_email_table: for t in today: dict_obj.add(t, today[t]) if len(validated_data.get('ef_insured_name', instance.ef_insured_name)['name']) == 0: dict_obj.add('ef_insured_name', not_avbl) else: dict_obj.add('ef_insured_name', validated_data.get('ef_insured_name', instance.ef_insured_name)['name']) if len(validated_data.get('ef_obligor_name', instance.ef_obligor_name)['name']) == 0: dict_obj.add('ef_obligor_name', not_avbl) else: dict_obj.add('ef_obligor_name', validated_data.get('ef_obligor_name', instance.ef_obligor_name)['name']) if len(validated_data.get('ef_obligor_name', instance.ef_obligor_name)['country']) == 0: dict_obj.add('el_country_name', not_avbl) else: dict_obj.add('el_country_name', validated_data.get('ef_obligor_name', instance.ef_obligor_name)['country']) dict_obj.add('enquirylog_limit', validated_data.get('ef_financials', instance.ef_financials) ['limit']) dict_obj.add('ef_underwriter_decision', validated_data.get('ef_underwriter_decision', instance.ef_underwriter_decision)) dict_obj.add('ef_underwriter_decision', validated_data.get('ef_underwriter_decision', instance.ef_underwriter_decision)) dict_obj.add('ef_decision_nty_fields', validated_data.get('ef_decision_nty_fields', instance.ef_decision_nty_fields)) dict_obj.add('ef_feedback', validated_data.get('ef_feedback', instance.ef_feedback)) dict_obj.add('relation_id', validated_data.get('relation_id', instance.relation_id)) dict_obj.add('enquirylog_status', 'closed') dict_obj.add('broker_email_id', validated_data.get('broker_email_id', instance.broker_email_id)) dict_obj.add('enquirylog_pipeline', validated_data.get('ef_pipeline', instance.ef_pipeline)) dict_obj.add('coverage', validated_data.get('ef_coverage', instance.ef_coverage)['coverage']) dict_obj.add('tenor', validated_data.get('ef_coverage', instance.ef_coverage)['tenor']) enquiry = enquirylog(email_id=dict_obj['email_id'], enquiry_id=dict_obj['enquiry_id'], coverage=dict_obj['coverage'], tenor=dict_obj['tenor'], email_subject=dict_obj['email_subject'], relation_id=dict_obj['relation_id'], email_broker=dict_obj['email_broker'], email_outlook_date=dict_obj['email_outlook_date'], enquirylog_limit=dict_obj['enquirylog_limit'], email_assigned_user=dict_obj['email_assigned_user'], email_today_mail=dict_obj['email_today_mail'], ef_insured_name=dict_obj['ef_insured_name'], ef_obligor_name=dict_obj['ef_obligor_name'], el_country_name=dict_obj['el_country_name'], ef_underwriter_decision=dict_obj['ef_underwriter_decision'], ef_decision_nty_fields=dict_obj['ef_decision_nty_fields'], ef_feedback=dict_obj['ef_feedback'], enquirylog_status=dict_obj['enquirylog_status'], enquirylog_pipeline=dict_obj['enquirylog_pipeline'], broker_email_id=dict_obj['broker_email_id'] ) enquiry.save() st = pipelineenquirylog.objects.filter(email_id=instance.email_id).count() print(cnt, st) if st == 1: print(inside) pipelineenquirylog.objects.filter(email_id=instance.email_id).update(is_pipeline='0') enquirylog.objects.filter(email_id=instance.email_id).update(enquirylog_pipeline='False') else: print(no_sub) # BOUND USE CASE if instance.ef_underwriter_decision == configur.get('decisions', 'bound_decision'): # enquiry Log dict_obj = temp_dict() # Update Submission table based on underwriter decision submission.objects.filter(email_id=instance.email_id).update(email_status='active') submission.objects.filter(email_id=instance.email_id).update( email_deleted=configur.get('mailstatus', 'set_status_as_delete')) submission.objects.filter(email_id=instance.email_id).update( email_uwriter_decision=instance.ef_underwriter_decision) submission.objects.filter(email_id=instance.email_id).update( email_today_mail=configur.get('mailstatus', 'bound_mail_type')) # CR7.1 submission.objects.filter(email_id=instance.email_id).update( email_deleted=configur.get('mailstatus', 'set_status_as_completed')) temp_email_table = submission.objects.filter(email_id=instance.email_id).values( 'email_id', 'enquiry_id', 'email_sender', 'email_subject', 'email_broker', 'email_outlook_date', 'email_today_mail', 'email_assigned_user') for today in temp_email_table: for t in today: dict_obj.add(t, today[t]) if len(validated_data.get('ef_insured_name', instance.ef_insured_name)['name']) == 0: dict_obj.add('ef_insured_name', not_avbl) else: dict_obj.add('ef_insured_name', validated_data.get('ef_insured_name', instance.ef_insured_name)['name']) if len(validated_data.get('ef_obligor_name', instance.ef_obligor_name)['name']) == 0: dict_obj.add('ef_obligor_name', not_avbl) else: dict_obj.add('ef_obligor_name', validated_data.get('ef_obligor_name', instance.ef_obligor_name)['name']) if len(validated_data.get('ef_obligor_name', instance.ef_obligor_name)['country']) == 0: dict_obj.add('el_country_name', not_avbl) else: dict_obj.add('el_country_name', validated_data.get('ef_obligor_name', instance.ef_obligor_name)['country']) dict_obj.add('enquirylog_limit', validated_data.get('ef_financials', instance.ef_financials) ['limit']) dict_obj.add('ef_underwriter_decision', validated_data.get('ef_underwriter_decision', instance.ef_underwriter_decision)) dict_obj.add('ef_decision_nty_fields', validated_data.get('ef_decision_nty_fields', instance.ef_decision_nty_fields)) dict_obj.add('ef_feedback', validated_data.get('ef_feedback', instance.ef_feedback)) dict_obj.add('relation_id', validated_data.get('relation_id', instance.relation_id)) dict_obj.add('enquirylog_status', 'bound') dict_obj.add('enquirylog_pipeline', validated_data.get('ef_pipeline', instance.ef_pipeline)) dict_obj.add('broker_email_id', validated_data.get('broker_email_id', instance.broker_email_id)) dict_obj.add('coverage', validated_data.get('ef_coverage', instance.ef_coverage)['coverage']) dict_obj.add('tenor', validated_data.get('ef_coverage', instance.ef_coverage)['tenor']) enquiry = enquirylog(email_id=dict_obj['email_id'], enquiry_id=dict_obj['enquiry_id'], coverage=dict_obj['coverage'], tenor=dict_obj['tenor'], email_subject=dict_obj['email_subject'], relation_id=dict_obj['relation_id'], email_broker=dict_obj['email_broker'], email_outlook_date=dict_obj['email_outlook_date'], enquirylog_limit=dict_obj['enquirylog_limit'], email_assigned_user=dict_obj['email_assigned_user'], email_today_mail=dict_obj['email_today_mail'], ef_insured_name=dict_obj['ef_insured_name'], ef_obligor_name=dict_obj['ef_obligor_name'], el_country_name=dict_obj['el_country_name'], ef_underwriter_decision=dict_obj['ef_underwriter_decision'], ef_decision_nty_fields=dict_obj['ef_decision_nty_fields'], ef_feedback=dict_obj['ef_feedback'], enquirylog_status=dict_obj['enquirylog_status'], enquirylog_pipeline=dict_obj['enquirylog_pipeline'], broker_email_id=dict_obj['broker_email_id'] ) enquiry.save() instance.save() return instance </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T07:04:40.323", "Id": "515672", "Score": "4", "body": "Hey Sherlock/user242906. Since you seem to have a registered and unregistered account; you can contact support, through the [contact](https://codereview.stackexchange.com/contact) form, to ask to merge your two accounts into one. Doing so will mean your edits won't need to get approval and you'll get notifications from users who interact with your post. To fill in the form; select \"I need to merge user profiles\" and for \"your other profile link\" provide the link https://codereview.stackexchange.com/users/242906/user242906" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T07:27:26.747", "Id": "261268", "Score": "0", "Tags": [ "python", "object-oriented", "database", "django" ], "Title": "Extract fields from email and store into a Django database" }
261268
<p>An Object-relational mapper built using php.</p> <p><strong>This was done for educational purposes, and curious to know what kind of improvement has to be done to use in production.</strong></p> <h6>Please refer to the complete source code in the Github repository - (<a href="https://github.com/maleeshagimshan98/infinite-simple-orm" rel="nofollow noreferrer">https://github.com/maleeshagimshan98/infinite-simple-orm</a>)</h6> <p>Below, I've described the internal workings...</p> <ul> <li><p><em>Entity Manager Class</em></p> <ul> <li><p>This is the main instance we are interacting with.</p> </li> <li><p>Use it to retrieve and Create/Update data</p> </li> <li><p>It uses Entity objects and their attributes to build the query and execute the query.</p> </li> <li><p>Handles associations with other Entities using entity attributes (<code> $Entity-&gt;associations-&gt;get()</code>)</p> </li> </ul> </li> <li><p><em>Entity Class</em></p> <ul> <li><p>Represent an entity in the database.</p> </li> <li><p>Has attributes of entity and column mappings to attributes for respective table</p> </li> <li><p>Has associations info that Entity has.</p> </li> </ul> </li> <li><p>Entity class structure is here,</p> <ul> <li><strong>Entity class</strong> <ul> <li><em>attributes</em> are managed using <code>AttributeContainer</code> class.</li> <li><em>associations</em> are managed using <code>AssociatedEntityContainer</code> class.</li> <li><em>attribs_map</em> - attribute to column mapping, managed by <code>AttributeMapContainer</code> class</li> </ul> </li> </ul> </li> </ul> <h4>AttributeContainer Class</h4> <pre><code>&lt;?php /** * © Maleesha Gimshan - 2021 - github.com/maleeshagimshan98 * * Entity's Attribute Container Class */ namespace Infinite\DataMapper\Entity; /** * Attribute container */ class AttributeContainer { /** * entity attributes * * @var array */ protected $attribs = []; /** * entity property names * * @var array */ protected $props = []; /** * constructor */ public function __construct () { } /** * get a single attribute * * @param string $attrib * @return string attribute * @throws \Exception */ protected function attribute ($attrib = null) { if (empty($attrib)) { return $this-&gt;attribs; } if (!isset($this-&gt;attribs[$attrib])) { throw new \Exception(&quot;Undefined_Attribute&quot;); } return $this-&gt;attribs[$attrib]; } /** * get entity's attributes * * @param mixed $attribute * @return string|array * @throws \Exception */ public function get ($attribute = null) { try { if (is_array($attribute)) { $arr = []; foreach ($attribute as $key) { $arr[] = $this-&gt;attribute($key); } return $arr; } return $this-&gt;attribute($attribute); } catch (\Exception $e) { if ($e-&gt;getMessage() == &quot;Undefined_Attribute&quot; ) { return $this-&gt;attribute(); } } } /** * get entity's properties * properties = $this-&gt;attribs[$name] - this $name is a property * * @return void */ public function getAttribKeys ($prop = null) { if (isset($prop)) { if (!isset($this-&gt;props[$prop])) { throw new \Exception(&quot;Undefined_Prop&quot;); } return $this-&gt;props[$prop]; } return $this-&gt;props; } /** * set entity's attribute * * @param string $name * @param array|object $attrib * @return void */ public function set ($name,$attrib) { $this-&gt;props[] = $name; $this-&gt;attribs[$name] = $attrib; } } ?&gt; </code></pre> <h4>AttributeMapContainer Class</h4> <pre><code>&lt;?php /** * © Maleesha Gimshan - 2021 - github.com/maleeshagimshan98 * * Entity's Attribute Container Class */ namespace Infinite\DataMapper\Entity; /** * Attribute Map Container */ class AttributeMapContainer { /** * entity attributes * * @var array */ protected $attrib_map = []; /** * constructor */ public function __construct () { } /** * get a single attribute_map element * * @param string $attrib attrib_map element name * @return string attribute_map element * @throws \Exception */ protected function map ($attrib = null) { if (!isset($this-&gt;attrib_map[$attrib])) { throw new \Exception(&quot;Undefined_Attribute&quot;); } return $this-&gt;attrib_map[$attrib]; } /** * get entity's attributes * * @param mixed $attribute * @return string|array * @throws \Exception */ public function get ($attribute = null) { if (empty($attribute)) { $arr = []; foreach ($this-&gt;attrib_map as $key) { $arr[] = $key; } return $arr; } if (is_array($attribute)) { $arr = []; foreach ($attribute as $key) { $arr[] = $this-&gt;map($key); } return $arr; } return $this-&gt;map($attribute); /** if $attribute === String */ } public function set ($name,$attrib) { $this-&gt;attrib_map[$name] = $attrib; } } ?&gt; </code></pre> <h3>AssociatedEntityContainer Class</h3> <pre><code>&lt;?php /** * © Maleesha Gimshan - 2021 - github.com/maleeshagimshan98 * * Associated Entity Container Class */ namespace Infinite\DataMapper\Entity; /** * Associated entity container */ class AssociatedEntityContainer { /** * entity association data * * @var array */ protected $associations = []; protected $associationKeys = []; /** * currently associated entities on this entity * * @var array */ protected $currentAssociated = []; /** * constructor */ public function __construct () { } /** * get an association * * @param string $association * @return string * @throws \Exception */ public function get ($association = null) { if (empty($association)) { return $this-&gt;associations; } if (!isset($this-&gt;associations[$association])) { throw new \Exception(&quot;Undefined_Association&quot;); } return $this-&gt;associations[$association]; } /** * get associations key names * * @return array */ public function getAssociationKeys () { return $this-&gt;associationKeys; } /** * set an association * * @param object $data * @return void * @throws \Exception */ public function set ($data) { foreach ($data as $key =&gt; $value) { $this-&gt;associationKeys[] = $key; if (empty($value-&gt;target)) { throw new \Exception(&quot;Target_Entity_Undefined&quot;); return; //IMPORTANT CHECK WHAT HAPPENS IN CASE OF ERROR } $this-&gt;associations[$key] = $value; } } } ?&gt; </code></pre> <h3>Entity Class</h3> <pre><code>&lt;?php /** * © Maleesha Gimshan - 2021 - github.com/maleeshagimshan98 * * base class for defining entities * in the database */ namespace Infinite\DataMapper; use Infinite\DataMapper\Entity\AttributeContainer; use Infinite\DataMapper\Entity\AttributeMapContainer; use Infinite\DataMapper\Entity\AssociatedEntityContainer; use Infinite\DataMapper\Entity\EntityResult; /** * Entity class * represents an entity */ class Entity { protected $qb; /** * entity name * * @var string */ public $entityName; /** * entity's attributes * * @var Infinite\DataMapper\Entity\AttributeContainer */ public $attribs; /** * attributes mapped to column names - table_name.column_name * * @var array */ public $attribs_map; /** * entity's property names * * @var Infinite\DataMapper\Entity\EntityResult object */ protected $entityResult; /** * entity table's name * * @var string */ protected $entity_table = &quot;&quot;; /** * entity associations with other entities * * @var Infinite\DataMapper\Entity\AssociatedEntityContainer */ public $associations; /** * entity's data limit - for pagination * * @var integer */ protected $limit = 10; /** * constructor * * @param string $name database table name of the entity * @param array|object $attribs * @return void * @throws \Exceptions */ public function __construct ($attribs,$name) { if (!$attribs) { throw new \Exception(&quot;Invalid_Entity_Definition&quot;); } $this-&gt;attribs = new AttributeContainer(); $this-&gt;attribs_map = new AttributeMapContainer($name); $this-&gt;associations = new AssociatedEntityContainer(); $this-&gt;entity_table = $name; $this-&gt;init($attribs,$name); } /** * get entity table * * @return string */ public function table () : string { return $this-&gt;entityTable; } /** * get entity's name * * @return string */ public function name () { return $this-&gt;entityName; } /** * get primary key * * @return string|array */ public function primary () { return $this-&gt;primary; } /** * set primary key * * @param object $attrib * @return void */ public function setPrimaryKey ($attrib,$name) { if (isset($attrib-&gt;primary) &amp;&amp; $attrib-&gt;primary) { $this-&gt;primary[] = $attrib-&gt;name ?? $name ; } } //.... /** * map entity attributes from configuration * * @param object $attribs entity attributes * @param string $name entity table name * @return Infinite\DataMapper\Entity\AttributeContainer attribute container */ protected function init ($attribs,$name) : AttributeContainer { /* TESTING */ //echo \json_encode($attribs); $keys = []; foreach ($attribs as $key =&gt; $value) { if ($this-&gt;entity_table == &quot;&quot;) { $this-&gt;entity_table = $name; } $this-&gt;setAttribute($key,$value); $this-&gt;setPrimaryKey($key,$value); if ($key === &quot;_assoc&quot;) { $this-&gt;associations-&gt;set($value); } } $this-&gt;initEntityResult(); return $this-&gt;attribs; } /** * initialize EntityResult object * * @return void */ protected function initEntityResult () { $keys = $this-&gt;attribs-&gt;getAttribKeys(); $keys = array_merge($keys,$this-&gt;associations-&gt;getAssociationKeys()); $this-&gt;entityResult = new EntityResult($keys,$this-&gt;entityName); } /** * get entity result object * * @return Infinite\DataMapper\Entity\EntityResult object */ public function getEntityResult () { return $this-&gt;entityResult; } /** * set entity's attributes * * @param string $name * @param string|object $attrib * @return void */ protected function setAttribute ($name,$attrib) {//echo \json_encode($attrib); $attributeName = $this-&gt;parseAttributeName($name,$attrib); if ($attributeName) { //setting the attribute mapping to columns $this-&gt;attribs_map-&gt;set($name,$attributeName); $this-&gt;attribs-&gt;set($name,$attrib); } } /** * sets the attribute's name with respect of configuration options * * @param string $attribName attribute name entity * @param string|object $attrib attribute options (if any), or (similar as $attribName) * @return string */ protected function parseAttributeName ($attribName,$attrib) { if (\is_object($attrib)) { if (!empty($attrib-&gt;name)) { $attribute = $attrib-&gt;name; } elseif (!empty($attrib-&gt;primary)) { //attribs with primary key, but no name comes here $attribute = $attribName; } else { return false; //TODO - CHECK -- associations comes here } } elseif (is_string($attrib)) { $attribute = $attrib; } return $attribute; } /** * format column names with table name * * @param string|array $columns * @return mixed */ protected function withTable ($columns) { if (is_string($columns)) { return $this-&gt;entityTable.&quot;.&quot;.$columns; } if (is_array($columns)) { $formattedColumns = []; foreach ($columns as $key) { $formattedColumns[] = $this-&gt;entityTable.&quot;.&quot;.$key; } return $formattedColumns; } } /** * get entity attributes' column names (any or all) * * @param string|array $attributeName * @return string|array */ public function mapAttribsToColumn ($attributeName = null) { if (\is_null($attributeName)) { return $this-&gt;withTable($this-&gt;attribs_map-&gt;get($attributeName)); } $attribs = $this-&gt;attribs-&gt;get($attributeName); if (is_array($attribs)) { $columns = []; foreach ($attribs as $key =&gt; $val) { $columns[] = $this-&gt;withTable($this-&gt;attribs_map-&gt;get($val)); } return $columns; } return $this-&gt;withTable($this-&gt;attribs_map-&gt;get($attributeName)); } /** * hydrate entity with the data fetched from database * * @param array|object $data fetched data from database * @return self */ public function hydrate ($data) { $data = (object) $data; $arr = []; $attribs = $this-&gt;attribs-&gt;get(); foreach ($attribs as $key =&gt; $value) { $attributeName = $this-&gt;parseAttributeName($key,$value); $arr[$key] = $data-&gt;$attributeName; } return new EntityResult($arr,$this-&gt;entityName); //always return a new instance } /** * process entity result object for insertion, based on entity's atrributes * (only entity owned attributes) * * @param [type] $data * @return void */ public function insertProps ($data) { $arr = []; $attribs = $this-&gt;attribs-&gt;getAttribKeys(); foreach ($attribs as $key) { $arr[] = $data[$key]; } return $arr; } } ?&gt; </code></pre> <h2>Entity Manager</h2> <ul> <li>Entity Manager class structure <ul> <li><code>EntityContainer</code> class - containing all entities.</li> <li><code>queryDb</code> class - for querying database.</li> <li><code>QueryBuilderWrapper</code> class - wrapping <code>Enmvs\FluentPdo\Query</code> query bulder class.</li> </ul> </li> </ul> <h3>EntityContainer Class</h3> <pre><code>&lt;?php /** * © Maleesha Gimshan - 2021 - github.com/maleeshagimshan98 * * Entity Container Class */ namespace Infinite\DataMapper; /** * Entity container */ class EntityContainer { /** * full qualified class name for the entity * * @var string */ protected $base_class_name = &quot;\Infinite\DataMapper\Entity\\&quot;; /** * database schema * * @var object */ protected $dbSchema; /** * entities - [...,\Infinite\DataMapper\Entity\ENTITY_CLASS_NAME] * * @var array */ protected $entities = []; /** * constructor */ public function __construct ($entityDefinition = null) { if(!empty($entityDefinition)) { $this-&gt;parseEntityDefinition($entityDefinition); } } //... /** * create an entity on the go * * @param string $name entity name * @return \Infinite\DataMapper\Entity entity object */ public function entity ($name) { $entityDef = $this-&gt;getDefinition($name); if (!$entityDef) { throw new \Exception(&quot;Undefined_Entity&quot;); } $entityClass = $this-&gt;base_class_name.&quot;$name&quot;; return $this-&gt;entities[$name] = new $entityClass($entityDef,$name); } /** * parse database entity definition * * @param [type] $schema JSON object defining the db schema * @return void */ protected function parseEntityDefinition ($schema) { $arr = []; foreach ($schema as $key =&gt; $val) { $arr[$key] = $val; } $this-&gt;dbSchema = (object) $arr; } /** * get entity definitions * * @param string $name * @return mixed */ protected function getDefinition ($name) { //echo json_encode($name); return $this-&gt;dbSchema-&gt;$name ?? false; } /** * checks if current entities count is zero * * @return boolean */ public function is_empty () { return count($this-&gt;entities) == 0; } /** * Get an entity * * @param string $entity Entity name * @return \Infinite\DataMapper\Entity object * @throws \Exception */ public function get ($entity) { if (empty($this-&gt;entities[$entity])) { return $this-&gt;entity($entity); //throw new \Exception(&quot;Undefined_Entity&quot;); } return $this-&gt;entities[$entity]; } /** * get all entities * * @return array */ public function getAll () { return $this-&gt;entities; } /** * set entity * * @param string $name * @param Infinite\DataMapper\Entity $entity entity object * @return void */ public function set ($name,$entity) { $this-&gt;entities[$name] = $entity; } } ?&gt; </code></pre> <p><strong>For the context of this question other <code>queryDb</code>, <code>QueryBuilderWrapper</code> classes are not relevant, thus not shown here.</strong></p> <h3>Entity Manager class</h3> <pre><code>&lt;?php /** * © Maleesha Gimshan - 2021 - github.com/maleeshagimshan98 * * Entity Manager class */ namespace Infinite\DataMapper; include_once dirname(__DIR__).&quot;/vendor/autoload.php&quot;; // Entity classes extended from Entity base class include_once dirname(__DIR__).&quot;/Products.php&quot;; include_once dirname(__DIR__).&quot;/sku.php&quot;; include_once dirname(__DIR__).&quot;/product_sku.php&quot;; include_once dirname(__DIR__).&quot;/orders.php&quot;; use Infinite\DataMapper\EntityContainer; use Infinite\DataMapper\QueryBuilder\QueryBuilderWrapper; use Infinite\DataMapper\QueryDb; use Infinite\DataMapper\Pagination; /** * Entity manager class */ class EntityManager { /** * PDOConnection * * @var \PDO object */ private $connection; /** * Entities * * @var Infinite\DataMapper\EntityContainer * */ public $entities; /** * current entity * * @var Infinite\DataMapper\Entity */ protected $currentEntity; /** * current associated entities * * @var Infinite\DataMapper\EntityContainer */ protected $currentAssociated; /** * sql statement created when querying entities * * @var \PDOStatement */ protected $sqlStatement; /** * sql statements created when inserting data * have multiple sql statements * execute all in one transaction * * @var array */ protected $sqlStatementStack = []; /** * CRUD action - select,insert,update,delete * * @var string */ protected $action = &quot;&quot;; /** * constructor * * @param object $config * @return void */ public function __construct (object $config) { $this-&gt;initConfig($config); } /** * initialize Entity manager with configuration * * @param object $config configuration object * @return void * @throws \Exception */ protected function initConfig (object $config) { if (empty($config-&gt;connection)) { throw new \Exception(&quot;Database_Connection_Not_Found&quot;); } $this-&gt;connection = $config-&gt;connection; //CONSIDER REMOVING THIS PROPERTY $this-&gt;entities = new EntityContainer(json_decode(file_get_contents(dirname(__DIR__).&quot;/config/entity_definition.json&quot;))); $this-&gt;currentAssociated = new EntityContainer(); $this-&gt;queryBuilder = new QueryBuilderWrapper($this-&gt;connection); $this-&gt;queryDb = new QueryDb($this-&gt;connection); } /** * return a new entity result object of a respective entity class - when inserting new data * * @param string $entity entity name * @return Infinite\DataMapper\Entity\EntityResult Entity result object * @throws \Exception */ public function entity (string $entityName) { return $this-&gt;entities-&gt;entity($entityName)-&gt;getEntityResult(); } /** * set current entity * * @param string $entity * @return void */ protected function setCurrentEntity ($entity) { $this-&gt;currentEntity = $this-&gt;entities-&gt;get($entity); } /** * prepare basic parts of query string * for getting an entity from database * * @param \Infinite\DataMapper\Entity\ $entity entity object * @return void */ protected function prepareGet ($entity) { /* TESING */ //echo \json_encode($entity); $this-&gt;sqlStatement = $this-&gt;queryBuilder-&gt;from($entity-&gt;table()) -&gt;select($entity-&gt;mapAttribsToColumn()); return $this-&gt;sqlStatement; } /** * get entity from database * * @param string $entity entity name * @param array|null $id get a row based on id [column_name,value] * @return self * @throws \Exception */ public function get ($entity,$id = null) { $this-&gt;action = &quot;select&quot;; $this-&gt;setCurrentEntity($entity); //echo json_encode($this-&gt;currentEntity); $sql = $this-&gt;prepareGet($this-&gt;currentEntity); if (!empty($id)) { $sql = $sql-&gt;where([ $this-&gt;currentEntity-&gt;mapAttribsToColumn($id[0]) =&gt; $id[1] ]); } return $this; /** TESTING */ //echo json_encode(); } /** * associate entities in the result * * @param string $entity associated entity name * @param mixed $joiningEntityId entity id (or foreign key) of associated entity * @return self * @throws \Exception */ public function associate ($entity,$joiningEntityId = null) { $associated = $this-&gt;currentEntity-&gt;associations-&gt;get($entity); $target = $this-&gt;entities-&gt;get($associated-&gt;target); $this-&gt;currentAssociated-&gt;set($associated-&gt;target,$target); //IMPORTANT - CHECK IF THIS IS NEEDED - $target $this-&gt;sqlStatement = $this-&gt;sqlStatement-&gt;leftJoin([ $target-&gt;mapAttribsToColumn($associated-&gt;refer), $this-&gt;currentEntity-&gt;mapAttribsToColumn($associated-&gt;inverse) ])-&gt;select($target-&gt;mapAttribsToColumn()); if (is_array($joiningEntityId)) { $this-&gt;sqlStatement = $this-&gt;sqlStatement-&gt;where( [ $target-&gt;mapAttribsToColumn($joiningEntityId[0]) =&gt; $joiningEntityId[1] ] ); } return $this; } /** * hydrate entity with data fetched from database * * @param array|object $res data fetched from database * @return void */ protected function hydrate ($res) { $currentEntityName = $this-&gt;currentEntity-&gt;name(); $entityCollection = []; foreach ($res as $key) { $result = $this-&gt;entities-&gt;entity($currentEntityName)-&gt;hydrate($key); if (!$this-&gt;currentAssociated-&gt;is_empty()) { $result = $this-&gt;hydrateAssociated($result,$key); } $entityCollection[] = $result; } //echo json_encode($entityCollection); return $entityCollection; } /** * hydrate associated entity of the current entity * (only single object from result set, * run this multiple times to hydrate all entities, and associated ones) * * @param Infinite\DataMapper\Entity $entity entiy object * @param array|object $data data fetched from database * @return Infinite\DataMapper\Entity */ protected function hydrateAssociated ($entity,$data) { foreach ($this-&gt;currentAssociated-&gt;getAll() as $key =&gt; $value) { $entity-&gt;set($key,$this-&gt;entities-&gt;entity($key)-&gt;hydrate($data)); } return $entity; } /** * execute the current CRUD Action statement * * @return void */ public function go ($data = null) { if ($this-&gt;action === 'select') { $res = $this-&gt;queryDb-&gt;select((object) [ &quot;sql&quot; =&gt; $this-&gt;sqlStatement-&gt;getSqlString(), &quot;data&quot; =&gt; $data ]); /* TESTING */// echo $sql; /* TESTING */ //echo json_encode($res); return $this-&gt;hydrate($res); //return $this-&gt;result($res); } if ($this-&gt;action === &quot;insert&quot;) { $isDone = true; //CHECK foreach ($this-&gt;sqlStatementStack as $sql) { $this-&gt;queryDb-&gt;transaction(); $isDone = $this-&gt;queryDb-&gt;insert((object)[ &quot;sql&quot; =&gt; $sql[0], &quot;data&quot; =&gt; $sql[1] ]); } if ($isDone) { $this-&gt;queryDb-&gt;commit(); } else { $this-&gt;queryDb-&gt;rollback(); } } } /** * save an entity to database * * @param EntityResult $entity entity object * @param array $values associated array of values - [&quot;column_1&quot; =&gt; &quot;value&quot;, &quot;column_2&quot; =&gt; &quot;value&quot;] * @return void */ public function save ($entity,$values) { $this-&gt;action = &quot;insert&quot;; $this-&gt;setCurrentEntity($entity-&gt;name()); $entity-&gt;setFromArray($values); $sqlStatement[] = $this-&gt;queryBuilder-&gt;insert( $this-&gt;currentEntity-&gt;table(), $this-&gt;currentEntity-&gt;attribs_map-&gt;get(), $this-&gt;currentEntity-&gt;insertProps($values) )-&gt;getSqlString(); $sqlStatement[] = $this-&gt;currentEntity-&gt;insertProps($values); $this-&gt;sqlStatementStack[] = $sqlStatement; //ONLY MAIN ENTITY IS BEIGN INSERTED } /** * execute raw sql statements directly * instead of using this ORM * * @param string $sql sql query string * @param object $data data to be bound on the prepared query string * @return mixed */ public function rawSql ($sql,$data) { } } ?&gt; </code></pre> <p><strong>Reasons for posting this question and what I'm looking for</strong></p> <ul> <li>Any improvements in the in-memory representation of <strong>relationships, entity attributes. (data structure)</strong></li> <li>Mostly I'm bothered about using foreach loops in most places.</li> <li>Any improvement for the code and for the code structure is welcome.</li> <li>What kind of improvements to be done to use in production?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T08:46:36.657", "Id": "518298", "Score": "0", "body": "The `composer install` or update is triggering error\n`\n[RuntimeException] \n Could not scan for classes inside \"EntityManager/\" which does not appear to \n be a file nor a folder \n`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T09:25:42.210", "Id": "518301", "Score": "0", "body": "@jona303 I can't figure out what the exact reason is, But a (dumb) quickfix would be remove those class map declarations and use composer install, then add them and use composer dumpautoload" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T13:30:27.423", "Id": "518320", "Score": "1", "body": "Please do not edit the question, especially the code after the question has been answered. You can ask a new question and link to the old one if they are related. Please read [What do I do when someone answers](https://codereview.stackexchange.com/help/someone-answers)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:02:19.217", "Id": "518324", "Score": "0", "body": "@pacmaninbw Sorry, I just read your comment after reverting back to my last revision... I will rollback to original question, post a new question and link to this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T21:55:47.847", "Id": "518415", "Score": "1", "body": "Also, please do not include focus points (in how you'd like the code to be reviewed) in your title. You title should only describe what your code does." } ]
[ { "body": "<p>It's not related to your four questions but the most important thing for me is that your library is not (yet) an ORM from my point of view.\nAn ORM is supposed to map Object and it's properties to a table and it's column.\nIf I understand your github documentation there is not model object mapped to the database. It's more like an ORM configuration but without the mapping to the final object.</p>\n<pre><code>$product = $entityManager-&gt;entity(&quot;product&quot;);\n\n// inserting values\n$props = [&quot;id&quot; =&gt; &quot;llmp_010&quot;, &quot;product_name&quot; =&gt; &quot;test_product&quot;, &quot;img_url&quot; =&gt; &quot;some_url&quot;];\n\n$entityManager-&gt;save($product,$props);\n</code></pre>\n<p>I see an array of properties, not an object with (encpsulated) properties that you can constraint.</p>\n<p>The same apply here</p>\n<pre><code>// get data by a key\n\n$data = $EntityManager-&gt;get('entity_name',['entity_attrib','some_value'])-&gt;go('some_value');\n</code></pre>\n<p>What am I supposed to get from the <code>go</code> method ?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T17:51:45.940", "Id": "516245", "Score": "0", "body": "Thank you for the answer, Yes, there have been few issues, and at the moment, I've updated my code to the latest on Github.. now EntityManager gets data from the EntityResult's (The object which contains all properties of entity) properties itself., You have to invoke ````go```` to actually execute the queries and get results, also when inserting, all are done in single transaction. (inspired by doctrine ORM)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T18:05:58.447", "Id": "516246", "Score": "0", "body": "For the last part of your answer, that is to get an entity by a key (eg - primary key), and you have to pass the key to ````go()```` method too, currently. I think you made a good point, that passing args to go is unnecessary and does not make sense. I will change that (in ````get```` too) for sure, in the next commit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T18:54:31.143", "Id": "516250", "Score": "0", "body": "That's not the point I was spotting. The `go` method will return me an Object `EntityResult` that contains a property named `props` that contains the data from the DB. That's not what an ORM is supposed to do. Let's suppose we have a `Product` entity with a `price` property. The ORM is supposed to return an Instance of `Product` that has at least a public property `price` or better an encapsulated private property `price` with a getter and setter method. The advantages of the OOP are totally lost." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T08:29:40.483", "Id": "518296", "Score": "0", "body": "````EntityResult```` is, something like a general container, which adds and hydrates those entity properties to EntityResult (based on the entity retrieved), (for example, product) and you can get and set them, and also currently these properties are public. That ````props```` property in EntityResult is for internal use only (it shoud be protected property, if my memory correct), not supposed to use by a user.. Please see update code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T19:15:57.093", "Id": "518570", "Score": "0", "body": "posted a new question in [here](https://codereview.stackexchange.com/q/262623/218131) because I've made changes to the code" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T15:26:38.313", "Id": "261584", "ParentId": "261272", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T08:19:32.730", "Id": "261272", "Score": "2", "Tags": [ "php", "database", "library", "orm" ], "Title": "Object relational mapper - optimize in memory data representation and code improvements" }
261272
<p>Link: <a href="https://leetcode.com/problems/reverse-nodes-in-k-group/" rel="nofollow noreferrer">https://leetcode.com/problems/reverse-nodes-in-k-group/</a></p> <p>Problem description:</p> <blockquote> <p>Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.</p> <p>k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.</p> <p>You may not alter the values in the list's nodes, only nodes themselves may be changed.</p> <p>e.g. Input: head = [1,2,3,4,5], k = 3 Output: [3,2,1,4,5]</p> </blockquote> <p>My solution:</p> <pre><code>/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode** subHead = &amp;head; int i = 0; for (ListNode* subTail = head; subTail != NULL; subTail = subTail-&gt;next) { if ((i+1) % k == 0) { ListNode* temp = subTail-&gt;next; reverse(subHead, &amp;subTail); subTail-&gt;next = temp; subHead = &amp;(subTail-&gt;next); } i++; } return head; } void reverse(ListNode** subHead, ListNode** subTail) { if (*subHead==NULL) return; ListNode* itHead = *subHead; ListNode* prev = NULL; ListNode* next = NULL; ListNode* end = (*subTail)-&gt;next; while (itHead != end) { next = itHead-&gt;next; itHead-&gt;next = prev; prev = itHead; itHead = next; } std::swap(*subHead, *subTail); } }; </code></pre> <p>This solution was accepted and seemed to do quite well in both space and time. I'm interested in how it can be optimized further, how it can be made more readable, more elegant, or better express good design principles. Note that the data definition and the signature <code>ListNode* reverseKGroup(ListNode* head, int k)</code> is enforced by the question. Feel free to comment on anything you'd like though.</p>
[]
[ { "body": "<p>Don't use the macro <code>NULL</code>. Use the specific keyword <code>nullptr</code> now.</p>\n<p>Your struct can be more simply written using immediate inline initializers.</p>\n<pre><code>struct ListNode {\n int val = 0;\n ListNode* next = nullptr;\n ListNode() = default;\n ListNode(int x) : val{x} {}\n ListNode(int x, ListNode* next) : val{x}, next{next} {}\n};\n \n</code></pre>\n<p>Also note that the <code>*</code> goes with the <em>type</em> in C++, not with the name being declared.</p>\n<p>Regarding<br />\n<code>void reverse(ListNode** subHead, ListNode** subTail)</code><br />\nIt appears that the names <code>subHead</code> and <code>subTail</code> are never modified by the code, so this would be easier if you passed <strong>references</strong> to the pointers, rather than having an extra explicit dereference operation when you use it.</p>\n<pre><code>ListNode* itHead = *subHead;\n//...\nwhile (itHead != end) {\n //...\n itHead = next;\n}\n</code></pre>\n<p>This is just a <code>for</code> loop that's spread out for no reason. The value of <code>next</code> you want is lost during the body of the loop, so I can see why you don't put that inside a <code>for</code> construct. But you can put the declaration of <code>subHead</code> there... put the parts you <em>can</em> into a <code>for</code> loop, even if it's not all three of them.</p>\n<p>Re:<br />\n<code>if (*subHead==NULL) return;</code><br />\nDon't make explicit comparisons against null. Use the truth predicates that are part of the (possibly smart!) pointer.</p>\n<p>Combining this with the tip of using references (...<code>ListNode*&amp; subHead,</code>) you get simply: <code>if (!subHead) return;</code>.</p>\n<p>Re:<br />\n<code>std::swap(*subHead, *subTail);</code><br />\nThis works because you know that these are raw pointers. But generally you write code like this as a template, or at least you code mostly <em>as if</em> you are writing a template, to ease future maintenance. If the type of something changes, the code should at best still work; second but still OK is cause a compile-time error that you must fix; but <em>bad</em> is to silently fail. Consider what would happen if these were not raw pointers but iterators of some type, <em>including</em> something supplied by your program or another library (not in <code>std</code>).</p>\n<p>You need to use the so-called <a href=\"https://www.codeproject.com/Articles/1245810/Avoid-the-std-step\" rel=\"nofollow noreferrer\">&quot;<code>std</code> two-step&quot;</a> to use <code>swap</code> and a few others. Or, if using C++20 you can use <code>std::ranges::swap</code> instead. Always use <code>swap</code> etc. properly without relying on knowledge that the overload you want is indeed found in <code>std</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T17:31:27.380", "Id": "515640", "Score": "0", "body": "Thanks. So if I understand correctly, the only place where a ptr to ptr is really needed would be ListNode** subhead = &head? I think I see that reference to ptr would be better for the parameters of reverse." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T14:40:27.900", "Id": "261292", "ParentId": "261273", "Score": "3" } }, { "body": "<h3>Don't force-feed OOP.</h3>\n<p><code>class Solution</code> is a symptom of OOP-braindamage. The only members are better off as free functions.</p>\n<p>Beware that most coding-challenge sites promote an astonishing amount of bad ideas. Inefficiency by orders of magnitude is par for the course, and it gets worse.</p>\n<h3>Encapsulation</h3>\n<p>Too much leads to useless boilerplate. Specifically, a node should be a pure dumb struct, only containing data-members (links, in their own struct if both directions, and data, preferably in that order).</p>\n<p>But the nodes should be encapsulated in a list-type.</p>\n<p>Well, in this case as the point is playing with the innards, the enclosing type can be omitted, but it is a special case.</p>\n<h3><a href=\"//herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/\" rel=\"nofollow noreferrer\">Almost Always <code>auto</code></a></h3>\n<p>Don't complicate things by writing the exact type when nobody cares. Such duplication is at best tiresome, leading to more work when refactoring and often causing inefficient code.</p>\n<h3>Use minimum-strength operations</h3>\n<p>This way, you can avoid remainder <code>%</code>, and as a plus if there are more than <code>INT_MAX</code> nodes, you don't suffer from signed overflow, which is UB.</p>\n<h3>Boolean</h3>\n<p>Use implicit conversions. Use boolean algebra. Avoid explicit comparison, especially against <code>true</code>, which is easily done wrong.</p>\n<pre><code>auto reverseKGroup(ListNode* head, int k) {\n auto first = &amp;head;\n int i = k;\n for (auto last = head; last; last = last-&gt;next) {\n if (!--i) {\n i = k;\n auto temp = last-&gt;next;\n reverse(first, &amp;last);\n last-&gt;next = temp;\n first = &amp;last-&gt;next;\n }\n }\n return head;\n}\n</code></pre>\n<h3>Don't add debug-code to the normal flow</h3>\n<p>Let <a href=\"//en.cppreference.com/w/cpp/error/assert\" rel=\"nofollow noreferrer\"><code>assert()</code></a> shine in its true role.</p>\n<h3>Know the standard library</h3>\n<p><a href=\"//en.cppreference.com/w/cpp/algorithm/iter_swap\" rel=\"nofollow noreferrer\"><code>std::iter_swap()</code></a> incorporates the two-step needed for <code>std::swap()</code> before C++20 for pointees.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-12T06:44:07.857", "Id": "519069", "Score": "0", "body": "What do you mean by *minimum-strength operations*?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-12T10:34:41.957", "Id": "519079", "Score": "1", "body": "Some operations are generally more expensive. In this case, I replaced remainder and addition with subtraction. remainder and division are a bit costly, though admittedly the non-locality of list-nodes could easily dominate anyway." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T19:20:20.247", "Id": "261305", "ParentId": "261273", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T08:20:06.977", "Id": "261273", "Score": "2", "Tags": [ "c++", "programming-challenge", "interview-questions" ], "Title": "LeetCode Reverse Nodes in k-Group" }
261273
<p>Well this a re-implementation of a PowerShell script that I wrote which does exactly the same thing, and I have ported it into Python.</p> <p>After a quick Google search I found that there is only one other script that does the same thing, which can be found here: <a href="https://reg2ps.azurewebsites.net" rel="nofollow noreferrer">https://reg2ps.azurewebsites.net</a>, though the output of <kbd><code>Get remediation script</code></kbd> isn't as beautiful as mine, so my script does something truly special and pioneering.</p> <p>You can find the PowerShell version here: <a href="https://codereview.stackexchange.com/a/261267/234107">https://codereview.stackexchange.com/a/261267/234107</a></p> <p>This Python script converts a Windows registry file into a PowerShell script that is readily executable, it converts contents of the <code>.reg</code> file into <code>New-PSDrive</code> (if the script modifies a hive that isn't <code>HKCU</code> or <code>HKLM</code>), <code>New-Item</code>, <code>Set-ItemProperty</code>, <code>Remove-Item</code> and <code>Remove-ItemProperty</code> commands.</p> <p>It supports all five default registry hives:<code>HKEY_CLASSES_ROOT</code>, <code>HKEY_CURRENT_CONFIG</code>, <code>HKEY_CURRENT_USER</code>, <code>HKEY_LOCAL_MACHINE</code> and <code>HKEY_USERS</code>, and conversion from all six registry data types: <code>REG_SZ</code>, <code>REG_DWORD</code>, <code>REG_QWORD</code>, <code>REG_EXPAND_SZ</code>, <code>REG_MULTI_SZ</code> and <code>REG_BINARY</code>.</p> <p>For starters, <code>reg_sz</code> and <code>reg_dword</code> are encoded in plain text, <code>reg_sz</code> values are plain ASCII string values, and the datatype for them in <code>Set-ItemProperty</code> cmdlet is <code>String</code>, <code>REG_DWORD</code> values are 32-bit (4 bytes, or two words) binary values encoded in hexadecimal, or 8 hexadecimal bits, their datatype is <code>DWord</code> and their values must be preceded by the hexadecimal header <code>0x</code>.</p> <p>String values are indicated by a double quotes after assignment sign, dword values are indicated by <code>=dword:</code>.</p> <p><code>REG_QWORD</code> is a 64-bit (8 bytes or four words) binary value, equivalent to 16 hexadecimal bits, it is usually split into chunks of two bits, reversed order and joined by comma.</p> <p>Qword values are indicated by <code>=hex(b):</code>, <code>&quot;Qword0&quot;=hex(b):8d,02,4e,b8,00,00,00,00</code> means the value is qword b84e028d, their datatype is qword and their values must be preceded by <code>0x</code>.</p> <p><code>REG_EXPAND_SZ</code> is expandstring, it is indicated by <code>=hex(2):</code>, it is a string of multiple substrings delimited by semicolons, then encoded in ASCII, then 00 (null char) is inserted between every byte, the bytes are delimited by commas, then the whole encoding is broke up into multiple lines using backslashes as line breaks.</p> <p>Like this:</p> <pre><code>&quot;ExpandString&quot;=hex(2):53,00,74,00,72,00,69,00,6e,00,67,00,31,00,3b,00,53,00,74,\ 00,72,00,69,00,6e,00,67,00,32,00,3b,00,53,00,74,00,72,00,69,00,6e,00,67,00,\ 33,00,3b,00,53,00,74,00,72,00,69,00,6e,00,67,00,34,00,00,00 </code></pre> <p>Notice that every second byte is a null byte.</p> <p><code>REG_MULTI_SZ</code> is multistring, it is indicated by <code>=hex(7)</code> and very similar to expandstring, but it is a null delimited string of multiple lines with null characters serving as line breaks, so there are null bytes with odd indexes, like this:</p> <pre><code>&quot;MultiString0&quot;=hex(7):4c,00,69,00,6e,00,65,00,20,00,31,00,00,00,4c,00,69,00,6e,\ 00,65,00,20,00,32,00,00,00,4c,00,69,00,6e,00,65,00,20,00,33,00,00,00,4c,00,\ 69,00,6e,00,65,00,20,00,34,00,00,00,4c,00,69,00,6e,00,65,00,20,00,35,00,00,\ 00,00,00 </code></pre> <p>The odd indexed null characters must be represented by commas in PowerShell, the correct way to modify multistring values is supplying a array of the strings delimited by null chars, the commas should be where the odd indexed nulls are.</p> <p><code>REG_BINARY</code> is an arbitrary binary value in any format, indicated by <code>=hex:</code>, encoded in the same way as expandstring and multistring.</p> <p>Like this:</p> <pre><code>&quot;Test Binary&quot;=hex:74,68,69,73,20,69,73,20,61,20,74,65,73,74,20,73,74,72,69,6e,\ 67 </code></pre> <p>That are all the principles of the value conversions.</p> <p>So here is the code:</p> <pre><code>import os, re, sys def reg2ps1(args): hive = { 'HKEY_CLASSES_ROOT': 'HKCR:', 'HKEY_CURRENT_CONFIG': 'HKCC:', 'HKEY_CURRENT_USER': 'HKCU:', 'HKEY_LOCAL_MACHINE': 'HKLM:', 'HKEY_USERS': 'HKU:' } addedpath = [] args = rf'{args}' if os.path.exists(args) and os.path.isfile(args) and args.endswith('.reg'): commands = [] f = open(args, 'r', encoding='utf-16') content = f.read() f.close() for r in hive.keys(): if r in content and hive[r] not in ['HKCU:', 'HKLM:']: commands.append(&quot;New-PSDrive -Name {0} -PSProvider Registry -Root {1}&quot;.format(hive[r].replace(':', ''), r)) filecontent = [] for line in content.splitlines(): if line != '': filecontent.append(line.strip()) text = '' joinedlines = [] for line in filecontent: if line.endswith('\\'): text = text + line.replace('\\', '') else: joinedlines.append(text + line) text = '' for joinedline in joinedlines: if re.search('\[HKEY(.*)+\]', joinedline): key = re.sub('\[-?|\]', '', joinedline) hivename = key.split('\\')[0] key = '&quot;' + (key.replace(hivename, hive[hivename])) + '&quot;' if joinedline.startswith('[-HKEY'): commands.append(f'Remove-Item -Path {key} -Force -Recurse -ErrorAction SilentlyContinue') else: if key not in addedpath: commands.append(f'New-Item -Path {key} -ErrorAction SilentlyContinue | Out-Null') addedpath.append(key) elif re.search('&quot;([^&quot;=]+)&quot;=', joinedline): delete = False name = re.search('(&quot;[^&quot;=]+&quot;)=', joinedline).groups()[0] if '=-' in joinedline: commands.append(f'Remove-ItemProperty -Path {key} -Name {name} -Force') delete = True elif '&quot;=&quot;' in joinedline: vtype = 'String' value = re.sub('&quot;([^&quot;=]+)&quot;=', '', joinedline) elif 'dword' in joinedline: vtype = 'Dword' value = '0x' + re.sub('&quot;([^&quot;=]+)&quot;=dword:', '', joinedline) elif 'qword' in joinedline: vtype = 'QWord' value = '0x' + re.sub('&quot;([^&quot;=]+)&quot;=qword:', '', joinedline) elif re.search('hex(\([2,7,b]\))?:', joinedline): value = re.sub('&quot;([^&quot;=]+)&quot;=hex(\([2,7,b]\))?:', '', joinedline).split(',') hextype = re.search('(hex(\([2,7,b]\))?)', joinedline).groups()[0] if hextype == 'hex(2)': vtype = 'ExpandString' chars = [] for i in range(0, len(value), 2): if value[i] != '00': chars.append(bytes.fromhex(value[i]).decode('utf-8')) value = '&quot;' + ''.join(chars) + '&quot;' elif hextype == 'hex(7)': vtype = 'MultiString' chars = [] for i in range(0, len(value), 2): if value[i] != '00': chars.append(bytes.fromhex(value[i]).decode('utf-8')) else: chars.append(',') chars0 = (''.join(chars)).split(',') chars.clear() for i in chars0: chars.append('&quot;' + i + '&quot;') value = '@(' + ','.join(chars).replace(',&quot;&quot;,&quot;&quot;', '') + ')' elif hextype == 'hex(b)': vtype = 'QWord' value.reverse() value = '0x' + ''.join(value).lstrip('0') elif hextype == 'hex': vtype = 'Binary' value1 = [] for i in value: value1.append('0x' + i) value = '([byte[]]$(' + ','.join(value1) + '))' if not delete: if '@=' in joinedline: value = joinedline.replace('@=', '') commands.append(f'Set-ItemProperty -Path {key} -Name &quot;(Default)&quot; -Type &quot;String&quot; -Value {value}') else: commands.append('Set-ItemProperty -Path {0} -Name {1} -Type {2} -Value {3} -Force'.format(key, name, vtype, value)) filename = args.replace('.reg', '_reg.ps1') output = open(filename, 'w+') print(*commands, sep='\n', file=output) output.close() if __name__ == '__main__': reg2ps1(sys.argv[1]) </code></pre> <p>I am really very new to Python and this is the first time I have written something so complex like this in Python, and I know my script is really ugly, but it does get the conversions done right.</p> <p>Sample input:</p> <pre><code>Windows Registry Editor Version 5.00 [HKEY_CURRENT_USER\Test] &quot;Test String&quot;=&quot;This is a test string&quot; &quot;Test Binary&quot;=hex:74,68,69,73,20,69,73,20,61,20,74,65,73,74,20,73,74,72,69,6e,\ 67 &quot;Dword0&quot;=dword:b5e50577 &quot;Dword1&quot;=dword:b7feec6c &quot;Qword0&quot;=hex(b):8d,02,4e,b8,00,00,00,00 &quot;Qword2&quot;=hex(b):ff,ff,ff,ff,00,00,00,00 &quot;MultiString0&quot;=hex(7):4c,00,69,00,6e,00,65,00,20,00,31,00,00,00,4c,00,69,00,6e,\ 00,65,00,20,00,32,00,00,00,4c,00,69,00,6e,00,65,00,20,00,33,00,00,00,4c,00,\ 69,00,6e,00,65,00,20,00,34,00,00,00,4c,00,69,00,6e,00,65,00,20,00,35,00,00,\ 00,00,00 &quot;ExpandString&quot;=hex(2):53,00,74,00,72,00,69,00,6e,00,67,00,31,00,3b,00,53,00,74,\ 00,72,00,69,00,6e,00,67,00,32,00,3b,00,53,00,74,00,72,00,69,00,6e,00,67,00,\ 33,00,3b,00,53,00,74,00,72,00,69,00,6e,00,67,00,34,00,00,00 </code></pre> <p>Sample output:</p> <p>Registry Editor view:</p> <p><a href="https://i.stack.imgur.com/fr6wf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fr6wf.jpg" alt="enter image description here" /></a></p> <pre><code>New-Item -Path &quot;HKCU:\Test&quot; -ErrorAction SilentlyContinue | Out-Null Set-ItemProperty -Path &quot;HKCU:\Test&quot; -Name &quot;Test String&quot; -Type String -Value &quot;This is a test string&quot; -Force Set-ItemProperty -Path &quot;HKCU:\Test&quot; -Name &quot;Test Binary&quot; -Type Binary -Value ([byte[]]$(0x74,0x68,0x69,0x73,0x20,0x69,0x73,0x20,0x61,0x20,0x74,0x65,0x73,0x74,0x20,0x73,0x74,0x72,0x69,0x6e,0x67)) -Force Set-ItemProperty -Path &quot;HKCU:\Test&quot; -Name &quot;Dword0&quot; -Type Dword -Value 0xb5e50577 -Force Set-ItemProperty -Path &quot;HKCU:\Test&quot; -Name &quot;Dword1&quot; -Type Dword -Value 0xb7feec6c -Force Set-ItemProperty -Path &quot;HKCU:\Test&quot; -Name &quot;Qword0&quot; -Type QWord -Value 0xb84e028d -Force Set-ItemProperty -Path &quot;HKCU:\Test&quot; -Name &quot;Qword2&quot; -Type QWord -Value 0xffffffff -Force Set-ItemProperty -Path &quot;HKCU:\Test&quot; -Name &quot;MultiString0&quot; -Type MultiString -Value @(&quot;Line 1&quot;,&quot;Line 2&quot;,&quot;Line 3&quot;,&quot;Line 4&quot;,&quot;Line 5&quot;) -Force Set-ItemProperty -Path &quot;HKCU:\Test&quot; -Name &quot;ExpandString&quot; -Type ExpandString -Value &quot;String1;String2;String3;String4&quot; -Force </code></pre> <p>Please help me simplify and beautify my code, so that it does the same conversions correctly with less code and better format, thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T14:34:50.347", "Id": "515613", "Score": "2", "body": "_my script does something truly special and pioneering_ - if only I had so much confidence in my code." } ]
[ { "body": "<p>This is not a re-implementation of a PowerShell script; it's a PowerShell code generator written in Python. If you wanted to write an <em>actual</em> implementation in Python, you'd want to use <a href=\"https://docs.python.org/3/library/winreg.html\" rel=\"nofollow noreferrer\">winreg</a>.</p>\n<p>Looking at your code as-is,</p>\n<ul>\n<li><code>rf'{args}'</code> is a raw format string that can be wholly replaced with <code>str(args)</code></li>\n<li>Consider replacing <code>os</code> path-related calls with <code>pathlib.Path</code></li>\n<li>Whenever you <code>open</code> a file, enclose it in a <code>with</code></li>\n<li>Rather than having one giant <code>reg2ps1</code> function, split it up</li>\n<li>Consider factoring out the <code>commands.append</code> loop with a generator function and <code>yield</code>; similar for <code>filecontent</code></li>\n<li><code>text = text + line.replace</code> is O(n^2); alternatives include forming a generator and passing it to <code>''.join</code>, or using <code>StringIO</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T14:47:57.307", "Id": "261293", "ParentId": "261274", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T09:22:42.687", "Id": "261274", "Score": "3", "Tags": [ "python", "performance", "beginner", "python-3.x", "programming-challenge" ], "Title": "Python script that converts Windows Registry Scripts (.reg) into PowerShell scripts (.ps1)" }
261274
<blockquote> <p>Sum of Pairs</p> <p>Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.</p> <pre><code>sum_pairs([11, 3, 7, 5], 10) # ^--^ 3 + 7 = 10 == [3, 7] sum_pairs([4, 3, 2, 3, 4], 6) # ^-----^ 4 + 2 = 6, indices: 0, 2 * # ^-----^ 3 + 3 = 6, indices: 1, 3 # ^-----^ 2 + 4 = 6, indices: 2, 4 # * entire pair is earlier, and therefore is the correct answer == [4, 2] sum_pairs([0, 0, -2, 3], 2) # there are no pairs of values that can be added to produce 2. == None/nil/undefined (Based on the language) sum_pairs([10, 5, 2, 3, 7, 5], 10) # ^-----------^ 5 + 5 = 10, indices: 1, 5 # ^--^ 3 + 7 = 10, indices: 3, 4 * # * entire pair is earlier, and therefore is the correct answer == [3, 7] Negative numbers and duplicate numbers can and will appear. NOTE: There will also be lists tested of lengths upwards of 10,000,000 elements. Be sure your code doesn't time out. </code></pre> </blockquote> <pre><code>def sum_pairs(ints, s): ''' Params: ints: list[int] s: int --- sum Return First two values from left in ints that add up to form sum ''' ints_dict = {k:v for v,k in enumerate(ints)} # O(n) earliest_ending_idx = float('inf') earliest_pair = None for idx, num in enumerate(ints): # O(n) if idx &gt;= earliest_ending_idx: return earliest_pair try: second_num_idx = ints_dict[s-num] if second_num_idx != idx: if max(second_num_idx, idx) &lt; earliest_ending_idx: earliest_ending_idx = max(second_num_idx, idx) earliest_pair = [num, s-num] except KeyError: # s-num not in dict pass return earliest_pair </code></pre> <p>It seems to me that my code is O(n) in time complexity but I can't submit the solution since it took too long to run. Am I mistaken in my analysis and is there a better way to solve this problem?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T12:41:27.543", "Id": "515597", "Score": "0", "body": "Welcome to the Code Review Community. Please provide the programming challenge description in the question. If we don't have an idea of what the code is supposed to do, we really can't review the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T17:33:41.170", "Id": "515641", "Score": "0", "body": "Rather than pasting a screenshot of the problem statement, please paste a quoted `>` text block verbatim. Otherwise this is not searchable." } ]
[ { "body": "<p>your solution first maps <strong>all</strong> of the numbers, and then check for pairs.</p>\n<p>what if, for instance, the list of numbers is very long, and the first two items already sum up to the desired sum?</p>\n<p>I think that the optimal solution would iterate over the list only once.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T03:33:33.877", "Id": "515924", "Score": "0", "body": "This is a good prompt! Unfortunately when I saw this, I was still stuck with the initial solution I had and didn't consider the (on hindsight) obvious option of storing complements in the dictionary as I go." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T11:16:42.167", "Id": "261280", "ParentId": "261275", "Score": "2" } }, { "body": "<p>You have the right idea with storing the complements, i.e. <code>s-num</code>.</p>\n<p>However, there's no need to store indices. The iteration can be stopped when a pair is found, so iterating through the list in the usual manner will yield the first such pair.</p>\n<pre><code>def sum_pairs(ints, s):\n complement_dict = {}\n \n for i in ints:\n if i in complement_dict:\n return [s-i, i]\n else:\n complement_dict[s - i] = i\n\n return None\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T14:33:20.420", "Id": "261332", "ParentId": "261275", "Score": "1" } } ]
{ "AcceptedAnswerId": "261332", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T09:49:00.533", "Id": "261275", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Python Sum of Pairs Codewars Solution requires optimization" }
261275
<p>I'm working with a pandas dataframe which describes the start and end time of visits. A toy example of the data could be as follows:</p> <pre><code>import pandas as pd data = pd.DataFrame({&quot;start&quot;: [pd.Timestamp(&quot;2020-01-01 01:23:45&quot;), pd.Timestamp(&quot;2020-01-01 01:45:12&quot;)], &quot;end&quot;: [pd.Timestamp(&quot;2020-01-01 02:23:00&quot;), pd.Timestamp(&quot;2020-01-01 03:12:00&quot;)]}) </code></pre> <p>I want to break down these visits into periods: from 01:00 to 02:00, there were two visitors, from 02:00 to 03:00, also two, and from 03:00 to 04:00, only one of the visitors was present. To achieve this, I'm generating bounds for my periods and generate a dataframe with overlaps:</p> <pre><code>periods = pd.DataFrame({&quot;period_start&quot;: pd.date_range(start = &quot;2020-01-01 01:00:00&quot;, end = &quot;2020-01-01 03:00:00&quot;, freq = &quot;1H&quot;), &quot;period_end&quot;: pd.date_range(start = &quot;2020-01-01 02:00:00&quot;, end = &quot;2020-01-01 04:00:00&quot;, freq = &quot;1H&quot;)}) def has_overlap(A_start, A_end, B_start, B_end): latest_start = max(A_start, B_start) earliest_end = min(A_end, B_end) return latest_start &lt;= earliest_end periods_breakdown = pd.DataFrame() for i in range(3): ps = periods.period_start[i] pe = periods.period_end[i] periods_breakdown[&quot;period&quot; + str(i)] = data.apply(lambda row: has_overlap(row.start, row.end, ps, pe), axis = 1) </code></pre> <p>On the toy data, this code returns</p> <pre><code> period0 period1 period2 0 True True False 1 True True True </code></pre> <p>The problem is that the actual data has 1M visits that I want to break down over 6000 periods, and the code runs for roughly 140 hours.</p> <ol> <li>Is there a better way to count visitors from this sort of data?</li> <li>Are there performance improvements to this code?</li> </ol>
[]
[ { "body": "<p>I think it is slow because your <code>periods_breakdown</code> is gigantic, and to fill each cell you have to compute its value.\nBut what you compute is whether each individual visit overlapped with each other visit, which is overkill.\nIf what you want is to know when there is two visits (or more) overlapping, but don't need to know which specific ones, you can simply <strong>count how many visits there are during each hour slot</strong> and you will know when there was an overlap because the count will be more than one.</p>\n<p>Based on the data you provided :</p>\n<pre class=\"lang-py prettyprint-override\"><code>import pandas as pd\ndata = pd.DataFrame({&quot;start&quot;: [pd.Timestamp(&quot;2020-01-01 01:23:45&quot;),\n pd.Timestamp(&quot;2020-01-01 01:45:12&quot;)],\n &quot;end&quot;: [pd.Timestamp(&quot;2020-01-01 02:23:00&quot;),\n pd.Timestamp(&quot;2020-01-01 03:12:00&quot;)]})\n\nNUMBER_OF_PERIODS = 6 # FIXME: use an upper bound\nvisitors_count_per_hour = [0] * NUMBER_OF_PERIODS\n\nyear_start = pd.Timestamp(year=2020, month=1, day=1, hour=0, minute=0, second=0, microsecond=0)\nfor visit_start, visit_end in zip(data[&quot;start&quot;], data[&quot;end&quot;]):\n print(f&quot;there was a visit between {visit_start} and {visit_end}&quot;)\n start_hour = visit_start.floor(&quot;H&quot;)\n end_hour = visit_end.floor(&quot;H&quot;)\n print(f&quot; in hours, it spanned from {start_hour} to {end_hour} included&quot;)\n visit_hours = pd.date_range(start=start_hour, end=end_hour, freq=&quot;1H&quot;)\n offset = len(pd.date_range(start=year_start, end=start_hour))\n print(f&quot; it started at period n°{offset}&quot;)\n for i, visit_hour in enumerate(visit_hours):\n print(f&quot; - so we count one person at hour {visit_hour}&quot;)\n visitors_count_per_hour[i + offset] += 1\n\nprint(visitors_count_per_hour)\n\nperiods_breakdown = pd.DataFrame()\nfor hour_index, visitor_count in enumerate(visitors_count_per_hour):\n slot_hour = year_start + pd.Timedelta(hours=hour_index)\n periods_breakdown[&quot;period&quot; + str(hour_index)] = [slot_hour] + \\\n ([True] if visitor_count &gt; 1 else [False]) + \\\n [visitor_count]\n\nprint(periods_breakdown)\n</code></pre>\n<p>which outputs</p>\n<pre><code>there was a visit between 2020-01-01 01:23:45 and 2020-01-01 02:23:00\n in hours, it spanned from 2020-01-01 01:00:00 to 2020-01-01 02:00:00 included\n it started at period n°1\n - so we count one person at hour 2020-01-01 01:00:00\n - so we count one person at hour 2020-01-01 02:00:00\nthere was a visit between 2020-01-01 01:45:12 and 2020-01-01 03:12:00\n in hours, it spanned from 2020-01-01 01:00:00 to 2020-01-01 03:00:00 included\n it started at period n°1\n - so we count one person at hour 2020-01-01 01:00:00\n - so we count one person at hour 2020-01-01 02:00:00\n - so we count one person at hour 2020-01-01 03:00:00\n[0, 2, 2, 1, 0, 0]\n period0 period1 period2 period3 period4 period5\n0 2020-01-01 00:00:00 2020-01-01 01:00:00 2020-01-01 02:00:00 2020-01-01 03:00:00 2020-01-01 04:00:00 2020-01-01 05:00:00\n1 False True True False False False\n2 0 2 2 1 0 0\n</code></pre>\n<p>My result is slightly different than yours because my period0 is <code>2020-01-01 00:00:00</code> while you started at <code>01:00:00</code>.</p>\n<p>Speaking of performance, your algorithm will fill N*M cells, N being the number of visits, M being the number of slots in your data. With the values you provided (N=1000000 and M=6000), it is not surpising it slow.\nMy solution, by not comparing each visit with each other, only does roughly N+M computes, which is a whole algorithmic complexity class down.</p>\n<p>I'm no expert of pandas, so there may a better way to write the code to do essentially the same thing. But if you want to have an even quicker program, maybe you can simplify your problem (find another algorithm) or make better use of pandas than me.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T11:33:36.183", "Id": "515790", "Score": "1", "body": "Thanks, I think this is part of the answer I needed. I don't think that performance is problematic only because of the N*M cells: if I would be filling 6 billion cells with zeros, that would be pretty quick, so part of the performance problems is definitely with the value calculations. Still, thanks for guiding me." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T14:45:06.827", "Id": "261335", "ParentId": "261278", "Score": "3" } }, { "body": "<p>As I worked more with these data, I realized that two problems were keeping me away from a decent performance:</p>\n<ol>\n<li>There is a big overhead with using <code>pandas</code>, and</li>\n<li>The data about visits is sparse, and I should make use of it</li>\n</ol>\n<p>So, the same data can be calculated by starting with an <code>np.zeros</code> matrix of a corresponding size, and setting <code>1</code>s within the range of each visit. Since the resulting data is purely numeric, it's better kept in a <code>numpy</code> array, not in a <code>pandas</code> dataframe. I also made use of <code>floor</code> and <code>ceil</code> functions for <code>pd.Timestamp</code> mentioned in <a href=\"https://codereview.stackexchange.com/a/261335/138891\">Lenormju's answer</a> to produce the following code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>range_start = min(data.start).floor(&quot;H&quot;)\nrange_end = max(data.end).ceil(&quot;H&quot;)\nrange_n = (range_end - range_start) // pd.Timedelta(&quot;1H&quot;)\n\nperiod_breakdown = np.zeros([len(data.index), range_n])\nfor i, row in data.iterrows():\n start_offset = (row.start.floor(&quot;H&quot;) - range_start) // pd.Timedelta(&quot;1H&quot;)\n end_offset = (row.end.ceil(&quot;H&quot;) - range_start) // pd.Timedelta(&quot;1H&quot;)\n period_breakdown[i,start_offset:end_offset] = 1\n</code></pre>\n<p>which runs for 15 minutes on the same dataset.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T06:40:20.493", "Id": "515930", "Score": "0", "body": "it used to take 140 hours, is getting down to 0,25 hour sufficient ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T07:24:41.390", "Id": "515935", "Score": "0", "body": "@Lenormju yes, 0,25 hours is quite sufficient." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T23:23:31.733", "Id": "261394", "ParentId": "261278", "Score": "0" } } ]
{ "AcceptedAnswerId": "261394", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T10:38:19.707", "Id": "261278", "Score": "4", "Tags": [ "python", "performance", "datetime", "pandas" ], "Title": "For each of the visitors, find if they were present within a time period: code is running slow" }
261278
<p>I have put together the back-end (API) with the Slim framework (v3) and MySQL.</p> <p><a href="https://i.stack.imgur.com/ghOJjm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ghOJjm.jpg" alt="enter image description here" /></a></p> <p>In index.php I have:</p> <pre><code>use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response; require '../vendor/autoload.php'; require '../src/config/db.php'; $app = new \Slim\App; // Todos Routes require '../src/routes/todos.php'; $app-&gt;run(); </code></pre> <p>In <code>db.php</code> I have:</p> <pre><code>class db{ // Properties private $dbhost = 'localhost'; private $dbuser = 'root'; private $dbpass = ''; private $dbname = 'todoapp'; // Connect public function connect(){ $mysql_connect_str = &quot;mysql:host=$this-&gt;dbhost;dbname=$this-&gt;dbname&quot;; $dbConnection = new PDO($mysql_connect_str, $this-&gt;dbuser, $this-&gt;dbpass); $dbConnection-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $dbConnection; } } </code></pre> <p>In <code>todos.php</code> I have:</p> <pre><code>use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response; $app = new \Slim\App; $app-&gt;options('/{routes:.+}', function ($request, $response, $args) { return $response; }); $app-&gt;add(function ($req, $res, $next) { $response = $next($req, $res); return $response -&gt;withHeader('Access-Control-Allow-Origin', '*') -&gt;withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization') -&gt;withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); }); // Get Todos $app-&gt;get('/api/todos', function(Request $request, Response $response){ $sql = &quot;SELECT * FROM todos&quot;; try{ // Get DB Object $db = new db(); // Connect $db = $db-&gt;connect(); $stmt = $db-&gt;query($sql); $todos = $stmt-&gt;fetchAll(PDO::FETCH_OBJ); $db = null; echo json_encode($todos); } catch(PDOException $e){ echo '{&quot;error&quot;: {&quot;text&quot;: '.$e-&gt;getMessage().'}'; } }); // Add Todo $app-&gt;post('/api/todo/add', function(Request $request, Response $response){ $title = $request-&gt;getParam('title'); $completed = $request-&gt;getParam('completed'); $sql = &quot;INSERT INTO todos (title, completed) VALUES (:title,:completed)&quot;; try { // Get DB Object $db = new db(); // Connect $db = $db-&gt;connect(); $stmt = $db-&gt;prepare($sql); $stmt-&gt;bindParam(':title', $title); $stmt-&gt;bindParam(':completed', $completed); $stmt-&gt;execute(); echo '{&quot;notice&quot;: {&quot;text&quot;: &quot;Todo Added&quot;}'; } catch(PDOException $e){ echo '{&quot;error&quot;: {&quot;text&quot;: '.$e-&gt;getMessage().'}'; } }); // Update Todo $app-&gt;put('/api/todo/update/{id}', function(Request $request, Response $response){ $id = $request-&gt;getAttribute('id'); $title = $request-&gt;getParam('title'); $completed = $request-&gt;getParam('completed'); $sql = &quot;UPDATE todos SET title = :title, completed = :completed WHERE id = $id&quot;; try{ // Get DB Object $db = new db(); // Connect $db = $db-&gt;connect(); $stmt = $db-&gt;prepare($sql); $stmt-&gt;bindParam(':title', $title); $stmt-&gt;bindParam(':completed', $completed); $stmt-&gt;execute(); echo '{&quot;notice&quot;: {&quot;text&quot;: &quot;Todo Updated&quot;}'; } catch(PDOException $e){ echo '{&quot;error&quot;: {&quot;text&quot;: '.$e-&gt;getMessage().'}'; } }); // Delete Todo $app-&gt;delete('/api/todo/delete/{id}', function(Request $request, Response $response){ $id = $request-&gt;getAttribute('id'); $sql = &quot;DELETE FROM todos WHERE id = $id&quot;; try{ // Get DB Object $db = new db(); // Connect $db = $db-&gt;connect(); $stmt = $db-&gt;prepare($sql); $stmt-&gt;execute(); $db = null; echo '{&quot;notice&quot;: {&quot;text&quot;: &quot;Todo Deleted&quot;}'; } catch(PDOException $e){ echo '{&quot;error&quot;: {&quot;text&quot;: '.$e-&gt;getMessage().'}'; } }); </code></pre> <h3>Questions/concerns:</h3> <ol> <li><p>Is the application well-structured or should I move the logic into controllers?</p> </li> <li><p>If I should move the logic into controllers, what would be the best approach to doing that?</p> </li> </ol> <h3>Post scriptum</h3> <p>I have added the front-end of the application <strong><a href="https://codereview.stackexchange.com/q/261363/178805">here</a></strong> for those that might be interested.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T07:54:06.183", "Id": "515782", "Score": "0", "body": "I have added the front-end of the application **[here](https://codereview.stackexchange.com/q/261363/178805)** if you're interested :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T14:02:25.960", "Id": "518771", "Score": "0", "body": "Why do you catch all PDO exceptions? Why don't you implement an error handler for all exceptions or just use the built-in error handler?" } ]
[ { "body": "<ol>\n<li>In short, no. Actually doesn't seem to be structured in any way :D</li>\n<li>If your API will be just that, you can even give up on slim and have a plain index.php with url rewrite so you can achieve the best performance.</li>\n</ol>\n<p>Few things that I recommend:</p>\n<ul>\n<li>first, I would try to use a DI (dependency injection). I like php-di ( <a href=\"https://php-di.org/\" rel=\"nofollow noreferrer\">https://php-di.org/</a> )</li>\n<li>next would be to try to go with an mvc structure where the view is actually a JSON output: have some classes, TodoController, and multiple public methods (one for each action/route). Another approach would be to use Actions, as in symfony (basically would mean to have separate class files for each route: AddTodoAction.php,DeleteTodoAction.php).</li>\n<li>the, you should group your files and here we can debate a lot. I like to have a &quot;Library&quot; folder and inside that have one folder per each module and each module has it's own grouping (Controller / Model / Dao / Processor / Validator / etc. *). It's some sort of mix between having all controllers inside a single folder and grouping by business logic. If you only have Todo's without any users or any other relations, you can have a generic Controller/Action folder and keep all controllers/actions inside that folder.</li>\n<li>ideally to also use a orm for communicating with the database, or at least use bindings for all inputs ($id should also be considered an input). I use eloquent with slim ( <a href=\"https://laravel.com/docs/8.x/eloquent\" rel=\"nofollow noreferrer\">https://laravel.com/docs/8.x/eloquent</a> ).</li>\n<li>have any sort of validation before actually using the input</li>\n<li>try and reuse the $response object that slim is already providing and avoid direct echo-ing the output as so.</li>\n</ul>\n<p>You can also try to have a look over this: <a href=\"https://github.com/gurkanbicer/slimmvc\" rel=\"nofollow noreferrer\">https://github.com/gurkanbicer/slimmvc</a></p>\n<p>Extra: have you tried slim 4.8? Why start a new project on such an old version?</p>\n<p>*: folder structure example:</p>\n<pre><code>config/\n bootstrap.php\n routes.php\n settings.php\npublic/\n index.php\nsrc/\n Core/ (here I keep common middlewares for authentication, health checks or other things, maybe a way to format arrays / objects to json to output them properly)\n Library/\n Todo/\n Action/\n AddTodoAction.php (called from routes.php and should only validate input, call a method from service and the output the result)\n DeleteTodoAction.php\n ListTodoAction.php\n Model/\n Todo.php\n TodoDao.php (can keep it here or in a separate namespace: Src/Library/Todo/Dao/TodoDao.php )\n Validator/ (can go with same approach as for controller vs action: a single class for all routes or multiple classes separated per action / business logic)\n AddTodoValidator.php\n TodoValidator.php\n TodoService.php (the service is the only class that I call from other services. It has methods for controller, example: getTodo(), and it calls a DAO class for communication with database / execute queries)\ntests/\n ... (if any)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T14:37:23.123", "Id": "261291", "ParentId": "261279", "Score": "4" } }, { "body": "<blockquote>\n<h3>Is the application well-structured or should I move the logic into controllers?</h3>\n</blockquote>\n<p>I agree with NemoXP that the current format is not well-structured. A file with 112 lines of code isn't horrible in terms of file length, but it handles multiple things - e.g. routing, updating models, etc. Separating the code out to controller methods would be wise - especially if multiple developers end up modifying the files.</p>\n<blockquote>\n<h3>If I should move the logic into controllers, what would be the best approach to doing that?</h3>\n</blockquote>\n<p>As NemoXP stated: a controller would be a good solution for moving the logic out of the router - e.g. TodoController, with a method for each route. That could have methods to abstract common tasks like returning the JSON, exception handling, etc.</p>\n<h2>Suggestions</h2>\n<h3>Avoid re-assignment</h3>\n<blockquote>\n<pre><code> // Get DB Object\n $db = new db();\n // Connect\n $db = $db-&gt;connect();\n</code></pre>\n</blockquote>\n<p>With the first assignment <code>$db</code> is assigned an instance of class <code>db</code>. Then in the next assignment that same variable is assigned the return value from the method <code>connect</code>, which is an instance of <code>PDO</code>.</p>\n<p>I likely mentioned in a review of your JavaScript code that it is wise to use <code>const</code> instead of <code>let</code> to avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment</a>. The concept applies here as well - over-writing a variable can make it difficult to &quot;reason&quot; about code if a variable changes type.</p>\n<p>A better name for the variable in the second assignment would be something that illustrates that it is a connection, not a database - something like <code>$connection</code>, <code>$conn</code>, etc.</p>\n<h3>Limit data returned</h3>\n<blockquote>\n<pre><code>$sql = &quot;SELECT * FROM todos&quot;;\n</code></pre>\n</blockquote>\n<p>For a small application this likely isn't an issue, especially if there are typically a small number of records and only a few columns. Problems can occur when:</p>\n<ul>\n<li>the table grows to have many columns - of course it isn't ideal but in real life it does happen. It is best to specify only the columns needed instead of <code>*</code></li>\n<li>the number of rows grows to more than is necessary. This can lead to memory issues. It is best to limit the number of results instead of selecting all records</li>\n<li>the data isn't filtered- perhaps for this application there isn't a need to filter the data but in a larger application, it would be wise to add some conditions to limit the data returned.</li>\n</ul>\n<h3>Storing credentials and other details</h3>\n<blockquote>\n<pre><code>private $dbhost = 'localhost';\nprivate $dbuser = 'root';\nprivate $dbpass = '';\nprivate $dbname = 'todoapp';\n</code></pre>\n</blockquote>\n<p>These are things that should not be stored in a repository. It is wise to store them in a file that is ignored by the VCS - e.g. .env files, which can be included with packages like <a href=\"https://github.com/vlucas/phpdotenv\" rel=\"nofollow noreferrer\">phpdotenv</a>.</p>\n<h3>Response Type</h3>\n<p>It appears that all routes return strings that are to be interpreted as JSON. In such cases it is appropriate to <a href=\"https://stackoverflow.com/a/477819/1575353\">add a header to describe the Content-Type</a>. While it likely isn’t a security hole anymore, <a href=\"http://jibbering.com/blog/?p=514\" rel=\"nofollow noreferrer\">at one point ~15 years ago an XSS attack may have been possible if content-type headers weren’t set</a>.</p>\n<pre><code>$response-&gt;withHeader('Content-type', 'application/json');\n</code></pre>\n<p>Presuming all routes have that same type, the header could be added with the other headers (e.g. <code>Access-Control-Allow-*</code>).</p>\n<h3>JSON String construction</h3>\n<p>In the route to get all TODO items <code>json_encode()</code> is used to convert the list to JSON format. Yet in other cases, included the <code>catch</code> blocks, a JSON object is created manually - e.g.</p>\n<blockquote>\n<pre><code> echo '{&quot;error&quot;: {&quot;text&quot;: '.$e-&gt;getMessage().'}';\n</code></pre>\n</blockquote>\n<p>This could be simplified using <code>json_encode()</code></p>\n<pre><code> echo json_encode('[&quot;error&quot; =&gt; [&quot;text” =&gt; $e-&gt;getMessage()]]];\n</code></pre>\n<p>The benefit here is no risk of the exception message breaking the string literal - e.g. if it contained a delimter character like <code>”</code> or <code>}</code>. Actually, now that I think of it, the original line could lead to a JavaScript error because the message is not surrounded by double quotes!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T07:54:25.453", "Id": "515783", "Score": "0", "body": "I have added the front-end of the application **[here](https://codereview.stackexchange.com/q/261363/178805)** if you're interested :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T20:34:54.107", "Id": "261310", "ParentId": "261279", "Score": "3" } } ]
{ "AcceptedAnswerId": "261310", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T11:00:42.947", "Id": "261279", "Score": "3", "Tags": [ "php", "sql", "api", "slim", "php7" ], "Title": "To-do app API made with Slim 3" }
261279
<p><strong>Hello everyone</strong></p> <p>In today's assignment I had to write a function to determine if (and how many) the quadratic function defined by the formula f(x) = ax^2 + bx +c has roots. I had decorators to write.</p> <p>Here is my solution:</p> <pre><code>from typing import List, Tuple from math import sqrt from datetime import datetime class DeltaError(Exception): '''Error when calculating roots, and delta is lower than 0.''' def __init__(self): Exception.__init__(self, &quot;Delta must be greater than 0!&quot;) class Quadratic: def __init__(self, a: int, b: int, c: int): self.a = a self.b = b self.c = c self.x = -1 @property def Roots(self): a, b, c = self.a, self.b, self.c d = sqrt(b * b - 4 * a * c) if d &gt; 0: x1 = (-b + d) / (2 * a) x2 = (-b - d) / (2 * a) return x1, x2 if d == 0: return -b / 2 * a if d &lt; 0: raise ZeroError @property def Vietas_formula(self): a, b, c = self.a, self.b, self.c d = b * b - 4 * a * c if d &gt; 0: return &quot;x1 + x2 = {x}&quot;.format(x = -b / a), &quot;x1 * x2 = {y}&quot;.format(y = c / a) @property def Vertex(self): a, b, c = self.a, self.b, self.c d = b * b - 4 * a * c return &quot;W: ({p}, {q})&quot;.format(p = -b / 2 * a, q = -d / 4 * a) @property def Time_dependent(self): if datetime.now().hour + 2 in range(8, 16): return &quot;Roots&quot; else: return &quot;Break&quot; @property def x_plus_3(self): a, b, c, x = self.a, self.b, self.c, self.x x += 3 return x * (x * a + b) + c quad = Quadratic(1, 5, 6) print(quad.Roots, quad.Vietas_formula, quad.Vertex, quad.Time_dependent, quad.x_plus_3) </code></pre> <p>I'm counting on advice, and a better use of classes, static assignment to a, b, c and delta values, so that through inheritance I can use in subsequent functions without having to declare them from scratch.</p> <p><strong>Have a nice day!</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T14:02:56.257", "Id": "515609", "Score": "1", "body": "_[you] had decorations to write_ as in the assignment forces you to call into declarations like `@property`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T06:31:14.750", "Id": "515667", "Score": "0", "body": "ummm... probably im wrong, but i thought @property are parts of decorators, but as i said im probably wrong.... How should I use decorators there?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T14:00:53.663", "Id": "515699", "Score": "0", "body": "No you're right - `@property` is a decorator; your wording just befuddled me a little." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T14:01:17.770", "Id": "515700", "Score": "0", "body": "And actually your use of `@property` overall is quite good, all things considered." } ]
[ { "body": "<p>Some minor stuff -</p>\n<ul>\n<li>your member functions and properties should be lower-case by PEP8</li>\n<li>you should add a property to get the discriminant, particularly since you use it in multiple places</li>\n<li>I don't know what <code>time_dependent</code> and <code>x_plus_3</code> do, nor why they're here. They seem like specific applications of the quadratic formula for a narrow situation. Given that, they should not be in this class.</li>\n<li>The returns from <code>vietas_formula</code> should not be strings; you should return a tuple of floats. Similar for <code>vertex</code>. Currently this is premature stringizing. Your <code>roots</code> already does this correctly.</li>\n<li>If you wanted to be thorough, <code>d &lt; 0</code> should not raise a <code>ZeroError</code> and instead should return complex roots. Python has <a href=\"https://docs.python.org/3/library/cmath.html\" rel=\"nofollow noreferrer\">built-in support for complex numbers</a>.</li>\n<li><code>self.x</code> does not belong as a member on the class.</li>\n<li>Have you renamed <code>DeltaError</code> to <code>ZeroError</code>?</li>\n<li><code>Exception.__init__</code> should be changed to use <code>super()</code></li>\n<li>The error message <code>Delta must be greater than 0!</code> is not strictly true, and should be <code>greater than or equal to zero</code>.</li>\n<li>Why must <code>a, b, c</code> be <code>int</code>? You should accept <code>float</code>.</li>\n</ul>\n<p>Some major stuff: have you checked this for correctness? I see at least three algebraic errors, including that <code>d = sqrt(b * b - 4 * a * c)</code> is calling <code>sqrt</code> too early to catch failures, and <code>-b / 2 * a</code> has incorrect order of operations. Unit testing for this kind of code is both easy and important; while translating your code I ran into test failures and had to make corrections almost every step of the way.</p>\n<h2>Suggested</h2>\n<p>I still don't understand why your code needs to take a break (it's actually pretty funny. Maybe it's unionized?), but so be it:</p>\n<pre><code>from cmath import sqrt, isclose\nfrom datetime import datetime, time\nfrom numbers import Complex\nfrom typing import Union, Tuple\n\nRootTypes = Union[\n Tuple[Complex],\n Tuple[Complex, Complex],\n]\n\nWORK_HOURS_START = time(8)\nWORK_HOURS_END = time(16)\n\n\nclass Quadratic:\n def __init__(self, a: float, b: float, c: float):\n self.a, self.b, self.c = a, b, c\n\n def y(self, x: Complex) -&gt; Complex:\n a, b, c = self.a, self.b, self.c\n return a*x*x + b*x + c\n\n def dydx(self, x: Complex) -&gt; Complex:\n a, b = self.a, self.b\n return 2*a*x + b\n\n @property\n def discriminant(self) -&gt; float:\n a, b, c = self.a, self.b, self.c\n return b*b - 4*a*c\n\n @property\n def roots(self) -&gt; RootTypes:\n a, b, c, d = self.a, self.b, self.c, self.discriminant\n if d == 0:\n return -b/2/a,\n\n sqrt_d = sqrt(d)\n return (-b + sqrt_d)/2/a, (-b - sqrt_d)/2/a\n\n @property\n def vietas_formula(self) -&gt; Tuple[\n float, # sum\n float, # product\n ]:\n a, b, c = self.a, self.b, self.c\n return -b/a, c/a\n\n @property\n def vertex(self) -&gt; Tuple[\n float, # p\n float, # q\n ]:\n a, b, c, d = self.a, self.b, self.c, self.discriminant\n return -b/a/2, -d/a/4\n\n def describe(self) -&gt; str:\n v1, v2 = self.vietas_formula\n return (\n f'Roots: {self.roots}\\n'\n f'Vieta constants: x1+x2={v1}, x1*x2={v2}\\n'\n f'Vertex: {self.vertex}'\n )\n\n\ndef time_problem() -&gt; None:\n if WORK_HOURS_START &lt;= datetime.now().time() &lt; WORK_HOURS_END:\n a, b, c = 1, 5, 6\n quad = Quadratic(a, b, c)\n print(quad.describe())\n else:\n print(&quot;I'm on a break for some reason.&quot;)\n\n\ndef abs_close(x: Complex, y: Complex) -&gt; bool:\n return isclose(x, y, abs_tol=1e-12)\n\n\ndef test_two_real() -&gt; None:\n q = Quadratic(1, 5, 6)\n\n x1, x2 = q.roots\n assert abs_close(0, x1.imag)\n assert abs_close(0, x2.imag)\n assert abs_close(0, q.y(x1))\n assert abs_close(0, q.y(x2))\n\n v1, v2 = q.vietas_formula\n assert abs_close(v1, x1 + x2)\n assert abs_close(v2, x1 * x2)\n\n vx, vy = q.vertex\n assert abs_close(0, q.dydx(vx))\n assert abs_close(vy, q.y(vx))\n\n\ndef test_one_real() -&gt; None:\n q = Quadratic(9, -6, 1)\n\n x, = q.roots\n assert abs_close(0, x.imag)\n assert abs_close(0, q.y(x))\n\n # In this case Vieta's formula can be interpreted as two identical superimposed roots\n x1, x2 = x, x\n v1, v2 = q.vietas_formula\n assert abs_close(v1, x1 + x2)\n assert abs_close(v2, x1 * x2)\n\n vx, vy = q.vertex\n assert abs_close(0, q.dydx(vx))\n assert abs_close(0, vy)\n\n\ndef test_two_complex() -&gt; None:\n q = Quadratic(4, -4, 3)\n\n x1, x2 = q.roots\n assert not abs_close(0, x1.imag)\n assert not abs_close(0, x2.imag)\n assert abs_close(0, q.y(x1))\n assert abs_close(0, q.y(x2))\n\n v1, v2 = q.vietas_formula\n assert abs_close(v1, x1 + x2)\n assert abs_close(v2, x1 * x2)\n\n vx, vy = q.vertex\n assert abs_close(0, q.dydx(vx))\n assert abs_close(vy, q.y(vx))\n\n\ndef test() -&gt; None:\n test_two_real()\n test_one_real()\n test_two_complex()\n\n\nif __name__ == '__main__':\n test()\n time_problem()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T06:33:22.020", "Id": "515668", "Score": "0", "body": "time dependence is quite simple, when the current time is between 8am and 3pm it should return roots, otherwise it should return \"im having a break\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T13:56:42.683", "Id": "515698", "Score": "0", "body": "That's weird, but sure. There's a better way to go about comparing a time range." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T14:20:19.883", "Id": "261290", "ParentId": "261283", "Score": "3" } } ]
{ "AcceptedAnswerId": "261290", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T12:02:05.367", "Id": "261283", "Score": "2", "Tags": [ "python", "object-oriented" ], "Title": "Quadratic equation class in Python OOP" }
261283
<p>The task is to get the most recent login time of the day for each user. Then send such a result to an API.</p> <p>The log file (<code>file.log</code>) looks like the following (only the last two days):</p> <pre><code>2021-05-26 09:28:40.720+0000 INFO [alice]: logged in 2021-05-26 09:47:44.714+0000 INFO [alice]: logged in 2021-05-26 09:48:47.379+0000 INFO [frank]: logged in 2021-05-26 09:50:30.582+0000 INFO [bob]: logged in 2021-05-26 09:51:57.903+0000 INFO [alice]: logged in 2021-05-26 09:51:58.590+0000 INFO [alice]: logged in 2021-05-26 09:51:58.608+0000 INFO [alice]: logged in 2021-05-26 09:58:03.701+0000 INFO [bob]: logged in 2021-05-26 10:00:30.295+0000 INFO [alice]: logged in 2021-05-26 10:07:19.646+0000 INFO [frank]: logged in 2021-05-26 10:30:57.741+0000 INFO [alice]: logged in 2021-05-26 10:32:18.680+0000 INFO [alice]: logged in 2021-05-26 11:49:15.756+0000 INFO [bob]: logged in 2021-05-26 11:49:16.112+0000 INFO [alice]: logged in 2021-05-26 11:49:45.783+0000 INFO [frank]: logged in 2021-05-26 11:50:01.289+0000 INFO [susan]: logged in 2021-05-26 11:50:18.526+0000 INFO [frank]: logged in 2021-05-26 12:46:51.695+0000 INFO [bob]: logged in 2021-05-26 12:49:22.957+0000 INFO [alice]: logged in 2021-05-26 12:49:32.019+0000 INFO [frank]: logged in 2021-05-26 13:27:59.130+0000 INFO [alice]: logged in 2021-05-26 13:27:59.131+0000 INFO [alice]: logged in 2021-05-26 13:28:05.917+0000 INFO [bob]: logged in 2021-05-26 13:28:37.896+0000 INFO [frank]: logged in 2021-05-26 13:29:03.567+0000 INFO [bob]: logged in 2021-05-26 13:33:13.660+0000 INFO [frank]: logged in 2021-05-26 13:33:18.855+0000 INFO [alice]: logged in 2021-05-26 14:08:33.071+0000 INFO [alice]: logged in 2021-05-27 01:00:00.060+0000 INFO [alice]: logged in 2021-05-27 02:14:16.376+0000 INFO [alice]: logged in 2021-05-27 02:14:31.096+0000 INFO [alice]: logged in 2021-05-27 02:14:38.673+0000 INFO [bob]: logged in 2021-05-27 02:17:04.743+0000 INFO [bob]: logged in 2021-05-27 02:17:04.953+0000 INFO [alice]: logged in 2021-05-27 02:17:10.777+0000 INFO [alice]: logged in 2021-05-27 02:17:10.778+0000 INFO [alice]: logged in 2021-05-27 02:26:33.354+0000 INFO [bob]: logged in 2021-05-27 03:16:03.776+0000 INFO [alice]: logged in 2021-05-27 03:16:03.776+0000 INFO [alice]: logged in 2021-05-27 03:16:03.777+0000 INFO [alice]: logged in 2021-05-27 03:17:24.907+0000 INFO [bob]: logged in 2021-05-27 03:23:40.098+0000 INFO [frank]: logged in 2021-05-27 03:55:54.217+0000 INFO [alice]: logged in 2021-05-27 03:55:55.706+0000 INFO [alice]: logged in 2021-05-27 03:56:55.150+0000 INFO [alice]: logged in 2021-05-27 04:00:41.350+0000 INFO [alice]: logged in 2021-05-27 04:02:10.483+0000 INFO [bob]: logged in 2021-05-27 04:04:22.981+0000 INFO [bob]: logged in 2021-05-27 04:19:04.411+0000 INFO [alice]: logged in 2021-05-27 04:27:20.947+0000 INFO [bob]: logged in 2021-05-27 04:27:21.308+0000 INFO [alice]: logged in 2021-05-27 05:48:13.161+0000 INFO [alice]: logged in 2021-05-27 05:48:37.195+0000 INFO [alice]: logged in 2021-05-27 06:04:32.551+0000 INFO [bob]: logged in 2021-05-27 06:04:39.121+0000 INFO [alice]: logged in 2021-05-27 06:16:48.495+0000 INFO [bob]: logged in 2021-05-27 06:35:02.143+0000 INFO [alice]: logged in 2021-05-27 06:35:41.609+0000 INFO [bob]: logged in 2021-05-27 06:36:04.664+0000 INFO [bob]: logged in 2021-05-27 06:37:36.787+0000 INFO [frank]: logged in 2021-05-27 06:38:00.993+0000 INFO [alice]: logged in 2021-05-27 06:39:15.904+0000 INFO [alice]: logged in 2021-05-27 06:40:45.971+0000 INFO [bob]: logged in 2021-05-27 06:40:51.106+0000 INFO [alice]: logged in 2021-05-27 06:40:52.237+0000 INFO [alice]: logged in 2021-05-27 06:40:52.361+0000 INFO [alice]: logged in 2021-05-27 06:41:06.290+0000 INFO [frank]: logged in 2021-05-27 06:41:12.399+0000 INFO [alice]: logged in 2021-05-27 06:47:18.085+0000 INFO [frank]: logged in 2021-05-27 06:47:21.375+0000 INFO [alice]: logged in 2021-05-27 06:49:59.740+0000 INFO [frank]: logged in 2021-05-27 06:50:23.645+0000 INFO [alice]: logged in 2021-05-27 06:50:23.646+0000 INFO [alice]: logged in 2021-05-27 06:51:28.829+0000 INFO [frank]: logged in 2021-05-27 06:51:29.224+0000 INFO [alice]: logged in 2021-05-27 06:52:39.460+0000 INFO [bob]: logged in 2021-05-27 06:54:55.778+0000 INFO [alice]: logged in 2021-05-27 06:54:55.792+0000 INFO [alice]: logged in 2021-05-27 06:54:59.776+0000 INFO [alice]: logged in 2021-05-27 07:04:18.643+0000 INFO [bob]: logged in 2021-05-27 07:04:48.062+0000 INFO [frank]: logged in 2021-05-27 07:11:06.814+0000 INFO [alice]: logged in 2021-05-27 07:11:59.307+0000 INFO [frank]: logged in 2021-05-27 07:12:09.189+0000 INFO [bob]: logged in 2021-05-27 07:12:46.338+0000 INFO [martin]: logged in 2021-05-27 07:14:14.124+0000 INFO [martin]: logged in 2021-05-27 07:32:59.817+0000 INFO [alice]: logged in 2021-05-27 07:33:01.126+0000 INFO [alice]: logged in 2021-05-27 07:36:52.810+0000 INFO [frank]: logged in 2021-05-27 07:39:17.658+0000 INFO [alice]: logged in 2021-05-27 08:01:49.556+0000 INFO [alice]: logged in 2021-05-27 08:10:08.179+0000 INFO [frank]: logged in 2021-05-27 08:14:37.349+0000 INFO [alice]: logged in 2021-05-27 08:15:41.975+0000 INFO [bob]: logged in 2021-05-27 08:18:41.127+0000 INFO [admin]: logged in 2021-05-27 08:19:12.261+0000 INFO [admin]: logged in 2021-05-27 08:48:26.673+0000 INFO [bob]: logged in 2021-05-27 08:48:27.030+0000 INFO [alice]: logged in 2021-05-27 08:49:20.622+0000 INFO [alice]: logged in 2021-05-27 09:24:28.605+0000 INFO [alice]: logged in 2021-05-27 09:27:46.069+0000 INFO [alice]: logged in 2021-05-27 09:29:16.216+0000 INFO [bob]: logged in 2021-05-27 09:29:16.464+0000 INFO [bob]: logged in 2021-05-27 09:45:54.497+0000 INFO [alice]: logged in </code></pre> <p><strong>Note</strong>: these are only the lines that end with <code>logged in</code>. The original file contains 24K different logs and could be much bigger.</p> <p>Parsing the file should give this result:</p> <pre><code>2021-05-27T09:45:54.497Z alice 2021-05-27T09:29:16.464Z bob 2021-05-27T08:19:12.261Z admin 2021-05-27T08:10:08.179Z frank 2021-05-27T07:14:14.124Z martin </code></pre> <p>Basically, the most recent login time of today (in this case 2021-05-27) for each user. Users that haven't logged in today, shouldn't be included.</p> <p>Then such a result is sent to an API one by one.</p> <p>To do that I implemented the following bash script:</p> <pre class="lang-sh prettyprint-override"><code>#!/bin/bash SERVER_API_URL=&quot;http://localhost:8080/api/user&quot; TODAY=$(date +'%Y-%m-%d') while read login_time user_id; do # following line is wrapped in echo for testing echo &quot;curl -X PUT $SERVER_API_URL/$user_id/lastLoginTime/$login_time&quot; done &lt; &lt;(cat file.log | grep &quot;$TODAY.*logged in&quot; | sort -r | awk -F' ' '!seen[$4]++' | awk '{p=index($2,&quot;+&quot;); print $1&quot;T&quot;substr($2,1,p-1)&quot;Z&quot;,$4 }' | awk -F'[' '{ print $1,$2}' | cut -d']' -f1) </code></pre> <p>Running this script on <code>file.log</code> gives this result:</p> <pre><code>curl -X PUT http://localhost:8080/api/user/alice/lastLoginTime/2021-05-27T09:45:54.497Z curl -X PUT http://localhost:8080/api/user/bob/lastLoginTime/2021-05-27T09:29:16.464Z curl -X PUT http://localhost:8080/api/user/admin/lastLoginTime/2021-05-27T08:19:12.261Z curl -X PUT http://localhost:8080/api/user/frank/lastLoginTime/2021-05-27T08:10:08.179Z curl -X PUT http://localhost:8080/api/user/martin/lastLoginTime/2021-05-27T07:14:14.124Z </code></pre> <p>For testing purposes, the curl command is printed to console instead of running it.</p> <p>It does the job, but I am not satisfied by the super long last command. How can it be improved? Any suggestion is welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T10:04:21.403", "Id": "515686", "Score": "2", "body": "Micro-review: the `cat` is useless and can be replaced by giving the filename as argument to `grep`." } ]
[ { "body": "<ul>\n<li>As @TobySpeight pointed out in a comment, the <code>cat</code> is redundant. Any time you have a line like <code>cat &quot;$file&quot; | grep &quot;$pattern&quot;</code> you can replace it with <code>grep &quot;$pattern&quot; &quot;$file&quot;</code></li>\n<li>If your log entries are already ordered by time (at least for each user's login event), you can likely use <code>tac</code> instead of <code>sort -r</code></li>\n<li>Can a user have <code>logged in</code> be their user ID? I assume not, but if they can, we have a bug where instead of sending their most recent login, you might send their most recent event of <em>any</em> kind (or something malformatted, might depend on how the rest of the log looks). Either way, if this turns out to be a problem it can easily be worked around by adding an anchor to the <code>grep</code>'s pattern, or using <code>grep -x</code></li>\n<li>I'm pretty sure the first two <code>awk</code> calls can be combined into a single one like <code>awk -F' ' '!seen[$4]++ { p = index($2, &quot;+&quot;); print $1 &quot;T&quot; substr($2, 1, p-1) &quot;Z&quot;, $4 }'</code></li>\n<li>By the way, <code>awk</code> looks <em>dense</em> without spaces, and putting some spaces between operators and delimiters are stuff makes it a lot easier to look at</li>\n<li>Using <code>awk</code> and <code>cut</code> to remove <code>[</code> and <code>]</code> seems a bit awkward. Assuming those characters can't appear inside user IDs (since that's how user IDs are delimited it'd be annoying if they could) <code>tr -d '[]'</code> should do the job just fine here</li>\n<li>Having a long line like that is annoying, but it becomes less annoying if it's split between multiple physical lines. Which <em>is</em> possible, see below</li>\n<li>Personally, I think it'd look better if you were to pipe your data <em>into</em> the <code>while</code> instead of sending it in from behind using <code>&lt; &lt;()</code>. It's a matter of opinion, but to me it better represents the flow of data and also subjectively looks nicer</li>\n<li>I imagine it might be useful to parse log files like this regardless of what they're called. Hardcoding the name <code>file.log</code> makes that harder. One alternative could be taking the name as a command line parameter and begin with something like <code>grep -x &quot;$TODAY.*logged in&quot; &quot;$1&quot;</code>. But doing command line argument parsing properly is a pain, not doing it properly makes for some really awkward-to-use scripts unless you remember how you wrote them in the first place, and pipes <em>are</em> pretty neat, so maybe we can get away with just operating on <code>/dev/stdin</code> instead. Granted, having to call it like <code>./submit-logins &lt; file.log</code> is slightly more annoying (especially if you aren't doing it from the command line), but it's an option</li>\n</ul>\n<p>All in all, I'd probably recommend something like</p>\n<pre><code>#!/bin/bash\n\nSERVER_API_URL=&quot;http://localhost:8080/api/user&quot;\n\nTODAY=$(date +'%Y-%m-%d')\n\ngrep -x &quot;$TODAY.*logged in&quot; /dev/stdin |\n tac |\n awk -F' ' '!seen[$4]++ { p = index($2, &quot;+&quot;); print $1 &quot;T&quot; substr($2, 1, p-1) &quot;Z&quot;, $4 }' |\n tr -d '[]' |\n while read -r login_time user_id; do\n # following line is wrapped in echo for testing\n echo &quot;curl -X PUT $SERVER_API_URL/$user_id/lastLoginTime/$login_time&quot;\n done\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T23:22:46.333", "Id": "261442", "ParentId": "261285", "Score": "3" } } ]
{ "AcceptedAnswerId": "261442", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T12:37:41.013", "Id": "261285", "Score": "3", "Tags": [ "bash", "linux", "shell", "awk" ], "Title": "Parse log file and send the result to an API" }
261285
<p>I'm trying to keep a bunch of Objects called <code>Machine</code> in their proper order. I was wondering if it'd be possible to further optimize the function <code>HandleLocationCount</code> for performance.</p> <p>Any general feedback is of course also welcome. The function <code>HandleLocationCount</code> is only executed when a new <code>Machine</code> object is added.</p> <p>The <code>Machine</code> object is below, it references a <code>Section</code> object, which acts as a container for the various machines.</p> <pre><code>public class Machine { [Key] public int ID { get; set; } public string OrderNo { get; set; } public Section Section { get; set; } public int LocationInSection { get; set; } public ForcedLocation ForcedLocation { get; set; } = ForcedLocation.Blank; } </code></pre> <p>Section object &amp; enum for completeness; it's an enum instead of a boolean for future proofing:</p> <pre><code>public class Section { [Key] public int ID { get; set; } public string Name { get; set; } public string OrderNo { get; set; } public IEnumerable&lt;Machine&gt; MachinesInSection { get; set; } } public enum ForcedLocation { /// &lt;summary&gt; /// Does nothing for the location. /// &lt;/summary&gt; Blank, /// &lt;summary&gt; /// This entity is always last in the location. /// &lt;/summary&gt; Keep_Last, } </code></pre> <p>The function that calls the <code>HandleLocationCount</code> function looks like this; a user is able to manually set the location if needed.</p> <pre><code> public Machine Add(Machine entity) { if (entity.LocationInSection == 0) { IEnumerable&lt;Machine&gt; AmountMachines = GetMachinesByOrderNoAndSection(entity.OrderNo, entity.Section); entity.LocationInSection = handleLocationCount(AmountMachines); } _machineRepository.Add(entity); return entity; } </code></pre> <p>The function that returns the index just searches every machine for their order number &amp; name, the repository itself is just an interface that has a generic index function</p> <pre><code>public IEnumerable&lt;Machine&gt; GetMachinesByOrderNoAndSection(string orderno, Section section) { return _machineRepository.Index() .Where(m =&gt; m.OrderNo == orderno &amp;&amp; m.Section == section); } </code></pre> <p>And the code for the location looks like this, it updates older machines if this is needed; else just passes the new location for the machine</p> <pre><code> private int HandleLocationCount(IEnumerable&lt;Machine&gt; AmountOfMachines) { int newLocation = AmountOfMachines.Count() + 1; foreach (var Machine in AmountOfMachines) { int oldLocation = Machine.LocationInSection; switch (Machine.ForcedLocation) { case ForcedLocation.Blank: break; case ForcedLocation.Keep_Last: Machine.LocationInSection = AmountOfMachines.Count() + 1; break; default: break; } if (Machine.LocationInSection != oldLocation) { newLocation = oldLocation; Update(Machine); } } return newLocation; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T04:44:48.063", "Id": "515662", "Score": "0", "body": "How many `machine`'s can be there with `ForcedLocation == ForcedLocation.Keep_Last` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T05:49:16.707", "Id": "515664", "Score": "0", "body": "There can be max one per section" } ]
[ { "body": "<p>The method <code>GetMachinesByOrderNoAndSection</code> returns an <code>IEnumerable&lt;Machine&gt;</code>. Depending on how the method is implemented, iterating the enumeration may query the database. In <code>HandleLocationCount</code> you are iterating it and also calling <code>.Count()</code> on it several times. The LINQ <code>Count</code> extension method might also iterate the enumeration.</p>\n<p>Make sure to iterate it only once, e.g. by working on a list crated with <code>var list = AmountOfMachines.ToList();</code>, if something like this is not already done in <code>GetMachinesByOrderNoAndSection</code>.</p>\n<p>Also, you could use two distinct variables for storing <code>newLocation</code> and <code>AmountOfMachines.Count() + 1</code> and call the latter only once.</p>\n<hr />\n<p>I am not sure to understand the logic right. But you seem to assign the same <code>AmountOfMachines.Count() + 1</code> to all the <code>Keep_Last</code> machines. If this is the case, you could simply assign them a constant number like <code>Int32.MaxValue</code>. They would be kept last once and for all.</p>\n<p>Another possible approach is to partition the number range into two ranges:</p>\n<ol>\n<li><code>[1 .. Int32.MaxValue / 2]</code> for <code>Blank</code>.</li>\n<li><code>[Int32.MaxValue / 2 + 1 .. Int32.MaxValue]</code> for <code>Keep_Last</code>.</li>\n</ol>\n<p>Adavantages:</p>\n<ul>\n<li>The machines stay in their respective group.</li>\n<li>They are ordered.</li>\n<li>Adding a machine at the end of a group does not require the <code>LocationInSection</code> of others to be updated.</li>\n</ul>\n<p>Instead of getting the count, you would get the maximium value in the two groups.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>int nextBlank = machineList\n .Where(m =&gt; m.ForcedLocation == ForcedLocation.Blank)\n .DefaultIfEmpty(0)\n .Max() + 1;\nint nextKeepLast = machineList\n .Where(m =&gt; m.ForcedLocation == ForcedLocation.Keep_Last)\n .DefaultIfEmpty(Int32.MaxValue / 2)\n .Max() + 1;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T13:46:29.280", "Id": "515606", "Score": "0", "body": "I will add the `GetMachinesByOrderNoAndSection` function to my question, would it be better to cast it to a list right away when querying the database for this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T13:53:21.550", "Id": "515608", "Score": "0", "body": "Additionally, the Location number is used later in the program to get the next or previous machine if it's needed for calculations. I will try the MaxValue, but I do believe that'd cause issues" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T14:03:40.790", "Id": "515610", "Score": "1", "body": "The `IQueryable` and `IEnumerable` perform a lazy evaluation. This can prevent loading a lot of data into memory at once. Lazy evaluation gets the records being iterated just in time. But since you must get the count and perform a foreach, both iterating, you need a list. So, it depends on the number of machines. Just a few dozen? No problem with returning a list. 10s or 100s of thousands? Not ideal. If the number is really huge making 2 queries would be better. One query just getting the `COUNT(*)` returning only one record and another one returning all the machines in a `IEnumerable<>`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T14:10:00.633", "Id": "515611", "Score": "0", "body": "The expected amount of machines per order number is somewhere between 20-50, however for the entire solution I'm probably looking at a few thousand machines. Would it be recommended to split the queries? I thought I'd be better to just use one query for getting everything and only then splitting things." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T14:18:49.937", "Id": "515612", "Score": "2", "body": "Since this methods returns always only one order and one section, have it return a `List<Machine>`. You can then get the number of machines through the `list.Count` property (note, not `.Count()`!). Splitting the query is then superfluous." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T13:37:11.193", "Id": "261289", "ParentId": "261286", "Score": "2" } } ]
{ "AcceptedAnswerId": "261289", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T13:05:49.820", "Id": "261286", "Score": "0", "Tags": [ "c#", "performance", "asp.net-core" ], "Title": "Optimizing location updates when adding a new object" }
261286
<p>How to make my script shorter and better? This code allows only digits, auto-format card number like this XXXX XXXX XXXX XXXX. if user hits delete or backspace to delete space in between digits, nothing happens caret just moves 1 space forward or backward, it depends on which key user pressed (delete or backspace). If user hits backspace after digit and the previous second symbol is space then backspace deletes the digit and moves 2 spaces back like this (XXXX X|XXX XXXX XXXX -&gt; XXXX| XXXX XXXX XXX ). Delete key dose the same but vice versa like this (XXX|X XXXX XXXX XXXX -&gt; XXXX |XXXX XXXX XXX ). It also allows ctrl+c,ctrl+v,ctrl+a,ctrl+x.</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>let input = document.querySelector('input'); input.addEventListener('keyup', function (e) { let cursor = input.selectionStart; let inpVal = input.value; let cardCode = inpVal.replace(/\s/g, '').substring(0, 16); cardCode = cardCode != '' ? cardCode.match(/.{1,4}/g).join(' ') : ''; input.value = cardCode; let key = e.keyCode || e.which; // let ctrl = e.ctrlKey || key === 17 || e.metaKey; if ((key &gt;= 48 &amp;&amp; key &lt;= 57) || (key &gt;= 96 &amp;&amp; key &lt;= 105)) { if (cursor &lt; parseInt(inpVal.length)) { input.selectionEnd = cursor; } } else if (key == 8) { if (input.value[cursor - 1] == ' ') { input.selectionEnd = cursor - 1; } else { input.selectionEnd = cursor; } } else if (key == 46) { if (input.value[cursor + 1] == ' ') { input.selectionEnd = cursor + 2; } else { input.selectionEnd = cursor; } } }); input.addEventListener('keydown', function (e) { let inpVal = input.value; let cursor = input.selectionStart; let key = e.keyCode || e.which; let ctrl = e.ctrlKey || key === 17 || e.metaKey; if ( key == 9 || // Ctrl+A (key == 65 &amp;&amp; ctrl === true) || // Ctrl+C (key == 67 &amp;&amp; ctrl === true) || // Ctrl+X (key == 88 &amp;&amp; ctrl === true) || // Ctrl+V (key == 86 &amp;&amp; ctrl === true) || // home, end, влево, вправо (key &gt;= 35 &amp;&amp; key &lt;= 40) || (key &gt;= 48 &amp;&amp; key &lt;= 57) || (key &gt;= 96 &amp;&amp; key &lt;= 105) ) { return; } else if (key == 8) { if (input.value[cursor - 1] == ' ' &amp;&amp; cursor &lt; parseInt(inpVal.length)) { e.preventDefault(); input.selectionEnd = cursor - 1; } } else if (key == 46) { if (input.value[cursor] == ' ' &amp;&amp; cursor &lt; parseInt(inpVal.length)) { e.preventDefault(); input.selectionStart = cursor + 1; } } else { e.preventDefault(); } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form method="GET" action="#" class="card"&gt; &lt;label style="font-size: 20px; display: block; padding: 10px" for="cardnum"&gt;Credit Card number&lt;/label&gt; &lt;input style="font-size: 20px; padding: 10px" autocomplete="off" id="cardnum" name="cardnum" type="text" maxlength="19" title="Please enter a card number in XXXX XXXX XXXX XXXX format" pattern="^\d{4}\s\d{4}\s\d{4}\s\d{4}$" inputmode="numeric" required /&gt; &lt;/form&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:45:48.147", "Id": "515715", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>I've mainly got three points:</p>\n<ol>\n<li><p>The whole thing should be wrapped in a function with the reference to the <code>input</code> element passed in. Currently it is hard coded to (only) apply to the first <code>input</code> on the page, which doesn't seem like a practical scenerio.</p>\n</li>\n<li><p>Instead of using the deprecated/non-standard <code>keyCode</code> and <code>which</code>, you should be using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key\" rel=\"nofollow noreferrer\"><code>key</code></a>. And if you do use <code>keyCode</code> you should define all code numbers as constants.</p>\n</li>\n<li><p>Unless I'm missing some side-effect, the use of <code>parseInt</code> on <code>inpVal.length</code> is pointless.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T13:21:43.367", "Id": "261330", "ParentId": "261287", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T13:12:26.680", "Id": "261287", "Score": "4", "Tags": [ "javascript", "validation", "formatting" ], "Title": "How to make my code shorter. This Code formats Credit card number. Vanilla JS" }
261287
<h1>Background</h1> <p>I am creating a tool to locate a small bitmap in a large bitmap by comparing each pixel. Since I am by far no professional programmer, I was searching for some code snippets and found <a href="https://www.codeproject.com/Articles/38619/Finding-a-Bitmap-contained-inside-another-Bitmap" rel="nofollow noreferrer">this</a>. The code from the link uses pointers and requires therefor the “unsafe” keyword and is working perfectly. With the usage of the “unsafe” keyword some virus scanners (incl. Windows Defender) is ringing all alarm bells. While this is no problem when executing the program on my computer since I can trust myself, it is a big issue when sending out the program to friends etc.</p> <p><a href="https://i.stack.imgur.com/kMsPV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kMsPV.png" alt="Report from VirusTotal.com" /></a></p> <h1>My solution, step by step (if anyone like me is looking for a detailed How-To)</h1> <p>I decided to write my own method for that without using “unsafe” content. Trying to explain my logic:</p> <p>The following image is only for visualization and for better understanding. My method should return the upper left corner of the found &quot;smallBitmap&quot; within the &quot;largeBitmap&quot; (5,5)</p> <p><a href="https://i.stack.imgur.com/KlEHG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KlEHG.png" alt="Simplified images" /></a></p> <p>The bitmaps are located on local storage, so handling and loading them is no issue.</p> <p>At first I am converting each bitmap to a <code>byte[]</code> that contains the RGB values for each pixel. I also got pretty confused about the fact that the values are stored in BGR order.</p> <pre><code>private byte[] GetPixelData(Bitmap bitmap) { BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); byte[] bytes = new byte[bitmap.Width * bitmap.Height * 3]; for (int y = 0; y &lt; bitmap.Height; ++y) { IntPtr mem = (IntPtr)((long)bitmapData.Scan0 + y * bitmapData.Stride); Marshal.Copy(mem, bytes, y * bitmapData.Width * 3, bitmapData.Width * 3); } bitmap.UnlockBits(bitmapData); return bytes; } </code></pre> <p>I learned pretty quick, that you have to write the bytes for each line of the bitmap, otherwise you end up writing all the padding values, since: &quot;The size of each row is rounded up to a multiple of 4 bytes (a 32-bit DWORD) by padding.&quot; (<a href="https://en.wikipedia.org/wiki/BMP_file_format#Pixel_storage" rel="nofollow noreferrer">Thanks Wikipedia!</a>)</p> <p>The resulting <code>byte[]</code> for the small bitmap looks like this: <a href="https://i.stack.imgur.com/O68JS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O68JS.png" alt="Small Bitmap" /></a></p> <p>The resulting <code>byte[]</code> for the large bitmap looks like this (only the relevant part): <a href="https://i.stack.imgur.com/Ovh3Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ovh3Y.png" alt="Large Bitmap" /></a></p> <p>The following code is the method itself.</p> <pre><code>public void LocateBitmap(Bitmap smallBmp, Bitmap largeBmp, byte tol) { byte[] small = GetPixelData(smallBmp); byte[] large = GetPixelData(largeBmp); for (int i = 0; i &lt; large.Length; i += 3) { if (large[i] == small[0] &amp;&amp; large[i + 1] == small[1] &amp;&amp; large[i + 2] == small[2]) { // The first similar pixel has been found, now iterate through all pixels of the small bitmap and compare them to the large bitmap int ii = 0; bool found = true; for (int j = 0; j &lt; small.Length; j += 3) { // Calculate 2d position for the calculation of the relative position in the large bitmap int row = j / 3 / smallBmp.Width; int column = j / 3 % smallBmp.Width; // Offset the index accordingly ii = i + largeBmp.Width * 3 * row + column * 3; // Read each RGB value for easier debugging byte largeR = large[ii + 2]; byte largeG = large[ii + 1]; byte largeB = large[ii + 0]; byte smallR = small[j + 2]; byte smallG = small[j + 1]; byte smallB = small[j + 0]; if (!IsInRange(largeR, smallR, tol) || !IsInRange(largeG, smallG, tol) || !IsInRange(largeB, smallB, tol)) { // If they are not equal, break the loop since it cannot be the small image found = false; break; } } if (found) { int coordsX = i / 3 % largeBmp.Width; int coordsY = i / 3 / largeBmp.Width; Console.WriteLine($&quot;Bitmap found at {ii} --&gt; {coordsX}|{coordsY}&quot;); } } } } private bool IsInRange(byte a, byte b, byte tol) { if (a &gt;= b - tol &amp;&amp; a &lt;= b + tol) return true; return false; } </code></pre> <h1>How would you optimize the method?</h1> <p>I know that you can get rid of some variables like <code>largeR</code>, but I would like to know how you would optimize these methods performance / execution time wise.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T16:49:55.700", "Id": "515637", "Score": "0", "body": "Your code looks great, do you happen to have a usage example with your code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T22:02:37.500", "Id": "515653", "Score": "0", "body": "What version of .NET the project is targeting?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T23:20:11.930", "Id": "515850", "Score": "0", "body": "Currently it is targeting .NET 4.7.2. I will supply a usage example after the weekend." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T05:15:30.130", "Id": "518812", "Score": "0", "body": "I made a small page on [GitHub](https://hanebu.github.io/Loot-Goblin/) that explain the usage of the code above. This tool is a small helper for the Ultima Online Freeshard called [UO Outlands](https://uooutlands.com)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T13:52:46.137", "Id": "519677", "Score": "0", "body": "In 4.7.2 you have no such cool apis as `Span<T>` or `ReadOnlySpan<T>`. Then only unsafe code can help to speed up the code. Btw, [here's some code](https://codereview.stackexchange.com/a/254289/226545) for example." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-26T15:35:56.840", "Id": "261303", "Score": "4", "Tags": [ "c#", "image", "pointers" ], "Title": "Possible optimization for finding small bitmap in large bitmap in C# without unsafe code?" }
261303
<p>I have method that fetches sorted and filtered data from Mysql Database, Firstly I had done It by using Java. Now I did it by Mysql but I don't like the way the code looks</p> <p>I have entity that named Order and It looks like this</p> <pre><code>public class Order implements Serializable { private int orderId; private int userId; private int carId; private String userAddress; private String userDestination; private double orderCost; @JsonSerialize(using = CustomLocalDateTimeJsonSerializer.class) private LocalDateTime orderDate; //getters, setters } </code></pre> <p>Method that performs all work</p> <pre><code>@Override public List&lt;Order&gt; findFilSortOrders(Map&lt;String, String&gt; filters, String sortedColumn, boolean descending, int startRow, int rowsPerPage) { StringBuilder query = new StringBuilder(&quot;SELECT*FROM (SELECT*FROM user_order &quot;); ResultSet resultSet = null; LinkedHashMap&lt;String,String&gt; filterToQuery; List&lt;String&gt; values = new ArrayList&lt;&gt;(); List&lt;String&gt; keys = new ArrayList&lt;&gt;(); List&lt;Order&gt; orders = new ArrayList&lt;&gt;(); if(filters!=null){ query.append(&quot;WHERE &quot;); filterToQuery = new LinkedHashMap&lt;&gt;(filters); values = new ArrayList&lt;&gt;(filterToQuery.values()); keys = new ArrayList&lt;&gt;(filterToQuery.keySet()); keys.forEach(key-&gt; { if(key.equals(&quot;orderDate&quot;)){ query.append(&quot;date_format(&quot;).append(key).append(&quot;,'%Y-%m-%d %H:%i') = ? AND &quot;); }else{ query.append(key).append(&quot; = ? AND &quot;); } }); query.setLength(query.length()-4); } query.append(&quot; LIMIT ?, ?) a&quot;).append(&quot; ORDER BY &quot;).append(sortedColumn).append(&quot; &quot;).append(descending?&quot;DESC&quot;:&quot;ASC;&quot;); try(Connection connection = MySQLDAOFactory.getConnection(); PreparedStatement statement = connection.prepareStatement(query.toString())){ for (int i=0;i&lt;values.size();i++){ switch (keys.get(i)){ case &quot;orderId&quot;: case &quot;userId&quot;: case &quot;carId&quot;:{ statement.setInt(i+1, Integer.parseInt(values.get(i))); break; } case &quot;orderDate&quot;: case &quot;userAddress&quot;: case &quot;userDestination&quot;:{ statement.setString(i+1,values.get(i)); break; } case &quot;orderCost&quot;:{ statement.setDouble(i+1,Double.parseDouble(values.get(i))); break; } } } statement.setInt(values.size()+1,startRow); statement.setInt(values.size()+2,rowsPerPage); resultSet = statement.executeQuery(); while(resultSet.next()){ Order order = new Order(); order.setCarId(resultSet.getInt(&quot;carId&quot;)); order.setOrderId(resultSet.getInt(&quot;orderId&quot;)); order.setUserId(resultSet.getInt(&quot;userId&quot;)); order.setUserAddress(resultSet.getString(&quot;userAddress&quot;)); order.setUserDestination(resultSet.getString(&quot;userDestination&quot;)); order.setOrderCost(resultSet.getDouble(&quot;orderCost&quot;)); order.setOrderDate(resultSet.getTimestamp(&quot;orderDate&quot;).toLocalDateTime()); orders.add(order); } }catch (SQLException e){ LOGGER.error(e); try { if (resultSet != null) { resultSet.close(); } } catch (SQLException throwables) { LOGGER.error(throwables); } } return orders; } </code></pre> <p>This code works but I dont like it looks If you could help me improve the code, I would be very grateful. Thanks for answering.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T06:33:52.580", "Id": "515670", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<p>First off, the SQL query you are generating probably doesn't do what you want it to do. Because you using a subquery (a <code>SELECT</code> inside a <code>SELECT</code>) you are first limiting the unsorted data, and the sorting it, resulting in returning &quot;random&quot; rows instead of the first rows in sorted order. There is no reason to use a subquery, so instead of</p>\n<pre><code>SELECT * FROM (SELECT * FROM user_order WHERE ... LIMIT ?, ?) a ORDER BY ...\n</code></pre>\n<p>use</p>\n<pre><code>SELECT * FROM user_order WHERE ... ORDER BY ... LIMIT ?, ?\n</code></pre>\n<hr />\n<p>Then you really should format your code cleanly. The indentation is really bad and you should insert some empty lines between logical code blocks to separate them optically. Also put spaces in lines, specifically around operators, between keywords (<code>if</code>, <code>while</code> etc.) and <code>(</code>, after <code>;</code> and before <code>{</code>. For example, the line:</p>\n<pre><code>for(int i=0;i&lt;values.size();i++){\n</code></pre>\n<p>should look like this:</p>\n<pre><code>for (int i = 0; i &lt; values.size(); i++) {\n</code></pre>\n<p>BTW, your editor/IDE should be able to do that for you. Look for a menu item &quot;Format code&quot;.</p>\n<hr />\n<p>Don't declare variables until you need them. Both <code>resultSet</code> and <code>orders</code> don't need to be declared until the loop at the end:</p>\n<pre><code>ResultSet resultSet = statement.executeQuery();\nList&lt;Order&gt; orders = new ArrayList&lt;&gt;();\nwhile (resultSet.next()){\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:21:15.620", "Id": "515714", "Score": "0", "body": "Thanks for answer. What about code efficiency?How can I do It by using Java Stream API?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T14:41:24.340", "Id": "261334", "ParentId": "261312", "Score": "0" } } ]
{ "AcceptedAnswerId": "261334", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T22:14:19.120", "Id": "261312", "Score": "1", "Tags": [ "java", "sorting", "mysql", "hash-map", "jdbc" ], "Title": "I have a query like this that seems complicated and I want to do it by using Java Stream Api" }
261312
<p>Progress. I managed to fix the remaining GF fields, including QRCode and the various Aztec fields. Verified with the RS Java code. Loading the latest ProCrypto-1-1-1 and ProCryptoTests-1-1-1 will load the latest RSFEC.</p> <pre><code>Installer ss project: 'Cryptography'; install: 'ProCrypto-1-1-1'; install: 'ProCryptoTests-1-1-1'; install: 'CryptographyRSPlugin'. </code></pre> <p>Currently all methods are pluganized except for { #encode: #runEuclideanAlgorithm:..., #dividePoly... &amp; @decode:twoS: }. I am getting segfaults on those primitives when called. Investigating...</p> <pre><code> - 41541 tallies, 53540 msec. ((116473 - 53540) / 116473) asFloat * 100 54% SpeedUp **Leaves** Unpluganized 24.7% {13224ms} RSFECDecoderWithPlugin&gt;&gt;decode:twoS: 3.0% {1587ms} RSFECDecoderWithPlugin&gt;&gt;runEuclideanAlgorithmPoly:poly:rDegrees: Pluganized 16.9% {9045ms} RSFECGenericGFPoly class&gt;&gt;newField:coefficients: 6.2% {3311ms} RSFECDecoderWithPlugin&gt;&gt;primFindErrorLocationsDegree:coefficients:fieldSize:expTable:logTable: 4.2% {2245ms} RSFECGenericGFPolyWithPlugin&gt;&gt;addOrSubtractPoly: 2.5% {1317ms} RSFECDecoderWithPlugin&gt;&gt;findErrorMagnitudes:errorLocations: 1.7% {887ms} RSFECGenericGFWithPlugin&gt;&gt;log: 1.1% {583ms} RSFECGenericGFPolyWithPlugin&gt;&gt;degree Other 8.2% {4414ms} LargePositiveInteger(Integer)&gt;&gt;bitShift: 5.8% {3115ms} SecureHashAlgorithm&gt;&gt;finalHash 5.2% {2775ms} ByteArray class(Behavior)&gt;&gt;new: 5.1% {2705ms} LargePositiveInteger&gt;&gt;+ 3.1% {1639ms} SecureHashAlgorithm&gt;&gt;hashInteger:seed: 2.4% {1260ms} SecureRandom&gt;&gt;nextRandom160 1.6% {833ms} SmallInteger(Magnitude)&gt;&gt;between:and: 1.5% {786ms} ByteArray&gt;&gt;unsignedLongAt:put:bigEndian: </code></pre> <p>You can read about my Squeak code release <a href="//stackoverflow.com/q/67696209">implementing ZXing's Reed Solomon Error Correction</a>. It was suggested to me that I ask a question here.</p> <p>The <strong>speedup is 56%</strong> so far.</p> <p>NOTE: I got plugganized GF and GFPoly functions working, with the exception of #dividePoly:. Got some Decoder methods working. I am updating the example here to be the plugganized #findErrorLocations: code.</p> <p>CryptographyRSPluginExtending-rww.7.mcz now has all 7 missing primitives, for the FECDecoder, the GFPoly and the GaloisCodingLoop. Building and deploying this RSPlugin iwll blow the image up on GFFEC class&gt;&gt;#startUp:. This is for debugging. Here is the list.</p> <pre><code>GaloisCodingLoopOutputByteInputExpCodingLoopWithPlugin&gt;&gt;#primCheckSomeShardsMatrixRows: matrixRows inputs: inputs toCheck: toCheck offset: offset byteCount: byteCount GaloisCodingLoopOutputByteInputExpCodingLoopWithPlugin&gt;&gt;#primCodeSomeShardsMatrixRows: matrixRows inputs: inputs outputs: outputs offset: offset byteCount: byteCount GaloisCodingLoopOutputByteInputExpCodingLoopWithPlugin&gt;&gt;#primComputeValueMatrixRow: matrixRow inputs: inputs inputIndex: inputIndex byteIndex: byteIndex value: value FECGFPolyWithPlugin&gt;&gt;#primInitializePolyFieldSize: fieldSize coefficients: localCoefficients FECGFPolyWithPlugin&gt;&gt;#primDividePolySelfCoefficients: coefficients otherCoefficients: otherCoefficients fieldSize: fieldSize FECDecoderWithPlugin&gt;&gt;#primDecode: decoded twoS: twoS generatorBase: generatorBase FECDecoderWithPlugin&gt;&gt;#primRunEuclideanAlgorithmPolyA: polyA polyB: polyB degrees: fieldSize </code></pre> <p>Here is the DoIt to load everything into a Squeak VMMaker image, build in the image directory of the opensmalltalk-vm git clone. [1][2][3].</p> <pre><code>Installer ss project: 'Cryptography'; install: 'ProCrypto-1-1-1'; install: 'ProCryptoTests-1-1-1'; install: 'CryptographyRSPlugin'. </code></pre> <p>VM and project links:</p> <p>[1] <a href="https://github.com/OpenSmalltalk/opensmalltalk-vm" rel="nofollow noreferrer">Opensmalltalk-vm</a></p> <p>[2] <a href="http://source.squeak.org/VMMaker.html" rel="nofollow noreferrer">VMMaker Squeak repository</a></p> <p>[3] <a href="http://www.squeaksource.com/Cryptography.html" rel="nofollow noreferrer">Cryptography Squeak repository</a></p> <p>[4] <a href="https://www.dropbox.com/sh/vmqi8afjgbmzr72/AAAAee0MjDpI1xqwv7WqP9QQa?dl=1" rel="nofollow noreferrer">RSFEC Squeak and C code/compiled:linked plugins</a></p> <p>Currently failing at DecoderWithPlugin&gt;&gt;#findErrorLocations: primitive call. Strange thing, argument goes nil , it looks like. How'd that happen? Here's the <a href="https://www.dropbox.com/s/fcinfptyvv4xb42/Decoder-primitiveFailed.zip?dl=0" rel="nofollow noreferrer">debug log/crash package</a>.</p> <p>I have generated C code from RSFEC's GF Squeak plugin code using the Squeak CCodeGenerator. Now the RSFECPlugin Smalltalk methods for the Decoder.</p> <pre><code>findErrorLocationsDegree: degree coefficients: coefficients count: count fieldSize: fieldSize result: result &quot;// This is a direct application of Chien's search&quot; &lt;var: 'coefficients' type: #'unsigned char*'&gt; &lt;var: 'result' type: #'unsigned char*'&gt; | numErrors e index | numErrors := degree. (numErrors = 1) ifTrue: [^ result at: 0 put:(coefficients at: 0)]. e := 0. index := 1. [(index &lt; fieldSize) &amp; (e &lt; numErrors)] whileTrue: [ ((self evaluateAt: index coefficients: coefficients count: count fieldSize: fieldSize) = 0) ifTrue: [ result at: e put: (self inverse: index withSize: fieldSize). e := e + 1]. index := index + 1]. (e = numErrors) ifFalse: [ ^interpreterProxy primitiveFailFor: PrimErrBadArgument ]. ^ result </code></pre> <p>And here is the resulting C Code from the Translator.</p> <pre><code>/* // This is a direct application of Chien's search */ /* RSFECPlugin&gt;&gt;#findErrorLocationsDegree: coefficients: count: fieldSize: result: */ static unsigned char * findErrorLocationsDegreecoefficientscountfieldSizeresult( sqInt degree, unsigned char *coefficients, sqInt count, sqInt fieldSize, unsigned char *result) { sqInt e; sqInt index; sqInt numErrors; numErrors = degree; if (numErrors == 1) { return result[0] = (coefficients[0]); } e = 0; index = 1; while ((index &lt; fieldSize) &amp;&amp; (e &lt; numErrors)) { if ((evaluateAtcoefficientscountfieldSize(index, coefficients, count, fieldSize)) == 0) { result[e] = (inversewithSize(index, fieldSize)); e += 1; } index += 1; } if (!(e == numErrors)) { return primitiveFailFor(PrimErrBadArgument); } return result; } </code></pre> <hr /> <p>While we wait, perhaps y'all would like to take a gander at the Smalltalk code [3] that gets translated into the posted C code....I am supposed to include the source being discussed:</p> <p>VM and project links:</p> <p>[1] <a href="https://github.com/OpenSmalltalk/opensmalltalk-vm" rel="nofollow noreferrer">Opensmalltalk-vm</a></p> <p>[2] <a href="http://source.squeak.org/VMMaker.html" rel="nofollow noreferrer">VMMaker Squeak repository</a></p> <p>[4] <a href="https://www.dropbox.com/sh/vmqi8afjgbmzr72/AAAAee0MjDpI1xqwv7WqP9QQa?dl=1" rel="nofollow noreferrer">RSFEC Squeak and C code/compiled:linked plugins</a></p> <pre><code>primitiveMultiplyPolySelfCoefficientsOtherCoefficientsProductFieldSize &lt;export: true&gt; &lt;var: 'selfCoefficients' type: 'unsigned char*' &gt; &lt;var: 'otherCoefficients' type: 'unsigned char*' &gt; &lt;var: 'product' type: 'unsigned char*' &gt; | otherCoefficients selfCoefficients product otherCount selfCount otherCoefficientsOop productOop selfCoefficientsOop fieldSize | interpreterProxy methodArgumentCount = 4 ifFalse: [ ^interpreterProxy primitiveFailFor: PrimErrBadNumArgs ]. selfCoefficientsOop := interpreterProxy stackObjectValue: 3. otherCoefficientsOop := interpreterProxy stackObjectValue: 2. productOop := interpreterProxy stackObjectValue: 1. fieldSize := interpreterProxy stackIntegerValue: 0. selfCount := interpreterProxy stSizeOf: selfCoefficientsOop. otherCount := interpreterProxy stSizeOf: otherCoefficientsOop. selfCoefficients := interpreterProxy firstIndexableField: selfCoefficientsOop. otherCoefficients := interpreterProxy firstIndexableField: otherCoefficientsOop. product := interpreterProxy firstIndexableField: productOop. self multiplyPolySelfCoefficients: selfCoefficients selfCount: selfCount otherCoefficients: otherCoefficients otherCount: otherCount product: product fieldSize: fieldSize. interpreterProxy methodReturnReceiver. </code></pre> <p>Here is the Squeak code for translation that does the actual polynomial multiply. NOTE: This method's translated C code is in-lined into the primitive function.</p> <pre><code>multiplyPolySelfCoefficients: selfCoefficients selfCount: selfCount otherCoefficients: otherCoefficients otherCount: otherCount product: product fieldSize: fieldSize &lt;var: 'selfCoefficients' type: #'unsigned char*'&gt; &lt;var: 'otherCoefficients' type: #'unsigned char*'&gt; &lt;var: 'product' type: #'unsigned char*'&gt; | aCoeff aCoefficients aLength bCoefficients bLength | aCoefficients := selfCoefficients. aLength := selfCount. bCoefficients := otherCoefficients. bLength := otherCount. 0 to: (aLength - 1) do: [:aIndex | aCoeff := aCoefficients at: aIndex. 0 to: (bLength - 1) do: [:bIndex | product at: (aIndex + bIndex) put: ((self addOrSubtract: (product at: (aIndex + bIndex)) by: (self multiply: aCoeff by: (bCoefficients at: bIndex) withSize: fieldSize))) ]]. ^ product </code></pre> <p>Pretty sweet right? Yo, Stylin' Squeak. .. ... '...*,^</p> <p>We run on top of Spur (memory mgr), Cog (JITting language process engine) + Sista (active advancing JITting). The mysteries of the Squeak VM...</p> <p>Hopefully the hot spots will change and the plugins have helped. They did: 407%! We shall see what more can be done...</p> <p>I have completed plugin work. I now have a running plugin. The <strong>speedup is 56%</strong> and all the hotspots changed again. Here are the profiling results from just the RSFEC code alone, no RSErasure code is in the profiles. The new hotspots are, with RSFECPlugin, then without.</p> <p>I am implemented further methods {#findErrorLocations:, #findErrorMagnitudes:errorLocations:, #decode:twoS:}.</p> <p>The remaining potential plugganization relates to complex object instantiation inside the plugin functions. {#decode:twoS:, #runEuclideanAlgorithm: and #initializeField:coefficients:}. The best value for work return is to plugganize #initializeField:coefficients: at 3.3 seconds (14%)</p> <p>Calls to unplugganized GFPoly/Decoder methods:</p> <pre><code>WITH GF &amp; GFPOLY &amp; DECODER PRIMITIVES - 22194 tallies, 22648 msec. (128683 / 22648 ) asFloat **Leaves** 29.1% {6586ms} RSFECDecoderWithPlugin&gt;&gt;decode:twoS: 14.7% {3329ms} RSFECGenericGFPoly class&gt;&gt;newField:coefficients: 1.0% {237ms} RSFECDecoderWithPlugin&gt;&gt;runEuclideanAlgorithmPoly:poly:rDegrees: </code></pre> <p>Calls to plugganized GF/GFPoly/Decoder methods:</p> <pre><code>7.3% {1646ms} RSFECDecoderWithPlugin&gt;&gt;primFindErrorLocationsDegree:coefficients:result:fieldSize: 2.9% {654ms} RSFECDecoderWithPlugin&gt;&gt;findErrorMagnitudes:errorLocations: 1.4% {317ms} RSFECGenericGFWithPlugin&gt;&gt;log: </code></pre> <p>And:</p> <pre><code>WITHOUT GF &amp; GFPOLY PRIMITIVES - NO RSFEC PRIMITIVES - 98352 tallies, 128683 msec. **Leaves** GF arithmetic 23.4% {30126ms} RSFECGenericGF&gt;&gt;exp: 13.4% {17229ms} RSFECGenericGF&gt;&gt;addOrSubtract:by: 11.9% {15251ms} RSFECGenericGF&gt;&gt;maskValue: 10.0% {12916ms} RSFECGenericGF&gt;&gt;log: 8.6% {11059ms} RSFECGenericGF&gt;&gt;normalizeIndex: 6.8% {8792ms} RSFECGenericGF&gt;&gt;multiply:by: GFPoly arithmetic 2.7% {3529ms} RSFECGenericGFPoly&gt;&gt;evaluateAt: 2.1% {2715ms} RSFECGenericGFPoly&gt;&gt;addOrSubtractPoly: 2.0% {2578ms} RSFECGenericGFPoly&gt;&gt;multiplyByMonomialDegree:coefficient: </code></pre> <p>Grazie, rabbit . .. ... '...'^,^</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T04:12:57.073", "Id": "515661", "Score": "3", "body": "Welcome to Code Review. If you haven't tested the program, how can you be sure it's correct? The program being correct to the best of your knowledge is one of our requirements, as stated in the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T14:53:27.530", "Id": "515707", "Score": "0", "body": "I was unaware of this requirement. The generated code comes from working Squeak code. I thought code review can look at code without such requirement. The code I showed was for GF multiplication. I will hit you up again when I get it compiling and tested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T20:07:55.537", "Id": "515751", "Score": "0", "body": "While we wait, perhaps y'all would like to take a gander at the Smalltalk code that gets translated into the posted C code....I am supposed to include the source being discussed: See the editorial update to my OP.\n\n\n\n\nhttps://www.dropbox.com/s/l76k8yq7cpjnodc/RSFECPlugin.st?dl=0" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T16:52:23.250", "Id": "515815", "Score": "2", "body": "What is it you want reviewed exactly? Since the C code is generated by a tool, it seems it makes more sense to review that tool than the generated code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T15:31:12.707", "Id": "516147", "Score": "0", "body": "I wanted my Squeak code reviewed that gets translated into C code. I was not asking for the translator to be reviewed as that is not my work. If interested in the tool, you can find it in the VMMaker repository/package on source.squeak.org. I got everything compiling for RS and the **speedup is 407 %.**. I updated the OP with the latest code: Squeak & C, and the profiling numbers for RSFECPlugin." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T19:31:30.510", "Id": "516254", "Score": "0", "body": "Implementing #findErrorLocations: & #findErrorMagnitudes:errorLocators: in the plugin. Adopted use of TraceMonitor. Currently getting a segFault/#primitiveFailed exception, depending. I'll place the code to load at the top of the OP, since I can \"code\" format it. After this, consider pluginizing #decode:twoS: & #runEuclideanAlgorithmPoly:poly:rDegrees:. I would need to instantiate a ByteArray, in that code to do so. We shall see." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:32:05.793", "Id": "518333", "Score": "0", "body": "I got the two methods in the decoder also plugganized {#findErrorLocationsDegree:coefficients: & #findErrorMagnitudes:errorLocations:}. The results are posted at the bottom of the OP. 568%!!! speedup in total, with the RSFECPlugin." } ]
[ { "body": "<p>Well, yes, let's call this the answer.\n<strong>Increased performance by 568%</strong>.</p>\n<blockquote>\n<p>I finally got the changes made. You know that time when you have 2 images and you do the work in one and forget, then delete that one and have to recode all those changes? Exactly.</p>\n</blockquote>\n<p>Nonetheless, I got the changes made and did a test of creating a ByteArray in a primitive/computation method:</p>\n<pre><code> #fecAddOrSubtractPolySelfCoefficients:selfCount:otherCoefficients:otherCount:.\n</code></pre>\n<p>In my case, I decided to create the result ByteArray in the computation method and return the resultOop to the primitive for #methodReturnValue:. Here is the primitive, followed by the computation method. This seems to work as I compiled and tested it. One consideration is that if we are in a primitive and call another, like happens in the decode methods, then I must remember to #interpreterProxy firstIndexableField: resultOop to access the array again (pass as argument to yet another compute method, for instance). Is this the best approach?</p>\n<pre><code> resultOop := self\n fecAddOrSubtractPolySelfCoefficients: selfCoefficients\n selfCount: selfCount\n otherCoefficients: otherCoefficients\n otherCount: otherCount.\n\n ^ interpreterProxy failed\n ifTrue: [interpreterProxy primitiveFail]\n ifFalse: [interpreterProxy methodReturnValue: resultOop].\n</code></pre>\n<p>And the computation method</p>\n<pre><code> resultOop := interpreterProxy\n instantiateClass: interpreterProxy classByteArray\n indexableSize: (selfCount max: otherCount).\n result := interpreterProxy firstIndexableField: resultOop.\n\n &quot;COMPUTATIONS filling #result&quot;\n\n ^ resultOop\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-10T21:09:50.657", "Id": "262900", "ParentId": "261315", "Score": "1" } } ]
{ "AcceptedAnswerId": "262900", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T01:21:32.653", "Id": "261315", "Score": "-1", "Tags": [ "c", "smalltalk" ], "Title": "Squeak code generating C code for performant Reed Solomon error correction" }
261315
<p>I am currently participating in research on transient absorption spectroscopy and four wave mixing. In the experimental design, an extreme ultraviolet (XUV) laser pulse and infrared (IR) laser pulse are sent through a finite gas sample with a certain time delay between them. My current task is to develop a function that, given data on the system and input pulses, provides the transmission spectrum of the XUV pulse electric field after exiting the sample.</p> <p><strong>The Procedure</strong></p> <p>The gist of the procedure is to take two matrices describing the sample susceptibility, combine them into a single matrix, diagonalize said matrix, normalize the left and right eigenvector matrices according to each other, apply an exponential function to the eigenvalue matrix, and finally compute the exiting spectrum given an input spectrum.</p> <p><strong>The Code</strong></p> <pre><code>function E_out = FiniteSampleTransmissionXUV(w, X_0, X_nd, E_in, a, N, tau) % Function takes as input: % &gt; w - A vector that describes the frequency spectrum range % &gt; X_0 - A vector that describes the susceptibility % without the IR pulse % &gt; X_nd - A matrix that describes the susceptibility with the % IR pulse % &gt; E_in - A vector that describes the frequency spectrum of the % incoming XUV pulse electric field % &gt; a - A constant that describes the intensity of the IR pulse % &gt; N - A constant that describes the optical depth of the % sample % &gt; tau - A constant that describes the time delay between the % IR pulse and the XUV pulse % % Function provides output: % &gt; A vector that describes the frequency spectrum of the % XUV pulse electric field at the end of the sample % determines number of frequency steps from input frequency range n = size(w); % constant % determines frequency step size delta_w = 1 / (n(2) - 1); % constant % create matrix sqrt(w_i*w_j) sqrt_w = w.^(1/2).' * w.^(1/2); % nxn matrix % combine X_0 and X_nd into total suscptibility matrix X_ij = (a * delta_w * sqrt_w .* X_nd) + ... diag(diag(sqrt_w).' .* (X_0)); % nxn matrix % diagonalize X_ij where sum(U_R_i^2) = 1 [U_R, LAMBDA, U_L] = eig(X_ij); % nxn matrices % attain the function that scales U_L'*U_R F = sum(U_L' * U_R, 1); % row vector sqrt_F = F.^2; % scale U_R and U_L so that U_L'*U_R = 1 U_R_bar = U_R ./ sqrt_F; % nxn matrix U_L_bar = U_L ./ sqrt_F; % nxn matrix % apply exponential transform to eigenvalues % diagonal nxn matrix exp_LAMBDA = diag(exp(1i * (2*pi*N / (3*10^8)) * diag(LAMBDA))); % create phase shift due to the time delay tau_phase = exp(1i * w * tau); % row vector % recombine transformed susceptibility matrix ULAMBDAU = U_R_bar * exp_LAMBDA * U_L_bar'; % nxn matrix % apply effects of finite propagation and pulse % time delay to input electric field spectrum E_out = ULAMBDAU * (tau_phase .* E_in).'; % vector end </code></pre> <p><strong>Testing</strong></p> <p>The following is a script to test and demonstrate the function.</p> <pre><code>n = 100; % number of frequency steps w = linspace(0,1,n); % linearly spaced 1D array X_0 = (1 + 1i) * (sin(5*pi*w)).^2; X_nd = (1 + 1i) * ((sin(1*pi*w')) * sin(1*pi*w)).^2; E_in = GaussianSpectrum(w, 1, 0.5, 0.1); a = 1; N = 10^8; tau = 0; E_out = FiniteSampleTransmissionXUV(w, X_0, X_nd, E_in, a, N, tau); figure(1) plot(w, E_in,'b') hold on plot(w, abs(E_out),'r') hold off function E_w_x0 = GaussianSpectrum(w, E_0, w_0, sigma) % creates a quasi-gaussian spectrum defined by the input % frequency range w, amplitude E_0, center frequency w_0, % and spectral width sigma E_w_x0 = E_0 * sin(pi*w) .* ... (exp(-((w - w_0) / (2^(1/2) * sigma)).^2)); end </code></pre> <p>In running the test, we see the frequency spectrum of the XUV pulse before entering the sample in blue with the exiting spectrum in red. One sees that frequencies of the XUV pulse have been absorbed, while new frequencies have been generated.</p> <p><a href="https://i.stack.imgur.com/TDgjl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TDgjl.png" alt="enter image description here" /></a></p> <p>Please let me know what violates best practices and how the function could be refactored to be more robust and clean. Thank you!</p>
[]
[ { "body": "<p>Very nice code, it’s hard to find anything to comment on it.</p>\n<p><code>3*10^8</code> is better written as <code>3e8</code> (IEEE float format), then MATLAB doesn’t need to do any computations, though I doubt this would ever be a significant portion of the computation time. It is up to you what you find most readable.</p>\n<p>In your test code, <code>2^(1/2)</code> is more commonly written as <code>sqrt(2)</code>. Again, what is more readable is up to you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T17:40:50.420", "Id": "261388", "ParentId": "261316", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T01:25:28.353", "Id": "261316", "Score": "5", "Tags": [ "simulation", "matlab" ], "Title": "Simulate transmission spectrum of extreme ultraviolet laser pulse through laser-dressed finite sample (MATLAB version)" }
261316
<p><strong>Basic paging function, is there logical problems with the JavaScript part?</strong></p> <p>very basic paging function.<br> I want to know if there are some problems in the logic of the code. I feel the JS code is a bit bloated.</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-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt; &lt;title&gt;Go Coding!&lt;/title&gt; &lt;style&gt; * { margin: 0; padding: 0; border: none; font-size: 12px; list-style: none; text-decoration: none; } body { padding: 20px; } .title { font-size: 36px; color: #f80; } .title&gt;small { font-size: 24px; color: #ccc; vertical-align: 4px; } .tip { color: #999; } .emp { color: #f80; } .list&gt;li { padding: 6px; border-bottom: 1px solid #eee; } .pagination { padding: 4px; } .pagination a { display: inline-block; padding: 4px 8px; color: #00c; } .pagination a.active { font-weight: bold; color: #f80; background-color: #eee; } .pagination .tip { margin: 0 0 0 10px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;ul class="list"&gt;&lt;/ul&gt; &lt;section class="pagination"&gt;&lt;/section&gt; &lt;script&gt; let data = { "list": [ { "id": 1, "title": 2001 }, { "id": 2, "title": 2002 }, { "id": 3, "title": 2003 }, { "id": 4, "title": 2004 }, { "id": 5, "title": 2005 }, { "id": 6, "title": 2006 }, { "id": 7, "title": 2007 }, { "id": 8, "title": 2008 }, { "id": 9, "title": 2009 }, { "id": 10, "title": 2010 }, { "id": 11, "title": 2011 }, // { "id": 12, "title": 2012 }, // { "id": 13, "title": 2013 }, // { "id": 14, "title": 2014 }, // { "id": 15, "title": 2015 }, // { "id": 16, "title": 2016 }, // { "id": 17, "title": 2017 }, // { "id": 18, "title": 2018 }, // { "id": 19, "title": 2019 }, // { "id": 20, "title": 2020 }, // { "id": 21, "title": 2021 }, ] } let list = data.list; console.log(`Data Length: ${list.length}`); pagination({ "current-page": 1, "page-size": 2, }); function pagination(par) { let pagination = document.querySelector(".pagination"); let listBox = document.querySelector(".list"); let currentPage = par["current-page"]; let pageNums = par["page-nums"] || 5; let pageSize = par["page-size"]; let num = data.list.length; let totalPage = 0; if (num / pageSize &gt; parseInt(num / pageSize)) { totalPage = parseInt(num / pageSize) + 1; } else { totalPage = parseInt(num / pageSize); } let sliceStart = (currentPage - 1) * pageSize; let sliceEnd = currentPage * pageSize; sliceEnd = sliceEnd &gt; num ? num : sliceEnd; let dataSlice = data.list.slice(sliceStart, sliceEnd); let listText = ""; for (let item of dataSlice) { listText += ` &lt;li&gt; &lt;h5 class="title"&gt; &lt;small&gt;${item.id} - &lt;/small&gt;${item.title} &lt;/h5&gt; &lt;/li&gt; `; } listBox.innerHTML = listText; let htmlText = ""; if (currentPage &gt; 1) { htmlText += ` &lt;a href="#" onClick="pagination({'current-page': ${currentPage - 1}, 'page-size': ${pageSize}})"&gt; &amp;#8592; &lt;/a&gt; `; } let start = currentPage - Math.floor(pageNums / 2); let end = currentPage + Math.floor(pageNums / 2); if (end &lt; pageNums) { end = pageNums; } if (end &gt; totalPage) { end = totalPage; } if (end - start != pageNums - 1) { start = end - pageNums + 1; } if (start &lt; 1) { start = 1; } for (let i = start; i &lt;= end; i++) { htmlText += ` &lt;a class="${currentPage === i ? 'item-link active' : 'item-link'}" href="#" data-index="${i}" onClick="pagination({'current-page': ${i}, 'page-size': ${pageSize}})"&gt; ${i} &lt;/a&gt; `; } if (currentPage &lt; totalPage) { htmlText += ` &lt;a href="#" onClick="pagination({'current-page': ${currentPage + 1}, 'page-size': ${pageSize}})"&gt; &amp;#8594; &lt;/a&gt; `; } htmlText += ` &lt;span class="tip"&gt; &lt;b class="emp"&gt;${currentPage}&lt;/b&gt; / ${totalPage} &lt;/span&gt; `; pagination.innerHTML = htmlText; } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<h2>UX</h2>\n<p>Great job on the end product! There are no distracting CSS animation frills and everything appears to work smoothly.</p>\n<p>Consider disabling the forward/backward arrows on the first and last pages instead of removing them entirely. This way, the numbers are always in a fixed place and the user won't accidentally click the wrong thing or have to reposition their cursor after the page numbers shift unexpectedly after a click.</p>\n<p><a href=\"https://stackoverflow.com/questions/271743/whats-the-difference-between-b-and-strong-i-and-em\">Use <code>&lt;strong&gt;</code> instead of <code>&lt;b&gt;</code></a>. HTML is for semantics/structure, not style/presentation.</p>\n<p>Consider <code>&lt;button&gt;</code> instead of <code>&lt;a&gt;</code> for similar reasons. The <code>&lt;a href=&quot;#&quot;&gt;</code> leaves an ugly <code>#</code> in the browser URL (yeah, you can use <code>javascript:void(0)</code> but that's also obtrusive). These buttons could be in a list.</p>\n<h2>Use <code>const</code> instead of <code>let</code></h2>\n<p>Instead of using <code>let</code> everywhere, prefer using <code>const</code> everywhere. Yes, it's two more characters to type but it has at least three benefits:</p>\n<ol>\n<li><p><code>const</code> prevents a class of bugs related to inadvertent reassigments. Take any increase in guarantees you can get for free.</p>\n</li>\n<li><p><code>const</code> adds expressiveness to the code: when you <em>do</em> use <code>let</code>, it communicates to the reader that you intend to reassign the variable, such as in a loop counter. If you apply <code>let</code> across the board, a reader can't distinguish effectively-final variables (like <code>pageNums</code>) and intended-to-be-reassigned dynamic variables (like <code>currentPage</code>).</p>\n</li>\n<li><p>If you make an effort to prioritize <code>const</code> throughout your code, yet you notice you're using <code>let</code> excessively, it's a useful code smell indicating over-reliance on mutability. This applies to this program. Frequently, you declare some numerical variable with <code>let</code>, then mutate it in a series of branches to clamp to max/min bounds and so forth. It's not obvious what sort of values they might have at a given program point.</p>\n<p>If you challenge yourself to code without <code>let</code>, you'd have to break this logic into functions. You could use ternaries, but ternaries are OK in my book as long as they're not nested. <code>+=</code> can become <code>map</code>/<code>join</code>.</p>\n<p>Refactoring <code>let</code> into <code>const</code> should automatically make your code safer and cleaner.</p>\n</li>\n</ol>\n<h2>Style suggestions</h2>\n<ul>\n<li><p><code>.title&gt;small</code> should be <code>.title &gt; small</code> so it doesn't look like a single class name.</p>\n</li>\n<li><p>I like the config object parameter for <code>pagination</code> but <code>par</code> isn't the clearest variable name. Consider destructuring <code>par</code> into variables or rename it to <code>config</code>.</p>\n</li>\n<li><p><code>&quot;current-page&quot;</code> in your pagination config is odd because kebab case isn't used in JS. Prefer <code>currentPage</code> for easy destructuring and style consistency.</p>\n</li>\n<li><p><code>let list = data.list;</code> can use destructuring <code>const {list} = data;</code>. You don't have to see <code>list</code> twice and it's easier to add more properties in the future.</p>\n</li>\n<li><p>Spread long HTML properties onto multiple lines. Try to stick to a max width of 80-90 characters.</p>\n<pre><code>htmlText += `\n &lt;a class=&quot;${currentPage === i ? 'item-link active' : 'item-link'}&quot; href=&quot;#&quot; data-index=&quot;${i}&quot; onClick=&quot;pagination({'current-page': ${i}, 'page-size': ${pageSize}})&quot;&gt;\n ${i} \n &lt;/a&gt;\n`;\n</code></pre>\n<p>becomes</p>\n<pre><code>htmlText += `\n &lt;a\n class=&quot;${currentPage === i ? 'item-link active' : 'item-link'}&quot; \n href=&quot;#&quot; \n data-index=&quot;${i}&quot;\n onClick=&quot;pagination({'current-page': ${i}, 'page-size': ${pageSize}})&quot;\n &gt;\n ${i} \n &lt;/a&gt;\n`;\n</code></pre>\n</li>\n<li><p>Functions should be verbs, classes should be nouns. <code>pagination</code> should be called <code>paginate</code> or <code>createPagination</code>. If it were a class, it'd be <code>Pagination</code> or <code>Paginator</code>.</p>\n</li>\n</ul>\n<h2>Avoid monolithic functions</h2>\n<p><code>pagination</code> is too large. Try to break it into helper functions for logical subtasks that build HTML or compute start/end bounds.</p>\n<p>For example,</p>\n<pre><code>let totalPage = 0;\n\nif (num / pageSize &gt; parseInt(num / pageSize)) {\n totalPage = parseInt(num / pageSize) + 1;\n} else {\n totalPage = parseInt(num / pageSize);\n}\n</code></pre>\n<p>could be a named function. In addition to modularity, parameters and <code>return</code> give a lot of power to avoid reassignments, mutability and ugly control flow.</p>\n<p>Beyond that, <code>parseInt(num / pageSize)</code> is repeated 3 times and <code>num / pageSize</code> 4 times. <code>Math.floor</code> communicates what this code is doing better than <code>parseInt</code>.</p>\n<p>In this case, I think the whole thing can be replaced with <code>const totalPages = Math.ceil(num / pageSize)</code>.</p>\n<p>Keep <code>Math.max</code> and <code>Math.min</code> in mind to replace <code>if</code>-<code>else</code> blocks.</p>\n<h2>Avoid hardcoded globals</h2>\n<p>The <code>pagination</code> function isn't reusable because it's tied to a special variable <code>data</code> in the external scope. <code>data</code> must have a <code>list</code> property, every item in the list has to have <code>title</code> and <code>id</code> properties and <code>document.querySelector(&quot;.pagination&quot;)</code> has to exist.</p>\n<p>Your intent was probably to make a function so that it could be called as a handler -- basically, bare minimum to operate. This is fine for a toy example but not suitable for a large app.</p>\n<p>If the paginator is self-contained, then you can use it as a library, move it to its own module and create as many paginators as you need without worrying about corrupt state.</p>\n<p>Tightly-scoped data and loose coupling makes it easy to localize bugs.</p>\n<h2>Separate responsibility</h2>\n<p>With pagination, it's typically the backend database that should pick out the subset of records. Typically, your API will have routes for getting a total count of records, then offset and limit parameters, something like <code>/api/posts?offset=30&amp;limit=10</code>.</p>\n<p>However, this paginator seems to expect to work with a whole data set, only to pick out and render a page with <code>let dataSlice = data.list.slice(sliceStart, sliceEnd);</code>.</p>\n<p>You could pull out the list-rendering logic from the paginator and let the caller deal with it as they see fit. The paginator only needs to fire a page change event. No need to pass the data in, slice it or assume anything else about it.</p>\n<h2>Use caution with template strings, <code>innerHTML</code> and <code>+=</code></h2>\n<p>I'm a huge fan of template strings with <code>innerHTML</code>. It offers an OK chunk of the syntactic power and cleanliness of JSX in vanilla JS.</p>\n<p>These tools aren't entirely free lunch, though. One problem is potential performance issues. Setting <code>.innerHTML</code> means the string is parsed and converted to DOM elements under the hood. <code>+=</code> can be potentially slow because of <a href=\"https://www.joelonsoftware.com/2001/12/11/back-to-basics/\" rel=\"nofollow noreferrer\">Shlemiel the painter's algorithm</a>. We don't have a React diffing algorithm to selectively rerender only specific children.</p>\n<p>These aren't immediate issues and engine optimizations make <code>+=</code> and <code>.innerHTML</code> as fast as possible, but keep this in mind when profiling if you notice performance problems later.</p>\n<p>Unlike JSX, template strings and <code>.innerHTML</code> don't sanitize anything, so be sure to sanitize to prevent <a href=\"https://en.wikipedia.org/wiki/Cross-site_scripting\" rel=\"nofollow noreferrer\">XSS</a> attacks if the data isn't trustworthy.</p>\n<p>Short of React/Vue/etc, you could try a JSX-like library like <a href=\"https://github.com/developit/htm\" rel=\"nofollow noreferrer\">htm</a> to solve some of these problems.</p>\n<h2>Check out existing packages</h2>\n<p>When reinventing the wheel, it's a good idea to skim libraries on npm and GitHub and see what the state of the art is. This can steer you clear of poor designs and towards good ones up front. There's value in doing it the hard way blindly, but check out other designs afterwards.</p>\n<p>For example, <a href=\"https://www.npmjs.com/package/react-paginate\" rel=\"nofollow noreferrer\">react-paginate</a> accepts a click handler for page navigation and doesn't actually render the list. Even if you don't code React, you can probably see how this works on a high level from their <a href=\"https://github.com/AdeleD/react-paginate/blob/739ebccac9eacc05f29da53db83e0c2b6b103089/demo/js/demo.js\" rel=\"nofollow noreferrer\">demo</a>.</p>\n<h2>Rewrite suggestion</h2>\n<p>This isn't an industrial-strength paginator and could benefit from validating parameters, but it seems good enough to illustrate my points.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const paginate = ({\n container,\n totalPages,\n pagesToDisplay,\n startPage,\n onPageChange,\n classes,\n prevText,\n nextText,\n}) =&gt; {\n const list = (size, cb) =&gt; Array(size).fill().map(cb).join(\"\");\n\n const makePaginationHTML = (currentPage, start) =&gt; `\n ${currentPage === 0 ? \"\" : `\n &lt;a href=\"#\" class=\"${classes.prev}\"&gt;${prevText}&lt;/a&gt;\n `}\n ${list(pagesToDisplay, (_, i) =&gt; `\n &lt;a href=\"#\" class=\"${classes.item}\"&gt;${start + i + 1}&lt;/a&gt;\n `)}\n ${currentPage === totalPages - 1 ? \"\" : `\n &lt;a href=\"#\" class=\"${classes.next}\"&gt;${nextText}&lt;/a&gt;\n `}\n `;\n\n const addPaginationListeners = (els, currentPage, start) =&gt; {\n [...els].forEach((e, i) =&gt; {\n start + i === currentPage &amp;&amp; e.classList.add(\"active\");\n e.addEventListener(\"click\", () =&gt; changePage(start + i));\n });\n container.querySelector(\".\" + classes.prev)\n ?.addEventListener(\"click\", () =&gt; changePage(currentPage - 1))\n ;\n container.querySelector(\".\" + classes.next)\n ?.addEventListener(\"click\", () =&gt; changePage(currentPage + 1))\n ;\n };\n\n const renderPagination = currentPage =&gt; {\n const half = Math.floor(pagesToDisplay / 2);\n const start = currentPage &gt;= totalPages - half\n ? totalPages - pagesToDisplay\n : Math.max(0, currentPage - half)\n ;\n container.innerHTML = makePaginationHTML(currentPage, start);\n addPaginationListeners(\n container.getElementsByClassName(classes.item), \n currentPage, \n start\n );\n };\n\n const changePage = nextPage =&gt; {\n renderPagination(nextPage);\n onPageChange(nextPage);\n };\n changePage(startPage);\n};\n\nconst renderPages = (currentPage, totalPages) =&gt; {\n document.querySelector(\".pagination-tip\").innerHTML = `\n &lt;strong class=\"emp\"&gt;${currentPage + 1}&lt;/strong&gt; / ${totalPages}\n `;\n};\nconst renderList = data =&gt; {\n document.querySelector(\".list\").innerHTML = data.map(e =&gt; `\n &lt;li&gt;\n &lt;h5 class=\"title\"&gt;\n &lt;small&gt;${e.id} - &lt;/small&gt;${e.title}\n &lt;/h5&gt;\n &lt;/li&gt;\n `).join(\"\");\n};\n\n(() =&gt; {\n const data = {\n list: [\n {id: 1, title: 2001},\n {id: 2, title: 2002},\n {id: 3, title: 2003},\n {id: 4, title: 2004},\n {id: 5, title: 2005},\n {id: 6, title: 2006},\n {id: 7, title: 2007},\n {id: 8, title: 2008},\n {id: 9, title: 2009},\n {id: 10, title: 2010},\n {id: 11, title: 2011},\n {id: 12, title: 2012},\n {id: 13, title: 2013},\n {id: 14, title: 2014},\n {id: 15, title: 2015},\n {id: 16, title: 2016},\n {id: 17, title: 2017},\n {id: 18, title: 2018},\n {id: 19, title: 2019},\n {id: 20, title: 2020},\n {id: 21, title: 2021},\n ]\n };\n const limit = 4;\n const totalPages = Math.ceil(data.list.length / limit);\n const onPageChange = currentPage =&gt; {\n // fetch data from server here\n const offset = limit * currentPage;\n renderList(data.list.slice(offset, offset + limit));\n renderPages(currentPage, totalPages);\n };\n\n paginate({\n container: document.querySelector(\".pagination\"),\n totalPages,\n pagesToDisplay: 5,\n startPage: 0,\n onPageChange,\n classes: {\n prev: \"prev\",\n next: \"next\",\n item: \"item-link\",\n },\n prevText: \"&amp;#8592;\",\n nextText: \"&amp;#8594;\",\n });\n})();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* {\n margin: 0;\n padding: 0;\n border: none;\n font-size: 12px;\n list-style: none;\n text-decoration: none;\n}\n\nbody {\n padding: 20px;\n}\n\n.title {\n font-size: 36px;\n color: #f80;\n}\n.title &gt; small {\n font-size: 24px;\n color: #ccc;\n vertical-align: 4px;\n}\n\n.tip {\n color: #999;\n}\n\n.emp {\n color: #f80;\n}\n\n.list &gt; li {\n padding: 6px;\n border-bottom: 1px solid #eee;\n}\n\n.pagination {\n display: inline-block;\n padding: 4px;\n}\n.pagination a {\n display: inline-block;\n padding: 4px 8px;\n color: #00c;\n}\n.pagination a.active {\n background: red;\n font-weight: bold;\n color: #f80;\n background-color: #eee;\n}\n.pagination-tip {\n margin: 0 0 0 10px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;ul class=\"list\"&gt;&lt;/ul&gt;\n&lt;section class=\"pagination\"&gt;&lt;/section&gt;\n&lt;span class=\"pagination-tip\"&gt;&lt;/span&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": "2021-05-29T03:09:07.010", "Id": "261360", "ParentId": "261317", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T02:58:05.477", "Id": "261317", "Score": "2", "Tags": [ "javascript", "performance", "pagination" ], "Title": "basic paging function, is there logical problems with the JavaScript part?" }
261317
<p>The general problem I'm trying to solve is that I have a code base that has zero documentation so I'm trying to automatically generate some diagrams of classes in package that I'm analyzing using erdantic.</p> <p>Trying to make this as reusable as possible, so I have a <code>generate_diagrams()</code> function that should take in one argument, which is the package I want to iterate through.</p> <p>I often feel like I throw the terms <em>module</em> and <em>package</em> around interchangeably — I might be doing it now — so I defaulted my argument to the name &quot;directory&quot;. But I feel that's not right since I'm not passing in a path.</p> <p>Should I change the argument in <code>generate_diagrams()</code> below? What's a more accurate name?</p> <pre><code>import erdantic as erd import glob import importlib import example.models from os import path, makedirs def draw_diagram(module, cls_name, output_path): &quot;&quot;&quot; Args: module: module object cls_name: name of the class that's associated with the module output_path: path where diagram to be saved Returns: void - outputs .png file at given path &quot;&quot;&quot; try: diagram = erd.create(module.__getattribute__(cls_name)) diagram.models diagram.draw(f&quot;{output_path}/{cls_name}.png&quot;) except erd.errors.UnknownModelTypeError: pass def generate_diagrams(directory): &quot;&quot;&quot; Args: directory: package you have imported that contains module(s) you wish to diagram Returns: void - generates diagram using draw_diagram function &quot;&quot;&quot; doc_path = path.dirname(__file__) modules = glob.glob(path.join(path.dirname(directory.__file__), &quot;*.py&quot;)) module_names = [path.basename(f)[:-3] for f in modules if path.isfile(f) and not f.endswith('__init__.py')] for module_name in module_names: if not path.exists(path.join(doc_path, module_name)): print(f'Making {module_name} directory') makedirs(module_name) module = importlib.import_module(f'{directory.__name__}.{module_name}') classes = dict([(name, cls) for name, cls in module.__dict__.items() if isinstance(cls, type)]) for name, cls in classes.items(): print(f'Drawing {module_name}.{name} diagram') draw_diagram(module, cls_name=name, output_path=path.join(doc_path, module_name)) def main(): generate_diagrams(directory=example.models) if __name__ == &quot;__main__&quot;: main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T17:49:09.327", "Id": "515739", "Score": "0", "body": "Have you tried Doxygen?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T18:37:32.697", "Id": "515746", "Score": "0", "body": "I have not. First time trying to automate diagram building. Is that the standard?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T18:42:52.077", "Id": "515747", "Score": "0", "body": "I don't know if I'd call it standard, but it's popular and well-established. I'd give that a shot before writing any code" } ]
[ { "body": "<p>The Doxygen recommendation notwithstanding,</p>\n<ul>\n<li>Consider adding PEP484 type hints, particularly to the signatures of functions such as <code>draw_diagram</code>. For that method, it's not really correct Python terminology to call the return value &quot;void&quot; - it's <code>None</code>.</li>\n<li>Does the single-expression statement <code>diagram.models</code> actually have any effect? If so that deserves a comment.</li>\n<li>Rather than <code>glob.glob</code> consider <code>pathlib.Path.glob</code> which has some usage niceties</li>\n<li><code>path.basename(f)[:-3]</code> is a very fragile way of acquiring a stem. Again, <code>pathlib.Path</code> can do a better job.</li>\n</ul>\n<p>The line</p>\n<pre><code>dict([(name, cls) for name, cls in module.__dict__.items() if isinstance(cls, type)])\n</code></pre>\n<p>first of all should not use an inner list, since <code>dict</code> can directly accept a generator; and secondly would be better-represented as a dictionary comprehension:</p>\n<pre><code>{name: cls for name, cls in module.__dict__.items() if isinstance(cls, type)}\n</code></pre>\n<p>This loop:</p>\n<pre><code> for name, cls in classes.items():\n print(f'Drawing {module_name}.{name} diagram')\n draw_diagram(module, cls_name=name, output_path=path.join(doc_path, module_name))\n</code></pre>\n<p>doesn't actually use <code>cls</code>, so should only iterate over the dictionary's keys, not its items.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T20:34:02.977", "Id": "515753", "Score": "0", "body": "All great suggestions. What's the protocol? Should I add an edited version of the changes? I also reconfigured to a class structure so I could add a logger to track exceptions in the draw diagram method" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T20:35:19.823", "Id": "515754", "Score": "0", "body": "If you think you've gotten all that you can out of this round, and enough time has passed that it's unlikely you'll get another answer (this is a judgement call on your behalf), then accept whichever answer you think has the highest value and post a new question with your revised code. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T16:19:17.303", "Id": "516089", "Score": "0", "body": "One last question before I accept this answer. What is your thoughts on the argument name \"directory\" for the generate_diagram() function? Is it more appropriately a package?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T16:21:52.320", "Id": "516090", "Score": "0", "body": "Packages are not a thing in Python - it's a module. Just as important as the name is the typehint, in this case `types.ModuleType`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T19:00:35.227", "Id": "261350", "ParentId": "261322", "Score": "1" } } ]
{ "AcceptedAnswerId": "261350", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T06:04:30.783", "Id": "261322", "Score": "3", "Tags": [ "python" ], "Title": "Program that provides diagrams for documentation" }
261322
<p>daily data:</p> <pre><code> ts_code close low 2021-03-10 APPL 6.67 6.66 2021-03-10 AMA 20.24 20.12 2021-03-11 APPL 6.75 6.50 2021-03-11 AMA 21.10 20.40 2021-03-12 AMA 21.31 21.03 2021-03-12 APPL 6.81 6.76 2021-03-15 AMA 21.43 20.95 2021-03-15 APPL 6.74 6.68 2021-03-16 AMA 21.49 21.10 2021-03-16 APPL 6.74 6.67 2021-03-17 APPL 6.67 6.64 2021-03-17 AMA 21.03 20.74 2021-03-18 APPL 6.56 6.51 2021-03-18 AMA 21.56 20.84 2021-03-19 APPL 6.55 6.47 2021-03-19 AMA 20.31 20.21 2021-03-22 AMA 21.38 20.37 2021-03-22 APPL 6.63 6.55 2021-03-23 APPL 6.60 6.54 2021-03-23 AMA 21.06 20.80 2021-03-24 APPL 6.62 6.55 2021-03-24 AMA 20.37 20.29 2021-03-25 AMA 20.59 20.24 2021-03-25 APPL 6.67 6.57 2021-03-26 APPL 6.69 6.64 2021-03-26 AMA 20.98 20.60 2021-03-29 AMA 21.32 21.03 2021-03-29 APPL 6.57 6.54 2021-03-30 AMA 21.76 21.04 2021-03-30 APPL 6.42 6.40 2021-03-31 APPL 6.39 6.33 2021-03-31 AMA 21.84 21.43 2021-04-01 APPL 6.51 6.32 2021-04-01 AMA 21.61 21.33 2021-04-02 AMA 21.33 21.19 2021-04-02 APPL 6.51 6.44 2021-04-06 AMA 21.51 21.34 2021-04-06 APPL 6.60 6.50 2021-04-07 AMA 21.47 21.14 2021-04-07 APPL 6.58 6.52 2021-04-08 AMA 21.39 21.16 2021-04-08 APPL 6.43 6.40 2021-04-09 AMA 21.13 20.92 2021-04-09 APPL 6.40 6.38 2021-04-12 APPL 6.34 6.32 2021-04-12 AMA 20.54 20.47 2021-04-13 APPL 6.34 6.31 2021-04-13 AMA 20.62 20.43 2021-04-14 APPL 6.36 6.28 2021-04-14 AMA 20.51 20.26 2021-04-15 AMA 20.20 19.92 2021-04-15 APPL 6.49 6.32 2021-04-16 APPL 6.69 6.40 2021-04-16 AMA 20.10 19.66 2021-04-19 AMA 20.98 19.75 2021-04-19 APPL 6.68 6.64 2021-04-20 AMA 21.52 20.76 2021-04-20 APPL 6.68 6.64 2021-04-21 APPL 6.58 6.57 2021-04-21 AMA 22.83 22.12 2021-04-22 APPL 6.57 6.56 2021-04-22 AMA 22.80 22.60 2021-04-23 AMA 23.11 22.89 2021-04-23 APPL 6.47 6.44 2021-04-26 APPL 6.36 6.36 2021-04-26 AMA 22.76 22.72 2021-04-27 AMA 22.76 22.68 2021-04-27 APPL 6.34 6.31 2021-04-28 APPL 6.31 6.28 2021-04-28 AMA 23.17 22.60 2021-04-29 AMA 23.41 22.93 2021-04-29 APPL 6.48 6.31 2021-04-30 AMA 23.11 22.83 2021-04-30 APPL 6.33 6.30 </code></pre> <p>Goal: create weekly data</p> <pre><code>logic = { 'low' : 'min', 'close' : 'last'} df_w=df_daily.groupby('ts_code').resample('W').agg({ 'low': 'min', 'close': 'last'}).reset_index().dropna() </code></pre> <p>It works slow when there are many dates and stocks. I don't know which part leads slow.</p> <p>Ref:</p> <ul> <li><a href="https://stackoverflow.com/questions/34597926/converting-daily-stock-data-to-weekly-based-via-pandas-in-python">This post</a> introduces the definition of weekly data and how to convert based on daily data.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:52:12.383", "Id": "515719", "Score": "1", "body": "Can you show your complete code? Snippets like this unfortunately can't give us enough review context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T10:11:23.017", "Id": "515788", "Score": "0", "body": "@Reinderien This is complete code. Run this code, the df_w is what I want. Could you tell which part you think is lacked or unclear?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T02:30:43.897", "Id": "515918", "Score": "1", "body": "`df_daily` is undefined and `logic` is defined but never used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T02:44:44.043", "Id": "515921", "Score": "0", "body": "@RootTwo df_daily is raw data and could not be defined." } ]
[ { "body": "<p><strong>Setup</strong></p>\n<p>I have considered first column as DatetimeIndex looking at the provided data where dates does not have a column name.</p>\n<pre><code>d=&quot;&quot;&quot;date,ts_code,close,low\n2021-03-10,APPL,6.67,6.66\n2021-03-10,AMA,20.24,20.12\n2021-03-11,APPL,6.75,6.50\n2021-03-11,AMA,21.10,20.40\n2021-03-12,AMA,21.31,21.03\n2021-03-12,APPL,6.81,6.76\n2021-03-15,AMA,21.43,20.95\n2021-03-15,APPL,6.74,6.68\n2021-03-16,AMA,21.49,21.10\n2021-03-16,APPL,6.74,6.67\n2021-03-17,APPL,6.67,6.64\n2021-03-17,AMA,21.03,20.74\n2021-03-18,APPL,6.56,6.51\n2021-03-18,AMA,21.56,20.84\n2021-03-19,APPL,6.55,6.47\n2021-03-19,AMA,20.31,20.21\n2021-03-22,AMA,21.38,20.37\n2021-03-22,APPL,6.63,6.55\n2021-03-23,APPL,6.60,6.54\n2021-03-23,AMA,21.06,20.80\n2021-03-24,APPL,6.62,6.55\n2021-03-24,AMA,20.37,20.29\n2021-03-25,AMA,20.59,20.24\n2021-03-25,APPL,6.67,6.57\n2021-03-26,APPL,6.69,6.64\n2021-03-26,AMA,20.98,20.60\n2021-03-29,AMA,21.32,21.03\n2021-03-29,APPL,6.57,6.54\n2021-03-30,AMA,21.76,21.04\n2021-03-30,APPL,6.42,6.40\n2021-03-31,APPL,6.39,6.33\n2021-03-31,AMA,21.84,21.43\n2021-04-01,APPL,6.51,6.32\n2021-04-01,AMA,21.61,21.33\n2021-04-02,AMA,21.33,21.19\n2021-04-02,APPL,6.51,6.44\n2021-04-06,AMA,21.51,21.34\n2021-04-06,APPL,6.60,6.50\n2021-04-07,AMA,21.47,21.14\n2021-04-07,APPL,6.58,6.52\n2021-04-08,AMA,21.39,21.16\n2021-04-08,APPL,6.43,6.40\n2021-04-09,AMA,21.13,20.92\n2021-04-09,APPL,6.40,6.38\n2021-04-12,APPL,6.34,6.32\n2021-04-12,AMA,20.54,20.47\n2021-04-13,APPL,6.34,6.31\n2021-04-13,AMA,20.62,20.43\n2021-04-14,APPL,6.36,6.28\n2021-04-14,AMA,20.51,20.26\n2021-04-15,AMA,20.20,19.92\n2021-04-15,APPL,6.49,6.32\n2021-04-16,APPL,6.69,6.40\n2021-04-16,AMA,20.10,19.66\n2021-04-19,AMA,20.98,19.75\n2021-04-19,APPL,6.68,6.64\n2021-04-20,AMA,21.52,20.76\n2021-04-20,APPL,6.68,6.64\n2021-04-21,APPL,6.58,6.57\n2021-04-21,AMA,22.83,22.12\n2021-04-22,APPL,6.57,6.56\n2021-04-22,AMA,22.80,22.60\n2021-04-23,AMA,23.11,22.89\n2021-04-23,APPL,6.47,6.44\n2021-04-26,APPL,6.36,6.36\n2021-04-26,AMA,22.76,22.72\n2021-04-27,AMA,22.76,22.68\n2021-04-27,APPL,6.34,6.31\n2021-04-28,APPL,6.31,6.28\n2021-04-28,AMA,23.17,22.60\n2021-04-29,AMA,23.41,22.93\n2021-04-29,APPL,6.48,6.31\n2021-04-30,AMA,23.11,22.83\n2021-04-30,APPL,6.33,6.30&quot;&quot;&quot;\ndf=pd.read_csv(StringIO(d))\ndf.date = pd.to_datetime(df.date)\ndf = df.set_index('date')\n</code></pre>\n<p><strong>Setup dataframe</strong></p>\n<pre><code> ts_code close low\ndate \n2021-03-10 APPL 6.67 6.66\n2021-03-10 AMA 20.24 20.12\n2021-03-11 APPL 6.75 6.50\n2021-03-11 AMA 21.10 20.40\n2021-03-12 AMA 21.31 21.03\n... ... ... ...\n2021-04-28 AMA 23.17 22.60\n2021-04-29 AMA 23.41 22.93\n2021-04-29 APPL 6.48 6.31\n2021-04-30 AMA 23.11 22.83\n2021-04-30 APPL 6.33 6.30\n</code></pre>\n<p><strong>Explanation</strong></p>\n<p>We are using <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Grouper.html\" rel=\"nofollow noreferrer\">pd.Grouper</a> which is much faster compared to <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.resample.html\" rel=\"nofollow noreferrer\">resample</a> when used with <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html\" rel=\"nofollow noreferrer\">groupby</a>.</p>\n<p><strong>Solution</strong></p>\n<pre><code>df.groupby(['ts_code', pd.Grouper(level=0, freq='W')]).agg({'low': 'min','close': 'last'}).reset_index()\n</code></pre>\n<p><strong>Ouput Head Sample</strong></p>\n<pre><code> ts_code date low close\n0 AMA 2021-03-14 20.12 21.31\n1 AMA 2021-03-21 20.21 20.31\n2 AMA 2021-03-28 20.24 20.98\n3 AMA 2021-04-04 21.03 21.33\n4 AMA 2021-04-11 20.92 21.13\n5 AMA 2021-04-18 19.66 20.10\n6 AMA 2021-04-25 19.75 23.11\n7 AMA 2021-05-02 22.60 23.11\n8 APPL 2021-03-14 6.50 6.81\n9 APPL 2021-03-21 6.47 6.55\n10 APPL 2021-03-28 6.54 6.69\n11 APPL 2021-04-04 6.32 6.51\n12 APPL 2021-04-11 6.38 6.40\n13 APPL 2021-04-18 6.28 6.69\n14 APPL 2021-04-25 6.44 6.47\n15 APPL 2021-05-02 6.28 6.33\n</code></pre>\n<h2>Performance Comparison</h2>\n<h3>Existing solution with resample</h3>\n<pre><code>%timeit df.groupby('ts_code').resample('W').agg({'low': 'min','close': 'last'}).reset_index().dropna()\n#Output - 23.6 ms ± 2.93 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n</code></pre>\n<h3>Using pd.Grouper</h3>\n<p><strong>Around 3 times faster</strong></p>\n<pre><code>%timeit df.groupby(['ts_code', pd.Grouper(level=0, freq='W')]).agg({'low': 'min','close': 'last'}).reset_index()\n#Output - 7.76 ms ± 403 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n</code></pre>\n<h3>Why is resample slower than pd.Grouper?</h3>\n<p>Let's consider an example to understand the difference between resample and Grouper.(Taken last 4 rows of provided data and added a last row with 1 month diff)</p>\n<p><strong>Sample Data</strong></p>\n<pre><code>d=&quot;&quot;&quot;date,ts_code,close,low\n2021-04-29,AMA,23.41,22.93\n2021-04-29,APPL,6.48,6.31\n2021-04-30,AMA,23.11,22.83\n2021-04-30,APPL,6.33,6.30\n2021-05-30,APPL,6.33,6.30&quot;&quot;&quot;\ndf = pd.read_csv(StringIO(d))\ndf.date = pd.to_datetime(df.date)\ndf = df.set_index('date')\ndf\n\n\n ts_code close low\ndate \n2021-04-29 AMA 23.41 22.93\n2021-04-29 APPL 6.48 6.31\n2021-04-30 AMA 23.11 22.83\n2021-04-30 APPL 6.33 6.30\n2021-05-30 APPL 6.33 6.30\n</code></pre>\n<p><strong>When resampling using resample for weekly freq</strong></p>\n<pre><code>df.groupby('ts_code').resample('W').agg({'low': 'min','close': 'last'}).reset_index()\n</code></pre>\n<p><strong>Output</strong></p>\n<pre><code> ts_code date low close\n0 AMA 2021-05-02 22.83 23.11\n1 APPL 2021-05-02 6.30 6.33\n2 APPL 2021-05-09 NaN NaN\n3 APPL 2021-05-16 NaN NaN\n4 APPL 2021-05-23 NaN NaN\n5 APPL 2021-05-30 6.30 6.33\n</code></pre>\n<p><strong>Using pd.Groupby</strong></p>\n<pre><code>df.groupby(['ts_code', pd.Grouper(level=0, freq='W')]).agg({'low': 'min','close': 'last'}).reset_index()\n</code></pre>\n<p><strong>Output</strong></p>\n<pre><code> ts_code date low close\n0 AMA 2021-05-02 22.83 23.11\n1 APPL 2021-05-02 6.30 6.33\n2 APPL 2021-05-30 6.30 6.33\n</code></pre>\n<p><strong>Explanation</strong></p>\n<p>As we can see the difference in output of resample and Grouper, resample samples the data including the missing frequencies(weekly) and add NaN to the values whereas Grouper is concerned only about grouping the provided data and sampling it to provided freq hence Grouper has less work, specific data to deal thus faster.</p>\n<p>In this question we were able to use Grouper since you were dropping na at the end but when we want to resample the data and need all the rows including the NaNs then we will have to use resample.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T18:56:42.740", "Id": "515996", "Score": "2", "body": "To my eyes and a couple other users, your post has one insightful observation. As such we have removed the comment from the other user and undeleted your answer. I'm sorry for any confusion around your post. Please feel free to ping me if you have any problems with your post henceforth." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T23:58:13.710", "Id": "516030", "Score": "0", "body": "@Uts Great,but would you mind explaining why pd.Grouper is faster?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T04:14:01.763", "Id": "516046", "Score": "2", "body": "@Jack explanation added to the solution." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T08:50:33.303", "Id": "261457", "ParentId": "261324", "Score": "6" } } ]
{ "AcceptedAnswerId": "261457", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T08:32:08.203", "Id": "261324", "Score": "0", "Tags": [ "python", "pandas" ], "Title": "create weekly data for stocks faster based on daily data" }
261324
<p>I have some Python code that runs as part of an Azure Synapse Analytics Apache Spark Notebook (or Synapse Notebook) and would like to add effective error handling. The code simply executes a given SQL script against the database. The code runs but I sometimes see errors like <code>attempt to use closed connection</code>. I would like to do the following:</p> <ul> <li>Improve code that I wrote through peer review</li> <li><s>Can I improve the error handling? eg pseudo-code <code>if connection still open close connection</code></s></li> <li><s>The code using SQL auth works. I would like to authenticate as the Managed Identity, I've tried using the object id of the MI in the connection string with <code>Authentication=ActiveDirectoryMsi</code> but it didn't work</s></li> </ul> <h2>Cell1 - parameters</h2> <pre><code>pAccountName = 'someStorageAccount' pContainerName = 'someContainer' pRelativePath = '/raw/sql/some_sql_files/' pFileName = 'someSQLscript.sql' </code></pre> <h1>Cell 2 - main</h1> <pre><code>import pyodbc from pyspark import SparkFiles try: # Add the file to the cluster so we can view it sqlFilepath = f&quot;&quot;&quot;abfss://{pContainerName}&quot;&quot;&quot; + &quot;@&quot; + f&quot;&quot;&quot;{pAccountName}.dfs.core.windows.net{pRelativePath}{pFileName}&quot;&quot;&quot; sc.addFile(sqlFilepath, False) # Open the file for reading with open(SparkFiles.getRootDirectory() + f'/{pFileName}', 'r') as f: lines = f.read() ## read all text from a file into a string # Open the database connection conn = pyodbc.connect( 'DRIVER={ODBC Driver 17 for SQL Server};' 'SERVER=someServer.sql.azuresynapse.net;' 'DATABASE=someDatabase;UID=batchOnlyUser;' 'PWD=youWish;', autocommit = True ) # Split the script into batches separated by &quot;GO&quot; for batch in lines.split(&quot;GO&quot;): conn.execute(batch) # execute the SQL statement except: raise finally: # Tidy up conn.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T14:25:11.433", "Id": "515703", "Score": "1", "body": "Can you show an example of what someSQLscript contains?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T14:41:58.787", "Id": "515704", "Score": "0", "body": "It could be any sql script really, so anything from just `select @@version` to big create table, insert statements etc" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T14:43:28.647", "Id": "515705", "Score": "0", "body": "Welcome to the Code Review Community. We can review the code and make suggestions on how to improve it. We can't help you write new code or debug the code. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask). At least 2 things are making the question off-topic, the first is that your valid concerns about security are making you use generic names. The second is that `Authentication=ActiveDirectoryMsi` doesn't work. We can only review working code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:17:35.860", "Id": "515713", "Score": "1", "body": "@pacmaninbw Per e.g. https://codereview.meta.stackexchange.com/a/696/25834 I don't see the generic names as a problem, and it's common practice to omit or change credentials; that on its own is not a reason for closure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T16:38:30.697", "Id": "515733", "Score": "1", "body": "Welcome to Code Review! The current question title, asks for code to be written, which is off-topic for Code Review. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T18:51:42.890", "Id": "515748", "Score": "0", "body": "So if I change it to “Review error handling...” instead of “Add effective ...” would that help?" } ]
[ { "body": "<p>Ignoring your closed-connection and managed-identity questions, since (a) I don't know how to answer them and (b) on their own they're off topic, there is still review to be done:</p>\n<ul>\n<li>A Pythonic way to tell the standard library to format your URI instead of you doing it yourself is to call into <code>urlunparse</code></li>\n<li>Consider using <code>pathlib</code></li>\n<li><code>connect</code> accepts kwargs as an alternative to the conn string, and the former will lay out your connection parameters more nicely</li>\n<li><code>except / raise</code> is redundant and should be deleted</li>\n<li>Your <code>try</code> starts too early and should only start <em>after</em> the connection has been established</li>\n<li>You're not reading a lines list; you're reading content, which would be a better variable name</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>from pathlib import Path\nfrom urllib.parse import urlunparse, ParseResult\nimport pyodbc\nfrom pyspark import SparkFiles\n\n\npAccountName = 'someStorageAccount'\npContainerName = 'someContainer'\npRelativePath = '/raw/sql/some_sql_files/'\npFileName = 'someSQLscript.sql'\n\n# Add the file to the cluster so we can view it\nsql_filename = urlunparse(\n ParseResult(\n scheme='abfss',\n netloc=f'{pContainerName}@{pAccountName}.dfs.core.windows.net',\n path=f'{pRelativePath}{pFileName}',\n params=None, query=None, fragment=None,\n )\n)\n\nsc.addFile(sql_filename, False)\n\n# Open the file for reading\nsql_file_path = Path(SparkFiles.getRootDirectory()) / pFileName\nwith sql_file_path.open() as f:\n content = f.read()\n\n# Open the database connection\nconn = pyodbc.connect(\n DRIVER='{ODBC Driver 17 for SQL Server}',\n SERVER='someServer.sql.azuresynapse.net',\n DATABASE='someDatabase',\n UID='batchOnlyUser',\n PWD='youWish',\n autocommit=True,\n)\n\ntry:\n # Split the script into batches separated by &quot;GO&quot;\n for batch in content.split(&quot;GO&quot;):\n conn.execute(batch) # execute the SQL statement\nfinally:\n conn.close()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:45:58.417", "Id": "515716", "Score": "1", "body": "ok useful, thank you. I'm going to leave it open for a few days but have upvoted and will consider marking as answer later." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:37:58.603", "Id": "261341", "ParentId": "261325", "Score": "1" } } ]
{ "AcceptedAnswerId": "261341", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T09:34:26.110", "Id": "261325", "Score": "0", "Tags": [ "python", "azure" ], "Title": "Add effective error handling to Python Notebook in Azure Synapse Analytics" }
261325
<p>The code's gonna be pretty simple and YES, I do know, what a proper UUID4 implementation is and what are possible approaches to implement RFC 4122.</p> <p>But somewhere there exists a small piece of software, where possible dependencies should be minified if possible. Because of this and some other reason let's consider the following UUID generator:</p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;random&gt; static std::string generate_uuid(size_t len) { static const char x[] = &quot;0123456789abcdef&quot;; std::string uuid; uuid.reserve(len); std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution &lt; &gt; dis(0, sizeof(x) - 2); for (size_t i = 0; i &lt; len; i++) uuid += x[dis(gen)]; return uuid; } </code></pre> <p>The output of the function is to be used in cases when some unique ID is required for a custom storage. Like &quot;here we put this data, and there is its 16-byte ID&quot;, meaning it would be enough if collisions are just &quot;not likely at all, like winning a lottery twice in a row&quot;.</p> <p>As far as modern C++ has improved random utils, it seemed a not-so-bad custom solution, but now I'm not that sure.</p> <p>What would you say? Thanks in advance</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T12:46:16.333", "Id": "515691", "Score": "1", "body": "UUID is just a 16 byte number. Why not simply compose two 64bit random numbers? Why do you treat it as a string? Also I heard somewhere that some of it's indexes have special meaning - like who generated it or something." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T00:25:51.390", "Id": "515762", "Score": "0", "body": "Note that the below answers are good if you just want to learn C++. You should never use such a uuid in a real production system, because the random number generator is not creating unique numbers. Random is not the same as unique or even likely unique." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T01:59:27.893", "Id": "515766", "Score": "2", "body": "NoNoNoNo. When people print out UUID they print out the hex version because otherwise it is not \"very\" human-readable. You should treat them as numbers internally just have a mechanism for printing them in hex (like overload the operator<< for your UUID type). Building a random number generator every time can be very expensive (at least make those static members of the function). Why not have a time component. Much more likely you are not going to clash (assuming time portion is large). then have the random part as the differentiator from UUID generated on the same second/millisecond." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T14:44:23.577", "Id": "515802", "Score": "0", "body": "Looking at the versions of UUID (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions) I can't see any version that would match your code. Assuming that is correct, this isn't a UUID generator. It could still be a way to generate a pseudo-random string, but please don't call it UUID." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T19:02:59.307", "Id": "515902", "Score": "0", "body": "All those considerations about the code quality are definitely true, it IS a rather simplified version and the random generator constructor is not a performance issue in my case even slightly. But what I really badly need to know is -- can I rely on the randomness of the resulting string? An important question is -- if I would need those IDs to be an unique key in my storage, would this version be sufficient? I HAVE mentioned that have seen the RFC for uuid, but not in strict theory -- will my code work in practice?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T10:52:46.257", "Id": "520471", "Score": "0", "body": "I'd say that as long as you're using `std::mt19937` which isn't a cryptographically secure random number generator, this is a failed attempt. You should not be able to predict next ID's given any set of IDs. You say that you know what a UUID is, but for some reason you don't format it as one, without indication **why**. If the length is too small then it may not be as unique as you might expect. The length is also specified in hex instead of binary, which is confusing to say the least." } ]
[ { "body": "<p>You forgot to include <code>&lt;string&gt;</code>, and misspelt <code>std::size_t</code> (twice).</p>\n<p>Since this doesn't create a RFC-4122-compliant UUID, I would change the name so it doesn't get used where it shouldn't. Perhaps <code>create_random_id()</code> or similar?</p>\n<p>I don't like the name <code>x</code> for the digit string - I'd prefer something more descriptive like <code>hex_chars</code> or even just <code>hex</code>.</p>\n<hr />\n<p>We could consider constructing a string that's already long enough, then setting all its characters:</p>\n<pre><code>std::string uuid(len, '\\0');\nfor (auto&amp; c: uuid) {\n c = x[dis(gen)];\n}\n</code></pre>\n<p>Or perhaps replace the loop with a standard algorithm:</p>\n<pre><code>std::string uuid;\nuuid.reserve(len);\nstd::generate_n(std::back_inserter(uuid), len,\n [&amp;]{ return x[dis(gen)]; });\n</code></pre>\n<p>Though I don't think that's necessarily clearer.</p>\n<hr />\n<p>Going a little over the top, we could make a general select-from-collection function and use that:</p>\n<pre><code>template&lt;std::ranges::sized_range C, class G&gt;\nauto sample_from(C const&amp; collection, G&amp;&amp; generator)\n{\n std::uniform_int_distribution&lt;typename C::size_type&gt; dis{0, std::ranges::size(collection) - 1};\n return collection[dis(generator)];\n}\n</code></pre>\n<p>⋮</p>\n<pre><code> static const std::string_view hex_chars = &quot;0123456789abcdef&quot;;\n std::generate_n(std::back_inserter(uuid), len,\n [&amp;]{ return sample_from(hex_chars, gen); });\n</code></pre>\n<hr />\n<p>We might even make a custom input-iterator for selecting random characters:</p>\n<pre><code>class random_char_source\n{\n const std::string chars;\n std::mt19937 generator;\n std::uniform_int_distribution&lt;std::size_t&gt; distribution;\n\npublic:\n using iterator_category = std::input_iterator_tag;\n using value_type = char;\n using difference_type = int;\n using pointer = const char*;\n using reference = const char&amp;;\n\n explicit random_char_source(std::string chars, std::random_device::result_type seed = std::random_device{}())\n : chars{std::move(chars)},\n generator{seed},\n distribution{0, this-&gt;chars.size() - 1}\n {}\n\n // it's an input iterator\n char operator*() { return chars[distribution(generator)]; }\n random_char_source&amp; operator++() { return *this; }\n};\n</code></pre>\n<p>That makes our ID generator very simple:</p>\n<pre><code>static std::string generate_random_id(std::size_t len)\n{\n auto hex_chars = random_char_source{&quot;0123456789abcdef&quot;};\n\n std::string uuid;\n uuid.reserve(len);\n std::copy_n(hex_chars, len, std::back_inserter(uuid));\n return uuid;\n}\n</code></pre>\n<hr />\n<p>However, for generating power-of-two numbers, and since we have a UniformRandomBitGenerator (the <code>std::mt19937</code> object), we can extract bits directly:</p>\n<pre><code>static std::string random_id(std::size_t len)\n{\n static const std::string_view hex_chars = &quot;0123456789abcdef&quot;;\n using Generator = std::mt19937;\n\n Generator gen{std::random_device{}()};\n\n std::string uuid;\n uuid.reserve(len);\n\n while (uuid.size() &lt; len) {\n auto n = gen();\n for (auto i = Generator::max(); i &amp; 0x8 &amp;&amp; uuid.size() &lt; len; i &gt;&gt;= 4) {\n uuid += hex_chars[n &amp; 0xf];\n n &gt;&gt;= 4;\n }\n }\n\n return uuid;\n}\n</code></pre>\n<p>You could probably make a simpler and more readable version of that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T02:02:14.930", "Id": "515767", "Score": "1", "body": "You should make the generator static. I believe it is expensive to initialize. Once initialized can be reused indefinitely." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T19:11:13.917", "Id": "515904", "Score": "0", "body": "Wow, thanks! Could I clarify just one thing -- would any of the following be enough to rely on it as something random enough to most likely not have collisions? (uniqueness on large scales is gonna be somewhat important) Seems like \"yes\", just wanted to be sure" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T19:22:33.720", "Id": "515905", "Score": "0", "body": "I don't think there's anything to reduce the randomness, so the average number of ids generated before the first collision will be 2 ^ (len/2). You can obviously tune the length for the amount of collision-resistance you need." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T13:03:47.573", "Id": "261329", "ParentId": "261326", "Score": "6" } }, { "body": "<p>I agree it's odd to generate random hex digits directly, rather than just formatting a few large ints as hex. Unlike Toby's code though, I think it would be simpler to use library code to format the random integers into hex. If you append too many digits, just truncate the string. <a href=\"https://en.cppreference.com/w/cpp/utility/to_chars\" rel=\"nofollow noreferrer\">to_chars</a> in C++17 is <em>very efficient</em> but a little harder to use.</p>\n<p>But in this code:</p>\n<p><code>static const char x[] = &quot;0123456789abcdef&quot;;</code><br />\nUse <code>constexpr</code>.</p>\n<p><code>sizeof(x)</code><br />\nDon't use <code>sizeof</code> on arrays to get the element count. This is easy to get wrong and if the definition of <code>x</code> changes then it will silently do the wrong thing. <code>std::size(x)</code> works here, as do a number of other standard library mechanisms.</p>\n<p>Do you only need one random ID, or one every once in a long while? OK. But if you're calling this repeatedly, you're doing the expensive overhead of initializing the random number generator to a &quot;true&quot; random number, each time. It would be better to make a factory class that holds the random number generator, initialized in the constructor.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T08:53:53.253", "Id": "515784", "Score": "1", "body": "`std::to_chars()` is quite awkward because you need to insert any leading zeros yourself. There's a possible case for `std::sprintf()` here, though you'll need to work out how many digits are usable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T19:09:10.570", "Id": "515903", "Score": "0", "body": "Thanks! Just a side note -- compared with the rest of the code, that constructor costs almost nothing in the case, though making it static or something is a good idea, yes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T13:50:33.283", "Id": "516083", "Score": "0", "body": "@TobySpeight If you append the full result of `sprintf`, drop out of the loop if the string is now long enough, and finally truncate the string if it's too long." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T14:50:15.427", "Id": "261336", "ParentId": "261326", "Score": "4" } } ]
{ "AcceptedAnswerId": "261329", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T11:30:01.717", "Id": "261326", "Score": "4", "Tags": [ "c++", "random", "c++17" ], "Title": "Custom UUID implementation on C++" }
261326
<p>Anybody mind providing an opinion on whether or not this is a good or bad example of Task Cancellation and why. I have my own opinion and I've been told that its baseless, just trying to find out who is off base. I don't think its me, but I am okay with it being me. I just need to know its me so I can evolve if required.</p> <pre class="lang-cs prettyprint-override"><code>class Program { static void Main() { ImportSource(); Console.ReadKey(); } public static void ImportSource() { var cancellationTokenSource = new CancellationTokenSource(); var token = cancellationTokenSource.Token; var task1 = Task.Run(() =&gt; Import(token), token); Thread.Sleep(500); // if we attempt to cancel the token CancelToken(cancellationTokenSource); } public static void CancelToken(CancellationTokenSource cancellationTokenSource) { Console.WriteLine(&quot;Cancellation in process!&quot;); cancellationTokenSource.Cancel(); } static void Import(CancellationToken token) { int i = 0; do { Thread.Sleep(100); // check if the token is cancelled if (token.IsCancellationRequested) { Console.WriteLine(&quot;Token was cancelled&quot;); break; } else { Console.WriteLine(&quot;Importing data is in process!&quot;); Import(token); i++; } } while (i &lt; 1); } } </code></pre> <p><b>EDIT:</b> Moved my last comment into body since trying not to influence the opinions isn't allowing for any traction. Here is where I am at with this code:</p> <p>My biggest problem with the above code is that its not a good example of recursive+iterative cancellation. If you entirely delete the do loop, you get identical results and have a decent recursive cancellation example. On the other hand, the loop implementation could change to i&lt;10, the recursive call could just be deleted and then you would have a decent example of iterative cancellation.</p> <p>So, how could this be modified to be a very clear and meaningful example of both recursive+iteration cancellation, but still keep it as minimal as possible?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T12:26:54.887", "Id": "515690", "Score": "1", "body": "1) Is this code you've written yourself? 2) If so, could you elaborate on what you think is the problem/ what area you're looking for feedback on - i.e. what does this code even do - what's the context. See https://codereview.stackexchange.com/help/on-topic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T18:01:45.333", "Id": "515740", "Score": "0", "body": "I want an unfiltered opinion of what you would think if I proposed the above program (which functions) as a \"Task Cancellation Example\". I have intentionally left out who wrote it and what my opinions are until I get some answers. I will eventually provide that, I just don't want to influence opinions at this point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T08:15:03.347", "Id": "515943", "Score": "0", "body": "The academic answer: it depends. For example from the cooperative perspective it can be considered as good example. On the other hand from consequent / consistent point of view is bad because it's mixing `Thread`s and `Task`s. So, from what perspective are you looking for assessment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T10:12:24.977", "Id": "515953", "Score": "1", "body": "From a demonstration perspective, which is exactly what this code is representing, I didn't even considered the mingling of Thread & Task as a problem. I will investigate the Task.Delay as a more coherent implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T10:24:54.860", "Id": "515955", "Score": "1", "body": "The question still stands. What do you want to demonstrate with/about CancellationToken? The primary use case? The core concept? The chaining ability? The transfer for all the way down? The exception handling? The `Register` functionality? The `CanBeCanceled` usage? etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T06:20:22.250", "Id": "516051", "Score": "0", "body": "@Bogatitus Sorry but I'm a bit confused with this *example of both recursive+iteration cancellation* . An algorithm is usually either iterative or recursive. Are you looking for 2 examples?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T09:12:55.770", "Id": "516060", "Score": "1", "body": "Your confusion is understandable and the answer may be that 2 examples are required, but I was wanting to know if its possible to do both in a clear way. IE, threads being as unpredictable as they are, an ideal example would potentially terminate within the loop check or a recursive check, but not exclusively like the current example does." } ]
[ { "body": "<p>Let me share with you my revised version in two parts.</p>\n<h2>First part</h2>\n<pre><code>static async Task Main()\n{\n Console.WriteLine(&quot;Application has been started&quot;);\n\n var cancellationSignal = new CancellationTokenSource();\n\n StartLongRunningOperationInBackground(cancellationSignal.Token);\n await CancelLongRunningOperationAfter(cancellationSignal);\n\n Console.WriteLine(&quot;Application has been finished&quot;);\n}\n\npublic static void StartLongRunningOperationInBackground(CancellationToken token)\n{\n _ = Task.Run(() =&gt; LongRunningIterativeOperation(token), token);\n\n Console.WriteLine(&quot;Long running operation has been started&quot;);\n}\n\npublic static async Task CancelLongRunningOperationAfter(CancellationTokenSource cancellationTokenSource, int cancelAfterInMs = 500)\n{\n await Task.Delay(cancelAfterInMs);\n cancellationTokenSource.Cancel();\n \n Console.WriteLine(&quot;Cancellation has been requested&quot;);\n}\n</code></pre>\n<h3>Changes</h3>\n<ul>\n<li>I've moved the declaration of the <code>CancellationTokenSource</code> to the <code>Main</code>\n<ul>\n<li>With that the cooperative nature of cancellation tokens are more clear</li>\n</ul>\n</li>\n<li>I've renamed the <code>ImportSource</code> to <code>StartLongRunningOperationInBackground</code>\n<ul>\n<li>I do believe that profound naming can help eligibility and understanding</li>\n</ul>\n</li>\n<li>I've moved the waiting before the cancellation request into the <code>CancelLongRunningOperationAfter</code>\n<ul>\n<li>I think it increases cohesion because cancellation should be done after that period of time</li>\n<li>So, they belong together</li>\n</ul>\n</li>\n<li>I've discarded the result of the <code>Task.Run</code>\n<ul>\n<li>This is a fairly common way to express <em>fire and forget</em></li>\n</ul>\n</li>\n</ul>\n<h2>Second part</h2>\n<pre><code>private const int maxSteps = 100;\nstatic void LongRunningIterativeOperation(CancellationToken token)\n{\n for (int currentStep = 0; currentStep &lt; maxSteps; currentStep++)\n {\n //Simulate computation intensive code\n Thread.Sleep(100);\n\n token.ThrowIfCancellationRequested();\n\n //Simulate progress report\n Console.WriteLine($&quot;Done: {currentStep + 1} / {maxSteps}&quot;);\n }\n}\n\nstatic void LongRunningRecursiveOperation(CancellationToken token, int currentStep = 0)\n{\n if (currentStep == maxSteps) return;\n\n token.ThrowIfCancellationRequested();\n\n //Simulate computation intensive code\n Thread.Sleep(100);\n\n //Simulate progress report\n Console.WriteLine($&quot;Done: {currentStep + 1} / {maxSteps}&quot;);\n\n LongRunningRecursiveOperation(token, currentStep + 1);\n}\n</code></pre>\n<h3>Changes</h3>\n<ul>\n<li>I've created two versions of the same method\n<ul>\n<li>One which demonstrates the iterative approach</li>\n<li>And another which does the same but in a recursive fashion</li>\n</ul>\n</li>\n<li>I've used <code>ThrowIfCancellationRequested</code> instead of checking the <code>IsCancellationRequested</code>\n<ul>\n<li>If we don't need to do any cleanup then <code>ThrowIfCancellationRequested</code> is more cleaner solution</li>\n</ul>\n</li>\n<li>I've used <code>Thread.Sleep</code> here intentionally\n<ul>\n<li>This is a blocking operation, which can be used to simulate CPU bound operation</li>\n<li>It is in alignment with <code>Task.Run</code>, which is designed for CPU bound operations</li>\n</ul>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T14:39:49.897", "Id": "516085", "Score": "1", "body": "Thank you Peter. FYI, I've been awake for about 22 hours and still have 7 more hours of obligations that have to be done today. I will analyze this as soon as I can, but it certainly looks interesting and I really appreciate the detailed explanations. Based on my quick review, are we are going with the theory that directly mangling the 2 types together with equal cancellation opportunity would generally be a bad use of the TPL? IE, I should pick a lane and parallelize that unit of work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T07:52:54.327", "Id": "516118", "Score": "0", "body": "@Bogatitus To be honest with you I don't get your question. Could you please rephrase it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T20:58:50.493", "Id": "516166", "Score": "1", "body": "Peter, those were very nice explanations and I learned a number of things from you. I think I'll end my quest to generically put both iterative and recursive cancellation \"work\" into the same task. I believe it is possible to demo them concurrently, but maybe not without one of them doing some degree of non-theoretical work." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T09:58:57.413", "Id": "261503", "ParentId": "261327", "Score": "0" } } ]
{ "AcceptedAnswerId": "261503", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T11:36:35.667", "Id": "261327", "Score": "1", "Tags": [ "c#", "multithreading", "task-parallel-library" ], "Title": "What is wrong with this CancellationTokenSource example" }
261327
<p>I have a legacy winForms application that now I'm in charge of maintaining and developing. This app has a lot of singleton instance.... Some are very similar to service that wrap other component or class other instead wrap some entities to making a cache-like pattern</p> <p>This is an example of this cached class</p> <pre><code>public class SingletonCycle { private static Cycle _instance; private static DevExpress.RackManager.RackManager _rackManager; public static event EventHandler&lt;Cycle&gt; OnCycleUpdated; private static void RaiseOnCycleUpdated(Cycle cycle) { OnCycleUpdated?.Invoke(cycle, cycle); } public static Cycle GetInstance() { return _instance; } public static void SetCycleInstance(Cycle cycle) { if (_instance != null) { SingletonAuditTrail.GetInstance().ModifiedCycle(cycle); } else { SingletonAuditTrail.GetInstance().StartCycle(cycle); } _instance = cycle; _instance.CreationDate = DateTime.Now; _instance.Operator = CommonUIManager.GetInstance().GetConfig().GetCurrentUser; SaveCycle(); } } </code></pre> <p>Because I want to test some part of the software I want to transform all this singleton in service that will be registered in container as singleton Lifestyle. The problem is that all this services are spread out in all the software and for now I can't use everywhere constructor injection because i can't put all the classes inside container. For now I try to use the container as static and everywhere use it instead of every singleton instances</p> <p><strong>Are there any problems of using container instead static singleton? Can you suggest some other advice to replace effectively singleton?</strong></p> <p>Only as an example to explain....This is my first try example of this implementation with DI and simpleInjector</p> <p>Register container in the static Main</p> <pre><code>public static Container Container { get; private set; } static void Main() { ........ var crpConfig = SingletonCrpCompactConfig.GetInstance(); var container = new Container(); container.Register(typeof(UnitOfWorkManager), CreateUOWManager(crpConfig), Lifestyle.Singleton); container.Register(typeof(RecipeModuleCache), CreateRecipeModuleCache(crpConfig, container), Lifestyle.Singleton); container.Verify(); Container = container; ...... } private static Func&lt;object&gt; CreateUOWManager(CrpCompactConfig crpConfig) { return () =&gt; new UnitOfWorkManager(crpConfig.ConnectionString); } private static Func&lt;object&gt; CreateRecipeModuleCache(CrpCompactConfig crpConfig, Container container) { return () =&gt; { var uowManager = container.GetInstance&lt;UnitOfWorkManager&gt;(); var cache = new RecipeModuleCache(crpConfig, uowManager); return cache; }; } </code></pre> <p>Example of the service to be registered inside the container</p> <pre><code>public class RecipeModuleCache { private readonly CrpCompactConfig _config; private readonly UnitOfWorkManager _uow; private CrpCompactRecipeModule _instance; private bool _cached; public RecipeModuleCache(CrpCompactConfig config, UnitOfWorkManager uow) { _config = config; _uow = uow; } public CrpCompactRecipeModule GetCached() { if (_cached) return _instance; _instance = StaticBuilders.Create(_uow); _cached = true; return _instance; } public void Invalidate() { _instance = null; _cached = false; } } </code></pre> <p>So when there is the singleton i use instead</p> <pre><code>Program.Container.GetInstance&lt;RecipeModuleCache&gt;() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T12:55:44.890", "Id": "261328", "Score": "1", "Tags": [ "c#", "design-patterns", "dependency-injection", "simple-injector" ], "Title": "Replace SingletonPattern by using IOC Container based architecture" }
261328
<p>I have the following data bindings set up:</p> <pre class="lang-xml prettyprint-override"><code>&lt;DataGrid x:Name=&quot;dataGridReflections&quot; Width=&quot;auto&quot; MaxWidth=&quot;1570&quot; HorizontalContentAlignment=&quot;Center&quot; AutoGenerateColumns=&quot;False&quot; SelectionMode=&quot;Single&quot; HorizontalScrollBarVisibility=&quot;Hidden&quot; VerticalScrollBarVisibility=&quot;Hidden&quot; Margin=&quot;0,0,240,0&quot;&gt; &lt;DataGrid.RowStyle&gt; &lt;Style TargetType=&quot;DataGridRow&quot;&gt; &lt;Setter Property=&quot;Foreground&quot; Value=&quot;{Binding ColourSet}&quot;/&gt; &lt;Setter Property=&quot;FontSize&quot; Value=&quot;{Binding FontSize}&quot;/&gt; &lt;Setter Property=&quot;FontWeight&quot; Value=&quot;{Binding FontWeight}&quot;/&gt; &lt;Setter Property=&quot;HorizontalContentAlignment&quot; Value=&quot;Center&quot; /&gt; &lt;Setter Property=&quot;HorizontalAlignment&quot; Value=&quot;Center&quot;/&gt; &lt;/Style&gt; &lt;/DataGrid.RowStyle&gt; &lt;DataGrid.ColumnHeaderStyle&gt; &lt;Style TargetType=&quot;{x:Type DataGridColumnHeader}&quot;&gt; &lt;Setter Property=&quot;FontWeight&quot; Value=&quot;Bold&quot; /&gt; &lt;Setter Property=&quot;HorizontalAlignment&quot; Value=&quot;Stretch&quot; /&gt; &lt;Setter Property=&quot;HorizontalContentAlignment&quot; Value=&quot;Center&quot; /&gt; &lt;Setter Property=&quot;FontSize&quot; Value=&quot;16&quot;/&gt; &lt;/Style&gt; &lt;/DataGrid.ColumnHeaderStyle&gt; &lt;DataGrid.Columns&gt; &lt;DataGridTextColumn Header=&quot;Bearing (PLL)&quot; Width=&quot;*&quot; MaxWidth=&quot;221&quot; Binding=&quot;{Binding BearingPLL, Mode=OneWay}&quot;&gt; &lt;DataGridTextColumn.ElementStyle&gt; &lt;Style TargetType=&quot;TextBlock&quot;&gt; &lt;Setter Property=&quot;HorizontalAlignment&quot; Value=&quot;Center&quot;/&gt; &lt;/Style&gt; &lt;/DataGridTextColumn.ElementStyle&gt; &lt;/DataGridTextColumn&gt; &lt;DataGridTextColumn Header=&quot;Bearing (°)&quot; Width=&quot;*&quot; MaxWidth=&quot;221&quot; Binding=&quot;{Binding BearingDegrees, Mode=OneWay}&quot;&gt; &lt;DataGridTextColumn.ElementStyle&gt; &lt;Style TargetType=&quot;TextBlock&quot;&gt; &lt;Setter Property=&quot;HorizontalAlignment&quot; Value=&quot;Center&quot;/&gt; &lt;/Style&gt; &lt;/DataGridTextColumn.ElementStyle&gt; &lt;/DataGridTextColumn&gt; &lt;DataGridTextColumn Header=&quot;Subtended (PLL)&quot; Width=&quot;*&quot; MaxWidth=&quot;221&quot; Binding=&quot;{Binding SubtendPLL, Mode=OneWay}&quot;&gt; &lt;DataGridTextColumn.ElementStyle&gt; &lt;Style TargetType=&quot;TextBlock&quot;&gt; &lt;Setter Property=&quot;HorizontalAlignment&quot; Value=&quot;Center&quot;/&gt; &lt;/Style&gt; &lt;/DataGridTextColumn.ElementStyle&gt; &lt;/DataGridTextColumn&gt; &lt;DataGridTextColumn Header=&quot;Subtended (°)&quot; Width=&quot;*&quot; MaxWidth=&quot;221&quot; Binding=&quot;{Binding SubtendDegrees}&quot;&gt; &lt;DataGridTextColumn.ElementStyle&gt; &lt;Style TargetType=&quot;TextBlock&quot;&gt; &lt;Setter Property=&quot;HorizontalAlignment&quot; Value=&quot;Center&quot;/&gt; &lt;/Style&gt; &lt;/DataGridTextColumn.ElementStyle&gt; &lt;/DataGridTextColumn&gt; &lt;DataGridTextColumn Header=&quot;Range&quot; Width=&quot;*&quot; MaxWidth=&quot;221&quot; Binding=&quot;{Binding Range, Mode=OneWay}&quot;&gt; &lt;DataGridTextColumn.ElementStyle&gt; &lt;Style TargetType=&quot;TextBlock&quot;&gt; &lt;Setter Property=&quot;HorizontalAlignment&quot; Value=&quot;Center&quot;/&gt; &lt;/Style&gt; &lt;/DataGridTextColumn.ElementStyle&gt; &lt;/DataGridTextColumn&gt; &lt;DataGridTextColumn Header=&quot;Intensity&quot; Width=&quot;*&quot; MaxWidth=&quot;221&quot; Binding=&quot;{Binding Intensity, Mode=OneWay}&quot;&gt; &lt;DataGridTextColumn.ElementStyle&gt; &lt;Style TargetType=&quot;TextBlock&quot;&gt; &lt;Setter Property=&quot;HorizontalAlignment&quot; Value=&quot;Center&quot;/&gt; &lt;/Style&gt; &lt;/DataGridTextColumn.ElementStyle&gt; &lt;/DataGridTextColumn&gt; &lt;DataGridTextColumn Header=&quot;Time&quot; Width=&quot;*&quot; MaxWidth=&quot;221&quot; Binding=&quot;{Binding Time, Mode=OneWay}&quot;&gt; &lt;DataGridTextColumn.ElementStyle&gt; &lt;Style TargetType=&quot;TextBlock&quot;&gt; &lt;Setter Property=&quot;HorizontalAlignment&quot; Value=&quot;Center&quot;/&gt; &lt;/Style&gt; &lt;/DataGridTextColumn.ElementStyle&gt; &lt;/DataGridTextColumn&gt; &lt;/DataGrid.Columns&gt; &lt;/DataGrid&gt; </code></pre> <p>Which is linked in the code behind as such:</p> <pre class="lang-cs prettyprint-override"><code>private void UpdateUserInterface() { if (ReflectionsReported != null) ReflectionsReported.Clear(); ReflectionList reflectionDatas; for (ReflectionCount = 0; ReflectionCount &lt; SmallestArray(); ReflectionCount++) { reflectionDatas = new(ReflectionCount); ReflectionsReported.Add(reflectionDatas); } labelMarkers.Content = Reflections.Revolution[(int)Reflections.Data.Marker][0]; labelReflections.Content = dataGridReflections.Items.Count; } </code></pre> <p>And the ReflectionsList is defined as:</p> <pre class="lang-cs prettyprint-override"><code>public ReflectionList(int i) : base() { ColourSet = ReflectionsUC.normal; FontWeight = FontWeights.Normal; ReflectionData reflr = new() { BearingPLL = Reflections.Revolution[(int)Reflections.Data.Bearing][i], BearingDegrees = Math.Round((decimal)Convert.ToInt32(Reflections.Revolution[(int)Reflections.Data.Bearing][i]) / 65536 * 360, 3), SubtendPLL = Reflections.Revolution[(int)Reflections.Data.Subtend][i], SubtendDegrees = Math.Round((decimal)Convert.ToInt32(Reflections.Revolution[(int)Reflections.Data.Subtend][i]) / 65536 * 360, 3), Intensity = Reflections.Revolution[(int)Reflections.Data.Intensity][i], Range = Reflections.Revolution[(int)Reflections.Data.Range][i], Time = DateTime.Parse(Reflections.Revolution[(int)Reflections.Data.Time][0]).ToString(&quot;HH:mm:ss&quot;) }; </code></pre> <p>With each value defined as:</p> <pre class="lang-cs prettyprint-override"><code>public class ReflectionData : INotifyPropertyChanged { private string _bearingPLL; private decimal _bearingDeg; private string _subtendPLL; private decimal _subtendDeg; private string _intensity; private string _range; private string _time; public string BearingPLL { get { return _bearingPLL; } set { if (_bearingPLL != value) { _bearingPLL = value; OnPropertyChanged(); } } } public decimal BearingDegrees { get { return _bearingDeg; } set { if (_bearingDeg != value) { _bearingDeg = value; OnPropertyChanged(); } } } public string SubtendPLL { get { return _subtendPLL; } set { if (_subtendPLL != value) { _subtendPLL = value; OnPropertyChanged(); } } } public decimal SubtendDegrees { get { return _subtendDeg; } set { if (_subtendDeg != value) { _subtendDeg = value; OnPropertyChanged(); } } } public string Intensity { get { return _intensity; } set { if (_intensity != value) { _intensity = value; OnPropertyChanged(); } } } public string Range { get { return _range; } set { if (_range != value) { _range = value; OnPropertyChanged(); } } } public string Time { get { return _time; } set { if (_time != value) { _time = value; OnPropertyChanged(); } } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string name = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } } </code></pre> <p>The update user interface method gets triggered every time the Reflections.Revolution gets filled with new data. Is there a better / easier way for me to do this with minimal processing / memory usage, understanding I do have a lot of data here which is updating once every 0.125 seconds. The end result is this: <a href="https://i.stack.imgur.com/bT4Zo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bT4Zo.png" alt="Working application" /></a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:25:42.787", "Id": "261337", "Score": "1", "Tags": [ "c#", "wpf", "databinding" ], "Title": "User control displaying data which refreshes every 0.125 seconds" }
261337
<p>I wrote my own logger, but I dislike how many times I overloaded the <code>log()</code> function. If anyone knows of another way of doing that, feel free to share.</p> <pre class="lang-java prettyprint-override"><code>/* * Syml, a free and open source programming language. * Copyright (C) 2021 William Nelson * mailto: catboardbeta AT gmail DOT com * Syml is free software, licensed under MIT license. See LICENSE * for more information. * * Syml is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package personal.williamnelson; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class Logger implements Closeable { public File logfile = new File(&quot;&quot;); protected FileOutputStream fos; protected OutputStreamWriter osw; public void init(File fileToLog) { try { logfile = fileToLog; if (fileToLog.exists()) { clearFile(fileToLog); } else { fileToLog.createNewFile(); } } catch (IOException e) { //NOSONAR System.out.println(&quot;An error occurred while creating a logfile. Are you sure that '&quot; + logfile.toString() + &quot;' is a valid filename?&quot;); System.exit(1); } try { fos = new FileOutputStream(fileToLog, false); osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8); clearFile(fileToLog);x } catch (IOException e) { System.out.println(&quot;An unrecognized error occurred while start logging stream and &quot; + &quot;writing to log stream, despite passing all tests.&quot;); } } public void log(String s, boolean n) throws IOException { osw.write(getTime() + '\n' + s + (n ? '\n' : &quot;&quot;)); } public void log(char c, boolean n) throws IOException { osw.write(getTime() + '\n' + c + (n ? '\n' : &quot;&quot;)); } public void log(File f, boolean n) throws IOException { osw.write(getTime() + '\n' + f.getAbsolutePath() + (n ? '\n' : &quot;&quot;)); } public void log(StringBuilder sb, boolean n) throws IOException { osw.write(getTime() + '\n' + sb.toString() + (n ? '\n' : &quot;&quot;)); } public void log(int i, boolean n) throws IOException { osw.write(getTime() + '\n' + i + (n ? '\n' : &quot;&quot;)); } public void log(Integer i, boolean n) throws IOException { osw.write(getTime() + '\n' + i + (n ? '\n' : &quot;&quot;)); } public void log(float f, boolean n) throws IOException { osw.write(getTime() + '\n' + f + (n ? '\n' : &quot;&quot;)); } public void log(double d, boolean n) throws IOException { osw.write(getTime() + '\n' + d + (n ? '\n' : &quot;&quot;)); } public void log(long l, boolean n) throws IOException { osw.write(getTime() + '\n' + l + (n ? '\n' : &quot;&quot;)); } public void log(short s, boolean n) throws IOException { osw.write(getTime() + '\n' + s + (n ? '\n' : &quot;&quot;)); } public void log(boolean b, boolean n) throws IOException { osw.write(getTime() + '\n' + (b ? &quot;true&quot; : &quot;false&quot;) + (n ? '\n' : &quot;&quot;)); } public void log(byte b, boolean n) throws IOException { osw.write(getTime() + '\n' + b + (n ? '\n' : &quot;&quot;)); } private String getTime() { DateTimeFormatter dtf = DateTimeFormatter.ofPattern(&quot;yyyy/MM/dd HH:mm:ss&quot;); // example: 2021/27/5 12:07:23 LocalDateTime ldtNow = LocalDateTime.now(); return ldtNow.format(dtf); } private void clearFile(File file) throws IOException { OutputStreamWriter oswClearer = new OutputStreamWriter(fos); oswClearer.write(&quot;&quot;); oswClearer.close(); } public void close() throws IOException { osw.close(); fos.close(); } } </code></pre>
[]
[ { "body": "<p>Minor, but: by convention package paths are supposed to be reverse domain traversals, so</p>\n<pre><code>personal.williamnelson\n</code></pre>\n<p>would actually be</p>\n<pre><code>io.github.catboardbeta\n</code></pre>\n<p>Said another way, &quot;personal&quot; is <a href=\"https://en.wikipedia.org/wiki/Top-level_domain\" rel=\"nofollow noreferrer\">not a top-level domain</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:58:43.833", "Id": "515720", "Score": "0", "body": "I read in another Stack Overflow post that if you don't have a domain you should use personal.xyzxyz" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T16:01:59.830", "Id": "515723", "Score": "0", "body": "But you do have a GitHub account, right? So you probably already have a subdomain under `github.io`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T16:02:01.753", "Id": "515724", "Score": "0", "body": "I don't have GitHub Pages, and this project is hosted on GitLab." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T16:03:42.430", "Id": "515725", "Score": "0", "body": "The package nomenclature is less about hosting and more about unique namespace identification. Even if you haven't initialized your Pages content, the subdomain is still assigned, and so any Java packages you attribute to that namespace are conceptually yours." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T16:05:16.527", "Id": "515727", "Score": "0", "body": "If it's about unique namespace identification, I would think personal would work fine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T17:24:27.203", "Id": "515736", "Score": "1", "body": "Like it or not, `personal.` is not a convention that most people follow. Refer https://stackoverflow.com/questions/292169/what-package-naming-convention-do-you-use-for-personal-hobby-projects-in-java to see recommendations that are all over the map." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:55:52.413", "Id": "261344", "ParentId": "261338", "Score": "0" } }, { "body": "<p>If you have a look at all the existing logging frameworks out there, you will notice that they basically only log Strings. This way, every decendant of Object (which will be auto converted using the <code>toString()</code> method) can be logged.</p>\n<p>Granted, this does not work for primitives, so if you really really want to log <code>int</code>, <code>short</code>, etc., there will not be another solution.</p>\n<p>But, usually you don't do this. In more than two decades of full-time java development, I <em>never</em> had the desire to log just a primitive. You simply don't do:</p>\n<pre><code>log(i); // current iteration\n</code></pre>\n<p>in reality, this will rather be something like</p>\n<pre><code>log(&quot;current iteration: &quot; + i);\n</code></pre>\n<p>which will be a String again.</p>\n<p>Therefore, I think you wrote a lot of code to solve a problem that does not exist.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T12:08:30.590", "Id": "515791", "Score": "0", "body": "Oh understood. Guessing I also shouldn't have the whole `boolean n` ... `n ? '\\n' : ''` then?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T18:22:49.303", "Id": "515828", "Score": "0", "body": "Depends on what you want to achieve. In real life, you just grab an existing framework for logging and you're done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T09:02:19.237", "Id": "515868", "Score": "0", "body": "Logging a primitive is trivial, since autoboxing was introduced in Java 1.5" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T11:33:17.673", "Id": "515878", "Score": "0", "body": "log(int) will not autobox to log(Integer) to fit log(String). You'd have to convert to Integer manually, or declare an alternative method with the primitive argument." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T15:14:40.160", "Id": "515890", "Score": "0", "body": "It will autobox to Object... See my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T06:57:26.720", "Id": "515933", "Score": "0", "body": "Nice, I wasn't aware of that. You never stop learning... ;-)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T05:52:50.597", "Id": "261364", "ParentId": "261338", "Score": "2" } }, { "body": "<p>Auto-boxing has been around long enough that I think you only need one log method. Even here I'd avoid single letter names.</p>\n<pre><code> public void log(Object toLog, Boolean newLine) {\n osw.write(getTime() + '\\n' + String.valueOf(toLog) + (newLine? '\\n' : &quot;&quot;));\n }\n</code></pre>\n<p>You don't need to instantiate a date formatter each time you get the time, do you?</p>\n<p>You don't need to create or truncate the file explicitly.</p>\n<p>Closing the OutputStreamWriter will close the FileOutputStream it wraps, so you needn't close the latter yourself.</p>\n<p>I'd prefer longer, more expressive field names than &quot;osw&quot;, personally.</p>\n<p>Your logging format seems to involve a lot of newlines. Do you really need them after the date/time stamp or would some other delimiter work as well? Also, you would find it hard to distinguish an empty string from all spaces. Should you consider putting delimiters around the logged value?</p>\n<p>Finally, as already mentioned, you may want to consider using one of the plethora of existing loggers rather than writing your own.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T07:16:44.017", "Id": "261409", "ParentId": "261338", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:27:17.590", "Id": "261338", "Score": "2", "Tags": [ "java", "file", "logging" ], "Title": "Java logger (of doom!)" }
261338
<p>I understand <a href="https://codereview.stackexchange.com/help/dont-ask">It's OK to ask &quot;Does this code follow common best practices?&quot;</a>, hance I think the question is on-topic.</p> <h2>tl;dr</h2> <p>I want to review my vimrc file in all its parts, without a specific focus at the moment.</p> <h2>Why do I need this?</h2> <p>It all started when I installed <a href="https://github.com/ardagnir/athame" rel="nofollow noreferrer">Athame</a>, a program which</p> <blockquote> <p>patches your shell to add full Vim support by routing your keystrokes through an actual Vim process</p> </blockquote> <p>Later, I started experiencing some weird issues, like <a href="https://github.com/qutebrowser/qutebrowser/issues/6366" rel="nofollow noreferrer">not being able to open PDF files in qutebrowser</a> and having the <code>+clipboard</code> Vim feature not working via <code>ssh -Y</code> from my local machine to a remote machine. Both problem systematically occurred &quot;some time&quot; after the reboot. I can't help but think that probably even <a href="https://vi.stackexchange.com/questions/29283/strange-error-when-closing-vim">this problem</a> could be related, as I started seeing them all at around the same time.</p> <p>With some help from the guys in ArchLinux' forum, I verified that some process was systematically deleting stuff in <code>/tmp/</code>.</p> <p>Unistalling Athame solved all these issue together.</p> <p>However, <a href="https://github.com/ardagnir/athame/issues/90" rel="nofollow noreferrer">the author comments that Athame should be able to do that by itself, because it just calls Vim and that's it, and that probably all is due to something in my vimrc</a>.</p> <p>So I need to do some troubleshooting, but commenting a piece of my vimrc, then seeing if the problem occurs without Athame, then installing Athame, and see if the problem occurs, and then commenting another piece of my vimrc, and then... doesn't seem to be a good strategy, especially considering that I've not understood how to trigger the nasty behavior at my will, which means I'd have probably to make a test per day.</p> <p>Now, I understand that troubleshooting is probably off topic here, but I think a first step before troubleshooting is a thorough review of my vimrc, aimed at spotting some obvious mistake I've done.</p> <h2>Here's the file</h2> <pre><code>augroup filetype_vim autocmd! autocmd FileType vim setlocal foldmethod=marker augroup END &quot; Leader mappings {{{1 &quot; let maplocalleader = &quot;\&lt;Enter&gt;&quot; let mapleader = &quot;\&lt;Space&gt;&quot; &quot; Plugins: {{{1 &quot; &quot; Plugin: VimPlug {{{2 &quot; if empty(glob('~/.vim/autoload/plug.vim')) silent !curl -fLo ~/.vim/autoload/plug.vim --create-dirs \ https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim au VimEnter * PlugInstall --sync | source $MYVIMRC endif call plug#begin('~/.vim/plugged') &quot; List of plugins {{{2 &quot; Plug 'junegunn/vim-plug' &quot;Plug 'junegunn/vim-peekaboo' &quot;Plug 'L9' Plug 'honza/vim-snippets' Plug 'itchyny/lightline.vim' Plug 'airblade/vim-gitgutter' Plug 'tpope/vim-fugitive' Plug 'tpope/vim-surround' Plug 'powerline/fonts' Plug 'scrooloose/nerdtree' Plug 'terryma/vim-multiple-cursors' &quot;Plug 'dag/vim-fish' &quot;Plug 'ryanoasis/nerd-fonts' Plug 'lervag/vimtex' Plug 'SirVer/ultisnips' Plug 'Valloric/YouCompleteMe' &quot;Plug 'beloglazov/vim-online-thesaurus' Plug 'ron89/thesaurus_query.vim' Plug 'uguu-org/vim-matrix-screensaver' Plug 'mbbill/undotree', { 'on': 'UndotreeToggle' } Plug 'vim-scripts/ScrollColors' Plug 'agude/vim-eldar' Plug 'mtth/scratch.vim' Plug 'vim-scripts/cmdalias.vim' Plug 'majutsushi/tagbar' Plug 'wincent/command-t' Plug 'ap/vim-css-color' Plug 'ryanoasis/vim-devicons' Plug 'Aster89/WinZoZ' Plug 'andymass/vim-matchup' call plug#end() &quot; 1}}} &quot; syntax enable &quot; Plugin: Undotree {{{2 &quot; let g:undotree_WindowLayout = 2 let g:undotree_SetFocusWhenToggle = 1 let g:undotree_TreeNodeShape = &quot;\u2022&quot; let g:undotree_ShortIndicators = 1 let g:undotree_HighlightChangedText = 1 &quot; Plugin: NERDTree {{{2 &quot; au StdinReadPre * let s:std_in = 1 &quot;au VimEnter * if argc() == 0 &amp;&amp; !exists(&quot;s:std_in&quot;) | exe 'NERDTree' | endif au VimEnter * if argc() == 1 &amp;&amp; isdirectory(argv()[0]) &amp;&amp; !exists(&quot;s:std_in&quot;) | exe 'NERDTree' argv()[0] | wincmd p | ene | endif au BufEnter * if (winnr(&quot;$&quot;) == 1 &amp;&amp; exists(&quot;b:NERDTree&quot;) &amp;&amp; b:NERDTree.isTabTree()) | q | endif let NERDTreeQuitOnOpen = 1 let g:NERDTreeGlyphReadOnly = &quot;\ue0a2&quot; let g:NERDTreeUseTCD = 1 &quot;let g:DevIconsEnableFoldersOpenClose = 1 if exists('g:loaded_webdevicons') call webdevicons#refresh() endif &quot; Plugin: YouCompleteMe {{{2 &quot; let g:ycm_complete_in_comments = 1 let g:ycm_complete_in_strings = 1 let g:ycm_min_num_of_chars_for_completion = 2 let g:ycm_collect_identifiers_from_comments_and_strings = 1 let g:ycm_seed_identifiers_with_syntax = 1 let g:ycm_always_populate_location_list = 1 let g:ycm_python_binary_path = 'python3' let g:ycm_server_python_interpreter = 'python3' let g:ycm_autoclose_preview_window_after_insertion = 1 let g:ycm_autoclose_preview_window_after_completion = 1 let g:ycm_key_list_select_completion = ['&lt;Tab&gt;'] let g:ycm_key_list_previous_completion = ['&lt;S-Tab&gt;'] let g:ycm_confirm_extra_conf = 0 let g:ycm_global_ycm_extra_conf = '~/.ycm_extra_conf.py' let g:ycm_clangd_args = ['-cross-file-rename'] let g:ycm_auto_hover = '' let g:ycm_error_symbol = &quot;\uf05e&quot; &quot;  let g:ycm_warning_symbol = &quot;\uf071&quot; &quot;  source /home/enrico/lsp-examples/vimrc.generated &quot; Plugin: MatchUp {{{2 &quot; let g:matchup_matchparen_offscreen = {'method': 'popup', 'highlight': 'OffscreenPopup'} &quot; Plugin: Vim snippets {{{2 &quot; let g:snips_author = &quot;Me&quot; let g:snips_email = &quot;me@me.me&quot; let g:snips_github = &quot;https://github.com/Aster89&quot; &quot; Plugin: UltiSnips {{{2 &quot; let g:UltiSnipsExpandTrigger = &quot;&lt;F8&gt;&quot; let g:UltiSnipsJumpForwardTrigger = &quot;&lt;F8&gt;&quot; let g:UltiSnipsJumpBackwardTrigger = &quot;&lt;S-F8&gt;&quot; let g:UltiSnipsEditSplit = &quot;vertical&quot; let g:UltiSnipsUsePythonVersion = 3 &quot; Plugin: VimTeX {{{2 &quot; let g:vimtex_delim_stopline = 1000 let g:vimtex_view_general_viewer = 'zathura' let g:vimtex_view_method = &quot;zathura&quot; &quot;let g:latex_view_general_viewer = 'zathura' &quot;let g:vimtex_view_general_options = '--unique @pdf\#src:@line@tex' &quot;let g:vimtex_view_general_options_latexmk = '--unique' let g:vimtex_fold_enabled = 1 let g:vimtex_fold_manual = 1 let g:vimtex_quickfix_method = 'pplatex' let g:vimtex_quickfix_autoclose_after_keystrokes = 5 let g:tex_flavor = 'latex' &quot; avoid some skinny *.tex file to be interpreted as plaintex files let g:vimtex_compiler_latexmk = { \ 'options' : [ \ '-shell-escape', \ '-verbose', \ '-file-line-error', \ '-synctex=1', \ '-interaction=nonstopmode', \ ], \} &quot; Plugin: scratch {{{2 &quot; let g:scratch_top = 1 let g:scratch_insert_autohide = 0 &quot; Plugin: TagBar {{{2 &quot; let g:tagbar_show_linenumbers = 1 &quot; Plugin: command-t {{{2 &quot; let g:CommandTCancelMap = ['&lt;ESC&gt;', '&lt;C-c&gt;'] &quot; Plugin: gitgutter {{{2 &quot; let g:gitgutter_close_preview_on_escape = 1 &quot; Plugin: lightline {{{2 &quot; &quot; lightline plugin, from https://github.com/itchyny/lightline.vim set noshowmode set laststatus=2 let g:lightline = { \ 'colorscheme': 'default', \ 'mode_map': { \ 'n' : 'NORMAL', \ 'i' : 'INSERT', \ 'R' : 'REPLACE', \ 'v' : 'VISUAL', \ 'V' : 'V-LINE', \ &quot;\&lt;C-v&gt;&quot;: 'V-BLOCK', \ 'c' : 'COMMAND', \ 's' : 'SELECT', \ 'S' : 'S-LINE', \ &quot;\&lt;C-s&gt;&quot;: 'S-BLOCK', \ 't': 'TERMINAL', \ }, \ 'active': { \ 'left': [ [ 'mode', 'paste' ], [ 'fugitive', 'filename' ] ] \ }, \ 'component': { \ 'lineinfo': &quot;\ue0a1 %3l:%-2c&quot;, \ }, \ 'component_function': { \ 'fileencoding': 'LightLineFileencoding', \ 'fileformat': 'LightLineFileformat', \ 'filename': 'LightLineFilename', \ 'filetype': 'LightLineFiletype', \ 'fugitive': 'LightLineFugitive', \ 'mode': 'LightLineMode', \ 'modified': 'LightLineModified', \ 'readonly': 'LightLineReadonly', \ }, \ 'separator': { 'left': &quot;\ue0b0&quot;, 'right': &quot;\ue0b2&quot; }, \ 'subseparator': { 'left': &quot;\ue0b1&quot;, 'right': &quot;\ue0b3&quot; } \ } function! LightLineModified() return &amp;ft =~ 'help\|vimfiler\|gundo\|undotree' ? '' : &amp;modified ? '+' : &amp;modifiable ? '' : '-' endfunction function! LightLineReadonly() return &amp;ft !~? 'vimfiler\|gundo\|undotree' &amp;&amp; &amp;readonly ? &quot;\ue0a2&quot; : '' endfunction function! LightLineFilename() return ('' != LightLineReadonly() ? LightLineReadonly() . ' ' : '') . \ (&amp;ft == 'vimfiler' ? vimfiler#get_status_string() : \ &amp;ft == 'unite' ? unite#get_status_string() : \ &amp;ft == 'vimshell' ? vimshell#get_status_string() : \ '' != expand('%:t') ? expand('%:t') : '[No Name]') . \ ('' != LightLineModified() ? ' ' . LightLineModified() : '') endfunction function! LightLineFugitive() if &amp;ft !~? 'vimfiler\|gundo\|undotree' &amp;&amp; exists(&quot;*fugitive#head&quot;) let branch = fugitive#head() return branch !=# '' ? &quot;\ue0a0 &quot;.branch : '' endif return '' endfunction function! LightLineFileformat() return winwidth(0) &gt; 70 ? (&amp;fileformat . ' ' . WebDevIconsGetFileFormatSymbol()) : '' endfunction function! LightLineFiletype() return winwidth(0) &gt; 70 ? (strlen(&amp;filetype) ? &amp;filetype . ' ' . WebDevIconsGetFileTypeSymbol() : 'no ft') : '' endfunction function! LightLineFileencoding() return winwidth(0) &gt; 70 ? (&amp;fenc !=# '' ? &amp;fenc : &amp;enc) : '' endfunction function! LightLineMode() return winwidth(0) &gt; 60 ? lightline#mode() : '' endfunction &quot; Encoding {{{1 &quot; set enc=UTF-8 &quot; Color scheme customization {{{1 &quot; &quot; `highlight` commands in `au`s before `colo`; &quot; see https://vi.stackexchange.com/q/3355/6498 au ColorScheme * \ hi Character ctermfg=magenta | \ hi Comment ctermfg=grey cterm=italic | \ hi CursorColumn ctermbg=NONE ctermfg=NONE cterm=bold | \ hi CursorLine ctermbg=NONE ctermfg=NONE cterm=bold | \ hi Pmenu ctermbg=grey ctermfg=black | \ hi PmenuSbar ctermbg=darkgrey | \ hi PmenuSel ctermbg=darkgrey ctermfg=white | \ hi PmenuThumb ctermbg=white | \ hi Search ctermbg=green | \ hi SignColumn ctermbg=none | \ hi SpecialChar ctermfg=magenta | \ hi SpellBad ctermbg=red ctermfg=white | \ hi SpellCap ctermbg=magenta ctermfg=black | \ hi SpellLocal ctermbg=brown ctermfg=white | \ hi SpellRare ctermbg=yellow ctermfg=black | \ hi String ctermfg=red | \ hi GitGutterAdd ctermfg=green | \ hi GitGutterChange ctermfg=white | \ hi GitGutterDelete ctermfg=red | \ hi YcmErrorLine cterm=NONE | \ hi YcmErrorSection ctermbg=red ctermfg=white | \ hi YcmErrorSign ctermbg=red ctermfg=white | \ hi YcmWarningLine cterm=NONE | \ hi YcmWarningSection ctermbg=yellow ctermfg=black | \ hi YcmWarningSign ctermbg=yellow ctermfg=black colo pablo &quot; set the colorscheme &quot; Non-plugin options {{{1 &quot; &quot; line numbers {{{2 &quot; set nu set rnu &quot; cursor and visibility {{{2 &quot; set cursorline set cursorcolumn set linebreak set list lcs=extends:→,precedes:←,tab:├─┤,trail:~,nbsp:░ set showbreak=↪ set noequalalways set nostartofline set nowrap set nowrapscan set formatoptions=tcronq2lj set showcmd set sidescroll=1 set tabstop=2 softtabstop=0 expandtab shiftwidth=2 smarttab smartindent autoindent set backspace=indent,eol,start &quot; search {{{2 &quot; set incsearch set hlsearch set ignorecase set smartcase &quot; command line {{{2 &quot; set wildignorecase set wildchar=&lt;Tab&gt; set wildcharm=&lt;Tab&gt; &quot; Easy and safe buffer/window navigation {{{2 &quot; set nobk &quot; this three options... set nowb &quot; ... are useful to navigate from buffer to buffer... set hid &quot; ... without having to write the buffer each time set dir=.,~/tmp,/var/tmp,/tmp &quot; numbers {{{2 &quot; set nrformats=alpha,bin,hex,octal &quot; updatetime {{{2 &quot; set updatetime=1000 &quot; info saved upon exit {{{2 &quot; &quot; Tell vim to remember certain things when we exit &quot; '10 : marks will be remembered for up to 10 previously edited files &quot; &quot;100 : will save up to 100 lines for each register &quot; :20 : up to 20 lines of command-line history will be remembered &quot; % : saves and restores the buffer list &quot; n... : where to save the viminfo files set viminfo='50,\&quot;100,:20,%,n~/.viminfo &quot; reset cursor when reopening a file {{{3 &quot; function! ResCur() if line(&quot;'\&quot;&quot;) &lt;= line(&quot;$&quot;) normal! g`&quot; return 1 endif endfunction aug resCur au! au BufWinEnter * call ResCur() aug END &quot; 3}}} &quot; &quot; handling special key combos {{{1 &quot; set &lt;S-F1&gt;=[23~ set &lt;S-F2&gt;=[24~ set &lt;S-F3&gt;=[25~ set &lt;S-F4&gt;=[26~ set &lt;S-F5&gt;=[28~ set &lt;S-F6&gt;=[29~ set &lt;S-F7&gt;=[31~ set &lt;S-F8&gt;=[32~ set &lt;S-F9&gt;=[33~ set &lt;S-F10&gt;=[34~ set &lt;S-F11&gt;=[23$ set &lt;S-F12&gt;=[24$ set &lt;S-Up&gt;=[a &quot; 1}}} &quot; &quot; language dictionary {{{1 &quot; &quot;let g:tq_openoffice_en_file = &quot;/usr/share/mythes/th_it_IT_v2&quot; set dictionary+=/usr/share/dict/cracklib-small &quot; set the dictionary &quot; 1}}} &quot; &quot; Leader mappings {{{1 &quot; let maplocalleader = &quot;\&lt;Enter&gt;&quot; let mapleader = &quot;\&lt;Space&gt;&quot; &quot; TODO fare una domanda per il coloring in vimdiff &quot; Ignore case toggle {{{2 &quot; nnoremap &lt;Leader&gt;ic :call Toggle_ic()&lt;CR&gt; fun! Toggle_ic() set ic! if &amp;ic echo 'ignorecase ON' else echo 'ignorecase OFF' endif endfun &quot; Highlight search clear {{{2 &quot; nnoremap &lt;silent&gt; &lt;Leader&gt;hl :nohls&lt;CR&gt; &quot; Edit and source vimrc {{{2 &quot; nnoremap &lt;silent&gt; &lt;Leader&gt;ev :tabedit $MYVIMRC&lt;CR&gt; nnoremap &lt;silent&gt; &lt;Leader&gt;sv :source $MYVIMRC&lt;CR&gt; &quot; YCM mappings {{{2 &quot; nnoremap &lt;silent&gt; &lt;Leader&gt;yrs :YcmRestartServer&lt;CR&gt; nnoremap &lt;silent&gt; &lt;leader&gt;ygt :YcmCompleter GetType&lt;CR&gt; nnoremap &lt;silent&gt; &lt;leader&gt;yfi :YcmCompleter FixIt&lt;CR&gt; nnoremap &lt;silent&gt; &lt;leader&gt;ygd :YcmCompleter GoToDefinition&lt;CR&gt; nnoremap &lt;silent&gt; &lt;leader&gt;ygD :YcmCompleter GoToDeclaration&lt;CR&gt; nnoremap &lt;silent&gt; &lt;leader&gt;ygr :YcmCompleter GoToReferences&lt;CR&gt; nnoremap &lt;silent&gt; &lt;leader&gt;ygi :YcmCompleter GoToInclude&lt;CR&gt; nnoremap &lt;leader&gt;ygs :YcmCompleter GoToSymbol&lt;Space&gt; nmap &lt;silent&gt; &lt;Leader&gt;D &lt;Plug&gt;(YCMHover) &quot; CommandT mappings {{{2 &quot; nmap &lt;silent&gt; &lt;Leader&gt;ff &lt;Plug&gt;(CommandT) nmap &lt;silent&gt; &lt;Leader&gt;fb &lt;Plug&gt;(CommandTBuffer) nmap &lt;silent&gt; &lt;Leader&gt;fj &lt;Plug&gt;(CommandTJump) &quot; Other plugins' mappings {{{2 &quot; nnoremap &lt;silent&gt; &lt;Leader&gt;n :NERDTreeToggle&lt;CR&gt; nnoremap &lt;silent&gt; &lt;Leader&gt;u :UndotreeToggle&lt;CR&gt; nnoremap &lt;silent&gt; &lt;Leader&gt;tb :TagbarToggle&lt;CR&gt; nnoremap &lt;silent&gt; &lt;Leader&gt;T :ThesaurusQueryReplaceCurrentWord&lt;CR&gt; &quot; set synonyms to no-op {{{1 &quot; inoremap &lt;Left&gt; &lt;NOP&gt; inoremap &lt;Right&gt; &lt;NOP&gt; inoremap &lt;Up&gt; &lt;NOP&gt; inoremap &lt;Down&gt; &lt;NOP&gt; noremap &lt;Left&gt; &lt;NOP&gt; noremap &lt;Right&gt; &lt;NOP&gt; noremap &lt;Up&gt; &lt;NOP&gt; noremap &lt;Down&gt; &lt;NOP&gt; noremap &lt;Space&gt; &lt;NOP&gt; noremap &lt;Del&gt; &lt;NOP&gt; noremap &lt;Backspace&gt; &lt;NOP&gt; noremap! &lt;Down&gt; &lt;NOP&gt; noremap! &lt;Up&gt; &lt;NOP&gt; &quot; look at https://vim.fandom.com/wiki/Unused_keys &quot; for all keys that are synonyms that can be &quot; deactivated &quot; Terminal debug {{{1 &quot; &quot; Source the termdebug plugin packadd termdebug packadd! matchit &quot; Terminal debug and relative numbering {{{2 &quot; &quot; function to start gdb and activate &quot;smart&quot; relativenumber nnoremap &lt;silent&gt; &lt;Leader&gt;td :call TermdebugAndRelNumOff()&lt;CR&gt; function! TermdebugAndRelNumOff() aug ClosingDebugger au! &quot; set/unset rnu when leaving/entering gdb window au BufLeave !gdb call SetRelNumInAllWin(1) au BufEnter !gdb call SetRelNumInAllWin(0) &quot; delete the aug (and its au-s) when closing gdb au BufUnload !gdb au! | aug! ClosingDebugger aug END &quot; start Termdebug Termdebug endfunction &quot; set/unset relativenumber in all windows if flag is v:true/v:false function! SetRelNumInAllWin(flag) &quot; see https://vi.stackexchange.com/a/26853/6498 for tabinfo in gettabinfo() let tabnr = tabinfo['tabnr'] for winid in tabinfo['windows'] call settabwinvar(tabnr, winid, '&amp;relativenumber', a:flag &amp;&amp; &amp;number) endfor endfor endfunction &quot; Overload normal behaviors {{{1 &quot; &quot; set consistent behavior for gt function! Mygt(count) let loop = a:count while loop &gt; 0 normal! gt let loop -= 1 endwhile endfunction nnoremap &lt;silent&gt; gt :&lt;C-U&gt;execute &quot;call Mygt(&quot; . v:count1 . &quot;)&quot;&lt;CR&gt; &quot; alleviate this behavior: https://vi.stackexchange.com/q/28118/6498 set timeout timeoutlen=1000 ttimeoutlen=100 &quot; Tabclose instead of quit-all &quot; https://vim.fandom.com/wiki/Tabclose_instead_of_quit-all command! -bang QA :call TabQAll('&lt;bang&gt;') function! TabQAll(bang) try if tabpagenr('$') &gt; 1 let text =&lt;&lt; trim END There are other open tabs. Do you want to close all of them? END let choice = confirm(join(text, &quot;\n&quot;), &quot;&amp;Yes\n&amp;No&quot;, 2, &quot;Warning&quot;) else let choice = 1 endif if choice == 1 exec 'qa'.a:bang endif catch echohl ErrorMsg | echo v:exception | echohl NONE endtry endfunction function! InitPlugins() call CmdAlias('qa', 'QA') au! InitPlugins VimEnter endfunction aug InitPlugins au! au VimEnter * :call InitPlugins() aug END &quot; Backward in jumplist nnoremap &lt;S-Tab&gt; &lt;C-O&gt; &quot; caps lock related {{{1 &quot; imap &lt;C-U&gt; &lt;Esc&gt;viwU&lt;Esc&gt;ea &quot; The following is aimed to use CTRL-^ (that is CTRL-MAIUSC-ì) in place of &quot; capslock. The advantage is the last line of code, which consists in &quot; turning off the fictitious capslock when exiting the insert mode &quot; (solution found on vim.wikia.com/wiki/insert-mode_only_Caps_Lock). &quot; Execute 'lnoremap x X' and 'lnoremap X x' for each letter a-z. for c in range(char2nr('A'), char2nr('Z')) exe 'lnoremap ' . nr2char(c+32) . ' ' . nr2char(c) exe 'lnoremap ' . nr2char(c) . ' ' . nr2char(c+32) endfor &quot; Kill the capslock when leaving insert mode. au InsertLeave * set iminsert=0 &quot; Show highlighting groups for current word {{{1 &quot; nmap &lt;C-S-P&gt; :call &lt;SID&gt;SynStack()&lt;CR&gt; function! &lt;SID&gt;SynStack() if !exists(&quot;*synstack&quot;) return endif echo map(synstack(line('.'), col('.')), 'synIDattr(v:val, &quot;name&quot;)') endfunc &quot; ***************************************************************** &quot; Autocommands &quot; ***************************************************************** &quot; maps &lt;Leader&gt;d to &quot;delete current line in clipboard and exit vim&quot; when &quot; editing a command line in the vim editor au BufEnter /tmp/bash-fc.* nn &lt;Leader&gt;d 0&quot;+y$dd:%d&lt;CR&gt;:wq&lt;CR&gt; &quot; sets tex filetype for tikz files au BufNewFile,BufRead *.tikz set filetype=tex &quot; sets textwidth for tex files au BufNewFile,BufRead *.tex set textwidth=79 &quot; ***************************************************************** &quot; Autocommands &quot; ***************************************************************** &quot; file type detection {{{1 &quot; &quot; what follows serves to detect the filetype of the current buffer even if no &quot; extensions has been set [cf. Learning the vi and Vim editors, from page 205] aug newFileDetection au! au CursorMovedI * call CheckFileType() aug end function! CheckFileType() if exists(&quot;b:countCheck&quot;) == 0 let b:countCheck = 0 endif let b:countCheck += 1 if &amp;filetype == &quot;&quot; &amp;&amp; b:countCheck &gt; 20 &amp;&amp; b:countCheck &lt; 200 filetype detect elseif b:countCheck &gt;= 200 || &amp;filetype != &quot;&quot; au! newFileDetection endif endfunction <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:47:28.983", "Id": "515717", "Score": "0", "body": "We can only review code which is known to be working. Does your code produce the correct output? Is it possible the hiccup was by a dependency problem (you seem to use a lot of plugins)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T16:00:54.727", "Id": "515722", "Score": "0", "body": "@Mast as far as I can tell, my vimrc is working, and with this review I'd like to confirm that all the bits are done the right way." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:29:33.380", "Id": "261339", "Score": "0", "Tags": [ "vimscript", "vim" ], "Title": "Has this vimrc something wrong?" }
261339
<p>I created this working sample and the code is below. Any advice on how to make this code; cleaner, more effective, just overall better! The data is coming from an API and I need to parse, select the value in location 0 set the title and then rebuild the drop down control.</p> <blockquote> <p>can it be done without the JSON.parse(data) or the $.each?</p> </blockquote> <p><a href="https://dotnetfiddle.net/lfJhGi" rel="nofollow noreferrer">https://dotnetfiddle.net/lfJhGi</a></p> <pre><code> $(&quot;#ddlReleaseYears&quot;).change(function () { $('#toptitle').text('change event'); //coming from API var data = &quot;[2021,2020,2019,2018,2017,2016]&quot;; var arr = JSON.parse(data); $('#toptitle').text(arr[0]); var HTML = &quot;&quot; $.each(arr, function (index, value) { HTML += &quot;&lt;option value='&quot; +value + &quot;' &quot;; HTML += &quot;&gt;&quot; +value + &quot;&lt;/option&gt;&quot; }); $(&quot;#ddlReleaseYears&quot;).html(&quot;&quot;); $(&quot;#ddlReleaseYears&quot;).append(HTML); }) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T16:13:07.780", "Id": "515731", "Score": "0", "body": "you could fill `data` dynamically based on the current year... (or you need to change your code in 7 months time... )" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T16:16:08.440", "Id": "515732", "Score": "0", "body": "can I do it without the `JSON.parse(data)` or the `$.each`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T18:15:12.673", "Id": "515743", "Score": "0", "body": "Why not a simple [for loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration) ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T20:15:29.773", "Id": "515752", "Score": "0", "body": "If the data you are receiving from the API is JSON, you need to parse it. Why would you not want to use `JSON.parse`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T22:12:56.260", "Id": "515760", "Score": "0", "body": "I was just thinking I would need to do something like this to get the data out arr[0]." } ]
[ { "body": "<p>The two first things that come to my mind:</p>\n<ol>\n<li>Using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"nofollow noreferrer\">template strings</a></li>\n<li>Modifying the dropdown HTML once:</li>\n</ol>\n<pre class=\"lang-javascript prettyprint-override\"><code>$(document).ready(function () {\n $(&quot;#ddlReleaseYears&quot;).change(function () {\n var data = &quot;[2021,2020,2019,2018,2017,2016]&quot;;\n var arr = JSON.parse(data);\n $('#toptitle').text(arr[0]);\n var HTML = &quot;&quot;\n $.each(arr, function (index, value) {\n HTML += `&lt;option value=&quot;${value}&quot;&gt;${value}&lt;/option&gt;`\n });\n // No need to set the html to &quot;&quot; and then append\n $(&quot;#ddlReleaseYears&quot;).html(HTML);\n })\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T21:32:31.577", "Id": "515755", "Score": "0", "body": "Thanks for the help anything I can do with setting the toptitle? ‘$('#toptitle').text(arr[0]);’" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T07:25:29.257", "Id": "515779", "Score": "0", "body": "I mean, that is readable: you get the element whose id is `toptitle` and you set its text to the first element of the array `arr`. Nothing to say about that" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T20:23:35.337", "Id": "261352", "ParentId": "261340", "Score": "1" } }, { "body": "<h2>Use the DOM API</h2>\n<p>Always try to avoid adding HTML to the page. Modern browsers come with all the APIs and interfaces to create and manipulate page content.</p>\n<p>using he API's is much quicker than adding HTML, And as you will not need jQuery even faster still.</p>\n<h2>Element by id</h2>\n<p>If you have elements identified by their ids as follows...</p>\n<pre><code>&lt;label for=&quot;dlReleaseYear&quot; id=&quot;toptitle&quot;&gt;&lt;/label&gt;\n&lt;select id=&quot;dlReleaseYear&quot;&gt;&lt;/select&gt;\n</code></pre>\n<p>...you can reference the element directly in JavaScript. You must ensure that the elements ID is unique.</p>\n<pre><code>toptitle.textContent = &quot;hello world&quot;;\n</code></pre>\n<h2>Select <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLSelectElement\">HTMLSelectElement</a></h2>\n<p>The select element has an interface <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLSelectElement\">HTMLSelectElement</a> to do all the common tasks.</p>\n<ul>\n<li><p>To empty the select element</p>\n<pre><code>dlReleaseYear.length = 0;\n</code></pre>\n</li>\n<li><p>To add an option use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/add\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLSelectElement add\">HTMLSelectElement.add</a> to add a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionElement\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLOptionElement\">HTMLOptionElement</a></p>\n<pre><code>dlReleaseYear.add(Object.assign(document.createElement(&quot;option&quot;), {value}))\n</code></pre>\n</li>\n</ul>\n<h2>Reusable</h2>\n<p>As DOM APIs are generally very verbose and too specific create utility functions to reduce the code noise. For example the function tag creates an element by tag name and assigns properties.</p>\n<pre><code>const tag = (tag, props = {}) =&gt; Object.assign(document.createElement(tag), props);\n</code></pre>\n<p>Thus adding an option becomes</p>\n<pre><code>dlReleaseYear.add(tag(&quot;option&quot;, {value: item, textContent: item}));\n</code></pre>\n<p>Adding options to a select element is a frequent task so rather than create a custom function, create a general function that adds options to a Select element so that it can be reused.</p>\n<pre><code>const tag = (tag, props = {}) =&gt; Object.assign(document.createElement(tag), props);\nconst selectOptions = (selEl, ...data) =&gt; (\n selEl.length = 0,\n data.forEach(value =&gt; { selEl.add(tag(&quot;option&quot;, {value, textContent: value})) },\n selEl\n)\n</code></pre>\n<h2>Events</h2>\n<p>To add event Listeners using the DOM API call the elements <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\" title=\"MDN Web API's EventTarget addEventListener\">EventTarget.addEventListener</a> function with the event name and the listener.</p>\n<p>To add the change event</p>\n<pre><code>dlReleaseYear.addEventListener(&quot;change&quot;, listenerFunction);\n</code></pre>\n<h2>Rewrite</h2>\n<p>Using all of the above you no long need to use jQuery with all its overheads and there is no need to build markup strings and then have the browser have to parse them.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const tag = (tag, props = {}) =&gt; Object.assign(document.createElement(tag), props);\nconst selectOptions = (selEl, ...data) =&gt; (\n selEl.length = 0,\n data.forEach(value =&gt; { selEl.add(tag(\"option\", {value, textContent: value})) }),\n selEl\n);\n\nddlReleaseYears.addEventListener(\"change\", updateYearOptions);\nfunction updateYearOptions() {\n const data = [2002,2003,2004,2005,2006];\n toptitle.textContent = data[0];\n selectOptions(ddlReleaseYears, ...data);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;label for=\"ddlReleaseYears\" id=\"toptitle\"&gt;Select option to test&lt;/label&gt;\n&lt;select id=\"ddlReleaseYears\"&gt;\n &lt;option&gt;Test&lt;/option&gt;\n &lt;option&gt;Years&lt;/option&gt;\n\n&lt;/select&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": "2021-05-29T14:40:57.557", "Id": "261380", "ParentId": "261340", "Score": "2" } } ]
{ "AcceptedAnswerId": "261352", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:30:38.083", "Id": "261340", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "Reload control using loop" }
261340
<pre><code>from datasets import load_dataset #Huggingface from transformers import BertTokenizer #Huggingface: def tokenized_dataset(dataset): &quot;&quot;&quot; Method that tokenizes each document in the train, test and validation dataset Args: dataset (DatasetDict): dataset that will be tokenized (train, test, validation) Returns: dict: dataset once tokenized &quot;&quot;&quot; tokenizer = BertTokenizer.from_pretrained(&quot;bert-base-uncased&quot;) encode = lambda document: tokenizer(document, return_tensors='pt', padding=True, truncation=True) train_articles = [encode(document) for document in dataset[&quot;train&quot;][&quot;article&quot;]] test_articles = [encode(document) for document in dataset[&quot;test&quot;][&quot;article&quot;]] val_articles = [encode(document) for document in dataset[&quot;val&quot;][&quot;article&quot;]] train_abstracts = [encode(document) for document in dataset[&quot;train&quot;][&quot;abstract&quot;]] test_abstracts = [encode(document) for document in dataset[&quot;test&quot;][&quot;abstract&quot;]] val_abstracts = [encode(document) for document in dataset[&quot;val&quot;][&quot;abstract&quot;]] return {&quot;train&quot;: (train_articles, train_abstracts), &quot;test&quot;: (test_articles, test_abstracts), &quot;val&quot;: (val_articles, val_abstracts)} if __name__ == &quot;__main__&quot;: dataset = load_data(&quot;./train/&quot;, &quot;./test/&quot;, &quot;./val/&quot;, &quot;./.cache_dir&quot;) tokenized_data = tokenized_dataset(dataset) </code></pre> <p>I would like to modify the function <code>tokenized_dataset</code> because it creates a very heavy dictionary. The dataset created by that function will be reused for a ML training. However, dragging that dictionary during the training will slow down the training a lot.</p> <p>Be aware that <code>document</code> is similar to</p> <pre><code>[['eleven politicians from 7 parties made comments in letter to a newspaper .', &quot;said dpp alison saunders had ` damaged public confidence ' in justice .&quot;, 'ms saunders ruled lord janner unfit to stand trial over child abuse claims .', 'the cps has pursued at least 19 suspected paedophiles with dementia .'], ['an increasing number of surveys claim to reveal what makes us happiest .', 'but are these generic lists really of any use to us ?', 'janet street-porter makes her own list - of things making her unhappy !'], [&quot;author of ` into the wild ' spoke to five rape victims in missoula , montana .&quot;, &quot;` missoula : rape and the justice system in a college town ' was released april 21 .&quot;, &quot;three of five victims profiled in the book sat down with abc 's nightline wednesday night .&quot;, 'kelsey belnap , allison huguet and hillary mclaughlin said they had been raped by university of montana football ' 'players .', &quot;huguet and mclaughlin 's attacker , beau donaldson , pleaded guilty to rape in 2012 and was sentenced to 10 years .&quot;, 'belnap claimed four players gang-raped her in 2010 , but prosecutors never charged them citing lack of probable ' 'cause .', 'mr krakauer wrote book after realizing close friend was a rape victim .'], ['tesco announced a record annual loss of £ 6.38 billion yesterday .', 'drop in sales , one-off costs and pensions blamed for financial loss .', 'supermarket giant now under pressure to close 200 stores nationwide .', 'here , retail industry veterans , plus mail writers , identify what went wrong .'], ..., ['snp leader said alex salmond did not field questions over his family .', &quot;said she was not ` moaning ' but also attacked criticism of women 's looks .&quot;, 'she made the remarks in latest programme profiling the main party leaders .', 'ms sturgeon also revealed her tv habits and recent image makeover .', 'she said she relaxed by eating steak and chips on a saturday night .']] </code></pre> <p>So in the dictionary, the keys are just strings, but the values are all list of lists of strings. Instead of having value = list of list of strings, I think it is better to create sort of a list of object function instead of having list of lists of strings. It will make the dictionary much lighter. How can I do that?</p> <p><strong>EDIT</strong></p> <p>I preprocess a dataset (article and abstract) before feeding a Neural Network model (NLP). First, I load the dataset with <code>datasets.load_dataset()</code> from different repositories, i.e. <code>./train/</code>, <code>./test/</code> and <code>./val/</code>. Once done, I tokenize each sentence of the articles and abstracts</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:39:21.597", "Id": "261342", "Score": "2", "Tags": [ "python", "object-oriented" ], "Title": "Replacing list of lists of string by function objects to speed up ML training process" }
261342
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/260989/231235">Android APP User class implementation</a>. I am attempting to build a user registering system and this post shows the user registration page implementation.</p> <p><strong>The experimental implementation</strong></p> <ul> <li><p>Project name: UserRegistrationAPP</p> </li> <li><p><code>birthday.xml</code> Layout file:</p> <pre><code>&lt;vector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:width=&quot;24dp&quot; android:height=&quot;24dp&quot; android:viewportWidth=&quot;24&quot; android:viewportHeight=&quot;24&quot;&gt; &lt;path android:pathData=&quot;M19.313,5.097h-3.375L15.938,4h-1.125v1.097h-2.25L12.563,4L11.437,4v1.097h-2.25L9.187,4L8.062,4v1.097L4.687,5.097C3.757,5.097 3,5.835 3,6.742v12.613C3,20.262 3.757,21 4.687,21h14.626c0.93,0 1.687,-0.738 1.687,-1.645L21,6.742c0,-0.907 -0.757,-1.645 -1.687,-1.645zM19.875,19.355c0,0.302 -0.253,0.548 -0.562,0.548L4.687,19.903c-0.31,0 -0.562,-0.246 -0.562,-0.548L4.125,6.742c0,-0.303 0.252,-0.548 0.562,-0.548h3.375L8.062,7.29h1.125L9.187,6.194h2.25L11.437,7.29h1.126L12.563,6.194h2.25L14.813,7.29h1.125L15.938,6.194h3.375c0.31,0 0.562,0.245 0.562,0.548v12.613z&quot; android:fillColor=&quot;#D8D8D8&quot; android:fillType=&quot;nonZero&quot;/&gt; &lt;path android:pathData=&quot;M7,9h2.222v1.142L7,10.142L7,9zM10.889,9h2.222v1.142L10.89,10.142L10.89,9zM14.778,9L17,9v1.142h-2.222L14.778,9zM7,12.429h2.222L9.222,13.57L7,13.57L7,12.43zM10.889,12.429h2.222L13.111,13.57L10.89,13.57L10.89,12.43zM14.778,12.429L17,12.429L17,13.57h-2.222L14.778,12.43zM7,15.857h2.222L9.222,17L7,17v-1.143zM10.889,15.857h2.222L13.111,17L10.89,17v-1.143zM14.778,15.857L17,15.857L17,17h-2.222v-1.143z&quot; android:fillColor=&quot;#D8D8D8&quot; android:fillType=&quot;nonZero&quot;/&gt; &lt;/vector&gt; </code></pre> </li> <li><p><code>email.xml</code> Layout file:</p> <pre><code>&lt;vector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:width=&quot;24dp&quot; android:height=&quot;24dp&quot; android:viewportWidth=&quot;24&quot; android:viewportHeight=&quot;24&quot;&gt; &lt;path android:pathData=&quot;M21.167,20.16L2.833,20.16C1.823,20.16 1,19.353 1,18.36L1,7.56C1,6.567 1.822,5.76 2.833,5.76h18.334C22.177,5.76 23,6.567 23,7.56v10.8c0,0.993 -0.822,1.8 -1.833,1.8zM2.833,6.66c-0.505,0 -0.916,0.404 -0.916,0.9v10.8c0,0.496 0.41,0.9 0.916,0.9h18.334c0.505,0 0.916,-0.404 0.916,-0.9L22.083,7.56c0,-0.496 -0.41,-0.9 -0.916,-0.9L2.833,6.66z&quot; android:fillColor=&quot;#D8D8D8&quot; android:fillType=&quot;nonZero&quot;/&gt; &lt;path android:pathData=&quot;M12.5,16.32L4.216,11.363c-0.22,-0.131 -0.282,-0.4 -0.14,-0.603 0.141,-0.203 0.434,-0.26 0.653,-0.13L12.5,15.28l7.771,-4.65c0.22,-0.13 0.512,-0.073 0.653,0.13 0.142,0.202 0.08,0.472 -0.14,0.603L12.5,16.32z&quot; android:fillColor=&quot;#D8D8D8&quot; android:fillType=&quot;nonZero&quot;/&gt; &lt;path android:pathData=&quot;M3.455,17.28c-0.147,0 -0.291,-0.075 -0.378,-0.214 -0.14,-0.22 -0.084,-0.518 0.126,-0.665l4.09,-2.88c0.21,-0.147 0.491,-0.088 0.63,0.133 0.14,0.22 0.084,0.518 -0.126,0.666l-4.09,2.88c-0.078,0.054 -0.165,0.08 -0.252,0.08zM20.545,17.28c-0.087,0 -0.174,-0.026 -0.252,-0.08l-4.09,-2.88c-0.21,-0.148 -0.266,-0.445 -0.126,-0.666 0.139,-0.22 0.42,-0.28 0.63,-0.133l4.09,2.88c0.21,0.147 0.266,0.445 0.126,0.665 -0.087,0.14 -0.231,0.214 -0.378,0.214z&quot; android:fillColor=&quot;#D8D8D8&quot; android:fillType=&quot;nonZero&quot;/&gt; &lt;/vector&gt; </code></pre> </li> <li><p><code>id.xml</code> Layout file:</p> <pre><code>&lt;vector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:width=&quot;24dp&quot; android:height=&quot;24dp&quot; android:viewportWidth=&quot;24&quot; android:viewportHeight=&quot;24&quot;&gt; &lt;path android:pathData=&quot;M21.508,20L1.492,20C1.22,20 1,19.78 1,19.508L1,5.492C1,5.22 1.22,5 1.492,5h20.016c0.272,0 0.492,0.22 0.492,0.492v1.009h-0.937L21.063,5.938L1.937,5.938v13.126h19.126L21.063,8.001L22,8.001v11.507c0,0.272 -0.22,0.492 -0.492,0.492z&quot; android:fillColor=&quot;#D8D8D8&quot; android:fillType=&quot;nonZero&quot;/&gt; &lt;path android:pathData=&quot;M7.5,13C6.12,13 5,11.88 5,10.501 5,9.123 6.12,8 7.5,8S10,9.12 10,10.499C10,11.877 8.88,13 7.5,13zM7.5,8.947c-0.855,0 -1.552,0.697 -1.552,1.552 0,0.855 0.697,1.551 1.552,1.551 0.855,0 1.552,-0.696 1.552,-1.551S8.355,8.947 7.5,8.947z&quot; android:fillColor=&quot;#D8D8D8&quot; android:fillType=&quot;nonZero&quot;/&gt; &lt;path android:pathData=&quot;M10.848,17L4.476,17C4.213,17 4,16.785 4,16.521c0,-1.092 0.314,-2.188 0.864,-3.01 0.647,-0.964 1.577,-1.494 2.622,-1.494 0.258,0 0.468,0.212 0.468,0.471 0,0.26 -0.21,0.472 -0.468,0.472 -0.925,0 -1.513,0.587 -1.844,1.08 -0.37,0.554 -0.611,1.269 -0.682,2.017h5.403c-0.106,-1.05 -0.556,-2.031 -1.207,-2.585 -0.197,-0.168 -0.222,-0.465 -0.056,-0.665 0.166,-0.199 0.461,-0.224 0.66,-0.057 0.966,0.818 1.563,2.264 1.563,3.771 0,0.264 -0.213,0.479 -0.475,0.479zM13.003,9L19,9v0.943h-5.997L13.003,9zM13.003,12.005L19,12.005v0.943h-5.997v-0.943zM13.003,15.047h4.123v0.944h-4.123v-0.944z&quot; android:fillColor=&quot;#D8D8D8&quot; android:fillType=&quot;nonZero&quot;/&gt; &lt;/vector&gt; </code></pre> </li> <li><p><code>name.xml</code> Layout file:</p> <pre><code>&lt;vector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:width=&quot;24dp&quot; android:height=&quot;24dp&quot; android:viewportWidth=&quot;24&quot; android:viewportHeight=&quot;24&quot;&gt; &lt;path android:pathData=&quot;M20.289,16.908c-0.452,-1.078 -1.103,-2.047 -1.928,-2.878 -0.826,-0.831 -1.789,-1.485 -2.86,-1.94 -0.308,-0.132 -0.623,-0.245 -0.943,-0.34 1.3,-0.847 2.165,-2.321 2.165,-3.995C16.723,5.133 14.603,3 11.998,3 9.392,3 7.273,5.133 7.273,7.755c0,1.674 0.864,3.148 2.164,3.995 -0.32,0.095 -0.634,0.208 -0.943,0.34 -1.07,0.455 -2.034,1.109 -2.86,1.94 -0.825,0.831 -1.475,1.8 -1.928,2.878C3.236,18.025 3,19.211 3,20.434c0,0.312 0.252,0.566 0.562,0.566 0.311,0 0.563,-0.254 0.563,-0.566 0,-2.117 0.819,-4.108 2.306,-5.605C7.918,13.333 9.896,12.51 12,12.51s4.081,0.824 5.569,2.32c1.487,1.497 2.306,3.488 2.306,5.605 0,0.312 0.252,0.566 0.563,0.566 0.31,0 0.562,-0.254 0.562,-0.566 -0.005,-1.223 -0.243,-2.41 -0.711,-3.526zM8.395,7.753c0,-1.997 1.616,-3.623 3.6,-3.623 1.985,0 3.6,1.626 3.6,3.623 0,1.997 -1.615,3.623 -3.6,3.623 -1.984,0 -3.6,-1.626 -3.6,-3.623z&quot; android:fillColor=&quot;#D8D8D8&quot; android:fillType=&quot;nonZero&quot;/&gt; &lt;/vector&gt; </code></pre> </li> <li><p><code>password.xml</code> Layout file:</p> <pre><code>&lt;vector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:width=&quot;24dp&quot; android:height=&quot;24dp&quot; android:viewportWidth=&quot;24&quot; android:viewportHeight=&quot;24&quot;&gt; &lt;path android:pathData=&quot;M20.311,10.334c-0.441,-0.443 -1.036,-0.691 -1.659,-0.691h-1.174L17.478,6.5C17.478,3.46 15.024,1 12,1 8.976,1 6.522,3.46 6.522,6.5v3.143L5.348,9.643c-0.623,0 -1.221,0.248 -1.66,0.691C3.249,10.777 3,11.374 3,12v1.964C3,18.955 7.029,23 12,23c2.385,0 4.677,-0.952 6.364,-2.646C20.051,18.66 21,16.362 21,13.964L21,12c0,-0.625 -0.247,-1.226 -0.689,-1.666zM8.087,6.5C8.087,4.331 9.84,2.571 12,2.571s3.913,1.76 3.913,3.929v3.143L8.087,9.643L8.087,6.5zM19.435,13.964c0,4.124 -3.328,7.465 -7.435,7.465 -4.107,0 -7.435,-3.341 -7.435,-7.465L4.565,12c0,-0.434 0.35,-0.786 0.783,-0.786h13.304c0.432,0 0.783,0.352 0.783,0.786v1.964z&quot; android:fillColor=&quot;#D8D8D8&quot; android:fillType=&quot;nonZero&quot;/&gt; &lt;path android:pathData=&quot;M12,12c-0.552,0 -1,0.373 -1,0.833v3.334c0,0.46 0.448,0.833 1,0.833s1,-0.373 1,-0.833v-3.334c0,-0.46 -0.448,-0.833 -1,-0.833z&quot; android:fillColor=&quot;#D8D8D8&quot; android:fillType=&quot;nonZero&quot;/&gt; &lt;/vector&gt; </code></pre> </li> <li><p><code>phone.xml</code> Layout file:</p> <pre><code>&lt;vector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:width=&quot;24dp&quot; android:height=&quot;24dp&quot; android:viewportWidth=&quot;24&quot; android:viewportHeight=&quot;24&quot;&gt; &lt;path android:pathData=&quot;M12.5,18.645c-0.64,0 -1.162,0.503 -1.162,1.121s0.522,1.121 1.162,1.121c0.64,0 1.162,-0.503 1.162,-1.12 0,-0.619 -0.522,-1.122 -1.162,-1.122zM18.247,1L6.753,1C5.787,1 5,1.76 5,2.692v18.616C5,22.24 5.787,23 6.753,23h11.494c0.966,0 1.753,-0.76 1.753,-1.692L20,2.692C20,1.76 19.213,1 18.247,1zM6.753,2.128h11.494c0.322,0 0.584,0.253 0.584,0.564L18.831,16.64L6.17,16.64L6.17,2.692c0,-0.31 0.262,-0.564 0.584,-0.564zM18.247,21.872L6.753,21.872c-0.322,0 -0.584,-0.253 -0.584,-0.564v-3.444h12.662v3.444c0,0.31 -0.262,0.564 -0.584,0.564z&quot; android:fillColor=&quot;#D8D8D8&quot; android:fillType=&quot;nonZero&quot;/&gt; &lt;/vector&gt; </code></pre> </li> <li><p><code>activity_main.xml</code> Layout file:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; tools:context=&quot;.MainActivity&quot;&gt; &lt;androidx.constraintlayout.widget.Guideline android:id=&quot;@+id/guideline_right2&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:orientation=&quot;vertical&quot; app:layout_constraintGuide_end=&quot;40dp&quot; /&gt; &lt;androidx.constraintlayout.widget.Guideline android:id=&quot;@+id/guideline_left&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:orientation=&quot;vertical&quot; app:layout_constraintGuide_begin=&quot;40dp&quot; /&gt; &lt;androidx.constraintlayout.widget.Guideline android:id=&quot;@+id/guideline_right&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:orientation=&quot;vertical&quot; app:layout_constraintGuide_end=&quot;40dp&quot; /&gt; &lt;ImageView android:id=&quot;@+id/img_bgName&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;0dp&quot; app:layout_constraintBottom_toBottomOf=&quot;@+id/editText_name&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/guideline_right&quot; app:layout_constraintHorizontal_bias=&quot;0.0&quot; app:layout_constraintStart_toStartOf=&quot;@+id/guideline_left&quot; app:layout_constraintTop_toTopOf=&quot;@+id/editText_name&quot; app:layout_constraintVertical_bias=&quot;1.0&quot; app:layout_constraintVertical_chainStyle=&quot;packed&quot; /&gt; &lt;ImageView android:id=&quot;@+id/img_bgID&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;0dp&quot; app:layout_constraintBottom_toBottomOf=&quot;@+id/editTextID&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/guideline_right&quot; app:layout_constraintHorizontal_bias=&quot;0.0&quot; app:layout_constraintStart_toStartOf=&quot;@+id/guideline_left&quot; app:layout_constraintTop_toTopOf=&quot;@+id/editTextID&quot; app:layout_constraintVertical_chainStyle=&quot;packed&quot; /&gt; &lt;ImageView android:id=&quot;@+id/img_bgPass&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;0dp&quot; app:layout_constraintBottom_toBottomOf=&quot;@+id/editTextID&quot; app:layout_constraintStart_toStartOf=&quot;@+id/guideline_left&quot; app:layout_constraintTop_toTopOf=&quot;@+id/editTextID&quot; app:layout_constraintVertical_bias=&quot;1.0&quot; /&gt; &lt;ImageView android:id=&quot;@+id/img_bgPass7&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;0dp&quot; app:layout_constraintBottom_toBottomOf=&quot;@+id/editTextBirthday&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/guideline_right2&quot; app:layout_constraintStart_toStartOf=&quot;@+id/guideline_left&quot; app:layout_constraintTop_toTopOf=&quot;@+id/editTextBirthday&quot; /&gt; &lt;ImageView android:id=&quot;@+id/img_bgPass8&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;0dp&quot; app:layout_constraintBottom_toBottomOf=&quot;@+id/editTextCellphone&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/guideline_right2&quot; app:layout_constraintStart_toStartOf=&quot;@+id/guideline_left&quot; app:layout_constraintTop_toTopOf=&quot;@+id/editTextCellphone&quot; /&gt; &lt;ImageView android:id=&quot;@+id/img_bgPass9&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;0dp&quot; app:layout_constraintBottom_toBottomOf=&quot;@+id/editTextEmail&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/guideline_right2&quot; app:layout_constraintStart_toStartOf=&quot;@+id/guideline_left&quot; app:layout_constraintTop_toTopOf=&quot;@+id/editTextEmail&quot; /&gt; &lt;ImageView android:id=&quot;@+id/img_bgPass10&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;0dp&quot; app:layout_constraintBottom_toBottomOf=&quot;@+id/editTextPassword&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/guideline_right2&quot; app:layout_constraintStart_toStartOf=&quot;@+id/guideline_left&quot; app:layout_constraintTop_toTopOf=&quot;@+id/editTextPassword&quot; /&gt; &lt;ImageView android:id=&quot;@+id/img_bgPass11&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;0dp&quot; app:layout_constraintBottom_toBottomOf=&quot;@+id/editTextPasswordAgain&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/guideline_right2&quot; app:layout_constraintStart_toStartOf=&quot;@+id/guideline_left&quot; app:layout_constraintTop_toTopOf=&quot;@+id/editTextPasswordAgain&quot; /&gt; &lt;EditText android:id=&quot;@+id/editText_name&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginStart=&quot;6dp&quot; android:layout_marginBottom=&quot;8dp&quot; android:backgroundTint=&quot;#00FFFFFF&quot; android:ems=&quot;18&quot; android:inputType=&quot;textPersonName&quot; android:text=&quot;@string/register_name&quot; android:textSize=&quot;12sp&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/editTextID&quot; app:layout_constraintStart_toEndOf=&quot;@+id/imageView12&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/textView2&quot; app:layout_constraintVertical_chainStyle=&quot;packed&quot; /&gt; &lt;EditText android:id=&quot;@+id/editTextID&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginStart=&quot;6dp&quot; android:layout_marginBottom=&quot;8dp&quot; android:backgroundTint=&quot;#00FFFFFF&quot; android:ems=&quot;18&quot; android:inputType=&quot;textPersonName&quot; android:text=&quot;@string/register_id&quot; android:textSize=&quot;12sp&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/editTextBirthday&quot; app:layout_constraintStart_toEndOf=&quot;@+id/imageView22&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/editText_name&quot; /&gt; &lt;EditText android:id=&quot;@+id/editTextBirthday&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginStart=&quot;6dp&quot; android:layout_marginBottom=&quot;8dp&quot; android:backgroundTint=&quot;#00FFFFFF&quot; android:ems=&quot;18&quot; android:inputType=&quot;textPersonName&quot; android:text=&quot;@string/register_birthday&quot; android:textSize=&quot;12sp&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/editTextCellphone&quot; app:layout_constraintStart_toEndOf=&quot;@+id/imageView17&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/editTextID&quot; /&gt; &lt;EditText android:id=&quot;@+id/editTextCellphone&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginStart=&quot;6dp&quot; android:layout_marginBottom=&quot;8dp&quot; android:backgroundTint=&quot;#00FFFFFF&quot; android:ems=&quot;18&quot; android:inputType=&quot;textPersonName&quot; android:text=&quot;@string/register_cellPhone&quot; android:textSize=&quot;12sp&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/editTextEmail&quot; app:layout_constraintStart_toEndOf=&quot;@+id/imageView19&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/editTextBirthday&quot; /&gt; &lt;EditText android:id=&quot;@+id/editTextEmail&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginStart=&quot;6dp&quot; android:layout_marginBottom=&quot;8dp&quot; android:backgroundTint=&quot;#00FFFFFF&quot; android:ems=&quot;18&quot; android:inputType=&quot;textPersonName&quot; android:text=&quot;@string/register_email&quot; android:textSize=&quot;12sp&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/editTextPassword&quot; app:layout_constraintStart_toEndOf=&quot;@+id/imageView21&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/editTextCellphone&quot; /&gt; &lt;EditText android:id=&quot;@+id/editTextPassword&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginStart=&quot;6dp&quot; android:layout_marginBottom=&quot;8dp&quot; android:backgroundTint=&quot;#00FFFFFF&quot; android:ems=&quot;18&quot; android:inputType=&quot;textPersonName&quot; android:text=&quot;@string/register_password&quot; android:textSize=&quot;12sp&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/editTextPasswordAgain&quot; app:layout_constraintStart_toEndOf=&quot;@+id/imageView20&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/editTextEmail&quot; /&gt; &lt;EditText android:id=&quot;@+id/editTextPasswordAgain&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginStart=&quot;6dp&quot; android:layout_marginBottom=&quot;12dp&quot; android:backgroundTint=&quot;#00FFFFFF&quot; android:ems=&quot;18&quot; android:inputType=&quot;textPersonName&quot; android:text=&quot;@string/register_PasswordAgain&quot; android:textSize=&quot;12sp&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/btn_apply&quot; app:layout_constraintStart_toEndOf=&quot;@+id/imageView18&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/editTextPassword&quot; /&gt; &lt;Button android:id=&quot;@+id/btn_apply&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;wrap_content&quot; android:text=&quot;Apply&quot; android:textColor=&quot;#FFFFFF&quot; android:textSize=&quot;18sp&quot; app:layout_constraintBottom_toBottomOf=&quot;parent&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/guideline_right&quot; app:layout_constraintHorizontal_bias=&quot;0.5&quot; app:layout_constraintStart_toStartOf=&quot;@+id/guideline_left&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/editTextPasswordAgain&quot; /&gt; &lt;TextView android:id=&quot;@+id/textView2&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginTop=&quot;64dp&quot; android:layout_marginBottom=&quot;16dp&quot; android:text=&quot;@string/registration_form_title&quot; android:textColor=&quot;#bf1f2a&quot; android:textSize=&quot;24sp&quot; app:layout_constraintBottom_toTopOf=&quot;&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/guideline_right&quot; app:layout_constraintHorizontal_bias=&quot;0.5&quot; app:layout_constraintStart_toStartOf=&quot;@+id/guideline_left&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; app:layout_constraintVertical_bias=&quot;0.4&quot; app:layout_constraintVertical_chainStyle=&quot;packed&quot; /&gt; &lt;ImageView android:id=&quot;@+id/imageView12&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginStart=&quot;8dp&quot; app:layout_constraintBottom_toBottomOf=&quot;@+id/img_bgName&quot; app:layout_constraintStart_toStartOf=&quot;@+id/img_bgName&quot; app:layout_constraintTop_toTopOf=&quot;@+id/img_bgName&quot; app:srcCompat=&quot;@drawable/name&quot; /&gt; &lt;ImageView android:id=&quot;@+id/imageView22&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginStart=&quot;8dp&quot; app:layout_constraintBottom_toBottomOf=&quot;@+id/img_bgID&quot; app:layout_constraintStart_toStartOf=&quot;@+id/img_bgID&quot; app:layout_constraintTop_toTopOf=&quot;@+id/img_bgID&quot; app:srcCompat=&quot;@drawable/id&quot; /&gt; &lt;ImageView android:id=&quot;@+id/imageView17&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginStart=&quot;8dp&quot; app:layout_constraintBottom_toBottomOf=&quot;@+id/img_bgPass7&quot; app:layout_constraintStart_toStartOf=&quot;@+id/guideline_left&quot; app:layout_constraintTop_toTopOf=&quot;@+id/img_bgPass7&quot; app:srcCompat=&quot;@drawable/birthday&quot; /&gt; &lt;ImageView android:id=&quot;@+id/imageView18&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginStart=&quot;8dp&quot; app:layout_constraintBottom_toBottomOf=&quot;@+id/img_bgPass11&quot; app:layout_constraintStart_toStartOf=&quot;@+id/img_bgPass11&quot; app:layout_constraintTop_toTopOf=&quot;@+id/img_bgPass11&quot; app:srcCompat=&quot;@drawable/password&quot; /&gt; &lt;ImageView android:id=&quot;@+id/imageView21&quot; android:layout_width=&quot;24dp&quot; android:layout_height=&quot;24dp&quot; android:layout_marginStart=&quot;8dp&quot; app:layout_constraintBottom_toBottomOf=&quot;@+id/img_bgPass9&quot; app:layout_constraintStart_toStartOf=&quot;@+id/img_bgPass9&quot; app:layout_constraintTop_toTopOf=&quot;@+id/img_bgPass9&quot; app:srcCompat=&quot;@drawable/email&quot; /&gt; &lt;ImageView android:id=&quot;@+id/imageView20&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginStart=&quot;8dp&quot; app:layout_constraintBottom_toBottomOf=&quot;@+id/img_bgPass10&quot; app:layout_constraintStart_toStartOf=&quot;@+id/img_bgPass10&quot; app:layout_constraintTop_toTopOf=&quot;@+id/img_bgPass10&quot; app:srcCompat=&quot;@drawable/password&quot; /&gt; &lt;ImageView android:id=&quot;@+id/imageView19&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginStart=&quot;8dp&quot; app:layout_constraintBottom_toBottomOf=&quot;@+id/img_bgPass8&quot; app:layout_constraintStart_toStartOf=&quot;@+id/img_bgPass8&quot; app:layout_constraintTop_toTopOf=&quot;@+id/img_bgPass8&quot; app:srcCompat=&quot;@drawable/phone&quot; /&gt; &lt;androidx.constraintlayout.widget.Guideline android:id=&quot;@+id/guideline&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:orientation=&quot;vertical&quot; app:layout_constraintGuide_begin=&quot;15dp&quot; /&gt; &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt; </code></pre> </li> <li><p><code>User</code> class implementation:</p> <pre><code>package com.example.userregistrationapp; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Locale; public class User implements java.io.Serializable{ private String fullName; private String personalID; private String dateOfBirth; private String cellPhoneNumber; private String emailInfo; private String password; private final String dateFormat = &quot;yyyy-MM-dd&quot;; public User(String fullNameInput, String personalIDInput, String dateOfBirthInput, String cellPhoneNumberInput, String emailInfoInput, String passwordInput) throws NoSuchAlgorithmException, NullPointerException, IllegalArgumentException // User object constructor { // Reference: https://stackoverflow.com/a/6358/6667035 if (fullNameInput == null) { throw new NullPointerException(&quot;fullNameInput must not be null&quot;); } this.fullName = fullNameInput; if (personalIDInput == null) { throw new NullPointerException(&quot;personalIDInput must not be null&quot;); } this.personalID = personalIDInput; if (dateOfBirthInput == null) { throw new NullPointerException(&quot;dateOfBirthInput must not be null&quot;); } this.dateOfBirth = dateOfBirthInput; if (cellPhoneNumberInput == null) { throw new NullPointerException(&quot;cellPhoneNumberInput must not be null&quot;); } this.cellPhoneNumber = cellPhoneNumberInput; if (emailInfoInput == null) { throw new NullPointerException(&quot;emailInfoInput must not be null&quot;); } this.emailInfo = emailInfoInput; if (passwordInput == null) { throw new NullPointerException(&quot;passwordInput must not be null&quot;); } this.password = hashingMethod(passwordInput); } public String getFullName() { return this.fullName; } public String getPersonalID() { return this.personalID; } public String getDateOfBirth() { return this.dateOfBirth; } public String getCellPhoneNumber() { return this.cellPhoneNumber; } public String getEmailInfo() { return this.emailInfo; } public String getHash() throws NoSuchAlgorithmException { return hashingMethod(this.fullName + this.personalID); } public String getHashedPassword() throws NoSuchAlgorithmException { return this.password; } public boolean checkPassword(String password) { boolean result = false; try { result = this.password.equals(hashingMethod(password)); } catch (Exception e) { e.printStackTrace(); } return result; } //********************************************************************************************** // Reference: https://stackoverflow.com/a/2624385/6667035 private String hashingMethod(String inputString) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance(&quot;SHA-256&quot;); String stringToHash = inputString; messageDigest.update(stringToHash.getBytes()); String stringHash = new String(messageDigest.digest()); return stringHash; } } </code></pre> </li> <li><p><code>strings.xml</code>:</p> <pre><code>&lt;resources&gt; &lt;string name=&quot;app_name&quot;&gt;UserRegistrationAPP&lt;/string&gt; &lt;string name=&quot;registration_form_title&quot;&gt;Registration Form&lt;/string&gt; &lt;string name=&quot;register_name&quot;&gt;Name&lt;/string&gt; &lt;string name=&quot;register_id&quot;&gt;ID&lt;/string&gt; &lt;string name=&quot;register_birthday&quot;&gt;birthday&lt;/string&gt; &lt;string name=&quot;register_cellPhone&quot;&gt;CellPhone&lt;/string&gt; &lt;string name=&quot;register_email&quot;&gt;Email&lt;/string&gt; &lt;string name=&quot;register_password&quot;&gt;Password&lt;/string&gt; &lt;string name=&quot;register_PasswordAgain&quot;&gt;Type Password Again&lt;/string&gt; &lt;string name=&quot;register_name_null_message&quot;&gt;Please fill in name!&lt;/string&gt; &lt;string name=&quot;please_fill_in_register_id&quot;&gt;Please fill in ID!&lt;/string&gt; &lt;string name=&quot;please_select_birthday&quot;&gt;Please select birthday!&lt;/string&gt; &lt;string name=&quot;please_fill_in_register_cellPhone&quot;&gt;Please fill in cellphone number!&lt;/string&gt; &lt;string name=&quot;please_fill_in_register_cellPhone_number&quot;&gt;Please fill in correct cellphone number!&lt;/string&gt; &lt;string name=&quot;please_fill_in_Email&quot;&gt;Please fill in Email!&lt;/string&gt; &lt;string name=&quot;please_fill_in_correct_Email&quot;&gt;Please fill in correct Email!&lt;/string&gt; &lt;string name=&quot;please_fill_in_password&quot;&gt;Please fill in password!&lt;/string&gt; &lt;string name=&quot;please_fill_in_confirm_password&quot;&gt;Please fill in password again!&lt;/string&gt; &lt;string name=&quot;confirmation_password_not_equal&quot;&gt;Please check passwords are equal!&lt;/string&gt; &lt;string name=&quot;send&quot;&gt;Registration information have been sent!&lt;/string&gt; &lt;string name=&quot;OK&quot;&gt;OK&lt;/string&gt; &lt;/resources&gt; </code></pre> </li> <li><p><code>MainActivity.java</code> implementation:</p> <pre><code>package com.example.userregistrationapp; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.os.Bundle; import android.text.InputType; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.security.NoSuchAlgorithmException; import java.util.Calendar; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText nameEditText = findViewById(R.id.editText_name); clickAndClear(nameEditText); final EditText personalIDEditText = findViewById(R.id.editTextID); clickAndClear(personalIDEditText); final EditText dateOfBirthInfoEditText = findViewById(R.id.editTextBirthday); View.OnClickListener dateOfBirthInfoClickHandler = v -&gt; { if (v ==dateOfBirthInfoEditText) { Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); new android.app.DatePickerDialog(v.getContext(), (view, year1, month1, day1) -&gt; { String dateTime = String.valueOf(year1)+&quot;-&quot;+String.valueOf(month1)+&quot;-&quot;+String.valueOf(day1); dateOfBirthInfoEditText.setText(dateTime); }, year, month, day).show(); } }; dateOfBirthInfoEditText.setOnClickListener(dateOfBirthInfoClickHandler); final EditText cellphoneNumberEditText = findViewById(R.id.editTextCellphone); clickAndClear(cellphoneNumberEditText); final EditText emailInfoEditText = findViewById(R.id.editTextEmail); clickAndClear(emailInfoEditText); final EditText passwordEditText = findViewById(R.id.editTextPassword); clickAndClear(passwordEditText, true); final EditText confirmPasswordEditText = findViewById(R.id.editTextPasswordAgain); clickAndClear(confirmPasswordEditText, true); final Button applyButton = findViewById(R.id.btn_apply); View.OnClickListener ApplyButtonClickHandler = v -&gt; { if (v == applyButton) { // Parsing Information String nameString = getEditTextContent(nameEditText); String personalIDString = getEditTextContent(personalIDEditText); String dateOfBirtString = getEditTextContent(dateOfBirthInfoEditText); String cellphoneNumberString = getEditTextContent(cellphoneNumberEditText); String emailInfoString = getEditTextContent(emailInfoEditText); String passwordString = getEditTextContent(passwordEditText); String confirmPasswordString = getEditTextContent(confirmPasswordEditText); // Checking Information if ((nameString.isEmpty()) || (nameString.contains(getResources().getString(R.string.register_name)))) { showAlertDialog(getResources().getString(R.string.register_name_null_message), getResources().getString(R.string.OK)); return; } if ((personalIDString.isEmpty()) || (personalIDString.equals(getResources().getString(R.string.register_id)))) { showAlertDialog(getResources().getString(R.string.please_fill_in_register_id), getResources().getString(R.string.OK)); return; } if ((dateOfBirtString.isEmpty()) || (dateOfBirtString.equals(getResources().getString(R.string.register_birthday)))) { showAlertDialog(getResources().getString(R.string.please_select_birthday), getResources().getString(R.string.OK)); return; } if ((cellphoneNumberString.isEmpty()) || (cellphoneNumberString.equals(getResources().getString(R.string.register_cellPhone)))) { showAlertDialog(getResources().getString(R.string.please_fill_in_register_cellPhone), getResources().getString(R.string.OK)); return; } if (checkCellphoneNumber(cellphoneNumberEditText.getText().toString()) == false) { showAlertDialog(getResources().getString(R.string.please_fill_in_register_cellPhone_number), getResources().getString(R.string.OK)); return; } if ((emailInfoString.isEmpty()) || (emailInfoString.equals(getResources().getString(R.string.register_email)))) { showAlertDialog(getResources().getString(R.string.please_fill_in_Email), getResources().getString(R.string.OK)); return; } if (checkEmail(emailInfoString)==false) { showAlertDialog(getResources().getString(R.string.please_fill_in_correct_Email), getResources().getString(R.string.OK)); return; } if (passwordString.isEmpty() || passwordString.equals(getResources().getString(R.string.register_password))) { showAlertDialog(getResources().getString(R.string.please_fill_in_password), getResources().getString(R.string.OK)); return; } if (confirmPasswordString.isEmpty()) { showAlertDialog(getResources().getString(R.string.please_fill_in_confirm_password), getResources().getString(R.string.OK)); return; } if (passwordString.equals(confirmPasswordString) == false) { showAlertDialog(getResources().getString(R.string.confirmation_password_not_equal), getResources().getString(R.string.OK)); return; } try { sendRegisterInfo(new User( nameString, personalIDString, dateOfBirtString, cellphoneNumberString, emailInfoString, passwordString )); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } showToast(getResources().getString(R.string.send), Toast.LENGTH_SHORT); } }; applyButton.setOnClickListener(ApplyButtonClickHandler); return; } private void sendRegisterInfo(User newUser) { // TODO: perform send operation! return; } private boolean checkEmail(String input) { return input.contains(&quot;@&quot;); } private boolean checkCellphoneNumber(String input) { return isNumeric(input); } private boolean isNumeric(String s) { return s != null &amp;&amp; s.matches(&quot;[-+]?\\d*\\.?\\d+&quot;); } private String getEditTextContent(final EditText editTextInput) { return editTextInput.getText().toString(); } private void showToast(String textInput, int duration) { Context context = getApplicationContext(); CharSequence text = textInput; Toast toast = Toast.makeText(context, text, duration); toast.show(); } private void showAlertDialog(String titleString, String stringOnPositiveButton) { androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this); builder.setMessage(titleString) .setPositiveButton(stringOnPositiveButton, (dialog, id) -&gt; { }); builder.show(); } // clickAndClear method // Clear EditText content after clicking it. private void clickAndClear(final EditText editTextInput) { View.OnClickListener editTextViewClickHandler = v -&gt; { if (v == editTextInput) { editTextInput.setText(&quot;&quot;); } }; editTextInput.setOnClickListener(editTextViewClickHandler); } // clickAndClear method // Clear EditText content after clicking it. // If isPassword==true, hide characters like `***` with `.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);` syntax. private void clickAndClear(final EditText editTextInput, final boolean isPassword) { View.OnClickListener editTextViewClickHandler = v -&gt; { if (v == editTextInput) { editTextInput.setText(&quot;&quot;); if (isPassword ==true) { editTextInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } } }; editTextInput.setOnClickListener(editTextViewClickHandler); } } </code></pre> </li> </ul> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/260989/231235">Android APP User class implementation</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>Besides creating <code>User</code> class, the full registration page implementation is shown in this post.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any possible improvement, please let me know.</p> </li> </ul>
[]
[ { "body": "<h2>throws</h2>\n<p>Unchecked exceptions aren't usually declared as being thrown by functions. So you don't <em>really</em> need to say that the constructor can throw <code>NullPointerException</code>. I don't really like that you're throwing <code>NullPointerException</code>, it seems unusual to me, however as the linked question and it's many related questions say, this is an area of debate/personal taste. Your <code>User</code> constructor says it throws <code>IllegalArgumentException</code>, but I can't see an obvious place that this actually happens. Some IDEs will highlight these types of issues for you so that you don't forget to remove throws declarations if you remove the code that actually throws the exception...</p>\n<p>Your <code>getHashedPassword</code> definitely doesn't throw <code>NoSuchAlgorithmException</code> for example since it only returns a member variable.</p>\n<h2>this</h2>\n<p>You don't need to use <code>this.</code> ever time you reference a member variable. In most instances it just adds noise/overhead that doesn't need to be there. Generally speaking, the only time that I'd expect to see <code>this.</code> is if you're passing in parameters that have the same name as the member variable and you need to disambiguate the references (usually in a constructor or a set method).</p>\n<h2>catch</h2>\n<p>You rarely want to catch <code>Exception</code>. This is generally reserved for top level, catch all cases (such as around an API endpoint to allow the exception to be translated into a response code). If your code can actually handle an exception, then you should be catching the specific exceptions that you are interested in, that way you don't accidently ignore an exception you weren't really expecting. So, <code>checkPassword</code> should probably be catching <code>NoSuchAlgorithmException</code>.</p>\n<h2>Say what you mean...</h2>\n<p>It seems likely to me that <code>sendRegisterInfo</code> will have the possibility for failure. You've also coded your <code>User</code> constructor with the expectation that hashing the password might not work. This results in a try/catch block in your <code>MainActivity</code>. However, all the catch does is print the stack and swallow the exception. As far as the user is concerned, they get a toast telling them the registration information has been sent. It's generally bad customer relations to mislead your users...</p>\n<h2>Apply</h2>\n<p>Apply is a funny name for a button that sends registration information. Maybe it makes sense in the rest of the screen flow (which I haven't looked at), however I'd expect something more like <em>submit</em> or <em>register</em>.</p>\n<p>You're also directly setting the <code>android:text</code> to &quot;Apply&quot; in the button declaration. Generally you'd want to use a string resource instead, indeed buttons are one of the first things I'd expect you to want to internationalise if you wanted to support multiple languages in the future.</p>\n<h2>clickAndClear</h2>\n<p>I might have missed something, however this method looks like it would drive me a bit crazy as a user. It makes sense for you to clear the text box when I first click on it, if it has some default value in it. However to me, it looks like if I fill out your registration information, then realise I've missed a letter in my e-mail address and click to update it, that you'll throw away what I've previously typed and rather than just adding in the missing character I'll have to type the whole address in again from scratch. I'd find that rather frustrating.</p>\n<h2>Password</h2>\n<p>You're setting the inputType for your password fields programmatically. Is there a reason that you're not setting it directly in the layout file?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T10:36:16.173", "Id": "261417", "ParentId": "261346", "Score": "1" } } ]
{ "AcceptedAnswerId": "261417", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T16:24:54.683", "Id": "261346", "Score": "1", "Tags": [ "java", "object-oriented", "android", "error-handling", "classes" ], "Title": "Android APP user registration page implementation" }
261346
<p>I've written the following module to generate arbitrary triangles based on a subset of lengths and angles, like what <a href="https://www.calculator.net/triangle-calculator.html" rel="nofollow noreferrer">this</a> provides. It works well enough but as-written it's fairly repetitive. I'm new to OpenSCAD so I'd love some feedback if there are cleaner ways to express this (or obviously if there are bugs/edge cases I've missed).</p> <pre><code>// Creates a 2D triangle with the given sides and/or angles. // Any three parameters can be used to describe the triangle, e.g. // a=3,b=4,c=5; a=3,b=4,c_angle=90; and a=3,b_angle=53.13,c_angle=90 // all describe the same triangle. // Side c runs along the x axis, with side a leaving the origin at a_angle. // Reference: https://www.calculator.net/triangle-calculator.html module triangle(a=0,b=0,c=0,a_angle=0,b_angle=0,c_angle=0) { assert(a_angle==a_angle &amp;&amp; b_angle==b_angle &amp;&amp; c_angle==c_angle, &quot;Invalid triangle: impossible angles&quot;); // returns c function shared_angle(a, b, c_angle) = sqrt(pow(b,2)+pow(a,2)-2*b*a*cos(c_angle)); // returns c_angle function opposing_angle(a, a_angle, b) = asin(b*sin(a_angle)/a); // returns angles A, B, C if they sum to 180 // if one angle is unset (0) it will be set to the difference of the other two function triangle_angles(a, b, c) = let ( a = a &gt; 0 ? a : assert(b!=0 &amp;&amp; c!=0, &quot;Insufficient angles&quot;) 180 - b - c, b = b &gt; 0 ? b : assert(a!=0 &amp;&amp; c!=0, &quot;Insufficient angles&quot;) 180 - a - c, c = c &gt; 0 ? c : assert(a!=0 &amp;&amp; b!=0, &quot;Insufficient angles&quot;) 180 - a - b ) assert(a + b + c == 180, &quot;Invalid triangle: impossible angles&quot;) [a,b,c]; // returns b function angle_ratio(a, angle_a, angle_b) = a*sin(angle_b)/sin(angle_a); // Three Sides if (a&gt;0 &amp;&amp; b&gt;0 &amp;&amp; c&gt;0) { assert(a_angle==0 &amp;&amp; b_angle==0 &amp;&amp; c_angle==0, &quot;Too many arguments&quot;); let ( a_angle = acos((pow(b,2)+pow(c,2)-pow(a,2))/(2*b*c)) ) { assert(a_angle==a_angle, &quot;Invalid triangle: impossible lengths&quot;); assert(sin(a_angle)!= 0, &quot;Invalid triangle: colinear&quot;); polygon(points = [[0, 0], [c, 0], [b * cos(a_angle), b * sin(a_angle)]]); } // Shared Angle } else if (a&gt;0 &amp;&amp; b&gt;0 &amp;&amp; c_angle&gt;0) { assert(c==0 &amp;&amp; a_angle==0 &amp;&amp; b_angle==0, &quot;Too many arguments&quot;); triangle(a,b,shared_angle(a,b,c_angle)); } else if (a&gt;0 &amp;&amp; c&gt;0 &amp;&amp; b_angle&gt;0) { assert(b==0 &amp;&amp; a_angle==0 &amp;&amp; c_angle==0, &quot;Too many arguments&quot;); triangle(a,shared_angle(a,c,b_angle),c); } else if (b&gt;0 &amp;&amp; c&gt;0 &amp;&amp; a_angle&gt;0) { assert(a==0 &amp;&amp; b_angle==0 &amp;&amp; c_angle==0, &quot;Too many arguments&quot;); triangle(shared_angle(b,c,a_angle),b,c); // Opposing Angle } else if (a&gt;0 &amp;&amp; a_angle&gt;0 &amp;&amp; b&gt;0) { assert(c==0 &amp;&amp; c_angle==0 &amp;&amp; b_angle==0, &quot;Too many arguments&quot;); triangle(a=a,b=b,c_angle=opposing_angle(a,a_angle,b)); } else if (a&gt;0 &amp;&amp; a_angle&gt;0 &amp;&amp; c&gt;0) { assert(b==0 &amp;&amp; b_angle==0 &amp;&amp; c_angle==0, &quot;Too many arguments&quot;); triangle(a=a,c=c,b_angle=opposing_angle(a,a_angle,c)); } else if (b&gt;0 &amp;&amp; b_angle&gt;0 &amp;&amp; a&gt;0) { assert(c==0 &amp;&amp; c_angle==0 &amp;&amp; a_angle==0, &quot;Too many arguments&quot;); triangle(a=a,b=b,c_angle=opposing_angle(b,b_angle,a)); } else if (b&gt;0 &amp;&amp; b_angle&gt;0 &amp;&amp; c&gt;0) { assert(a==0 &amp;&amp; a_angle==0 &amp;&amp; c_angle==0, &quot;Too many arguments&quot;); triangle(a=a,c=c,a_angle=opposing_angle(b,b_angle,c)); } else if (c&gt;0 &amp;&amp; c_angle&gt;0 &amp;&amp; a&gt;0) { assert(b==0 &amp;&amp; b_angle==0 &amp;&amp; a_angle==0, &quot;Too many arguments&quot;); triangle(a=a,c=c,b_angle=opposing_angle(c,c_angle,a)); } else if (c&gt;0 &amp;&amp; c_angle&gt;0 &amp;&amp; b&gt;0) { assert(a == 0 &amp;&amp; a_angle == 0 &amp;&amp; b_angle == 0, &quot;Too many arguments&quot;); triangle(b = b, c = c, a_angle = opposing_angle(c, c_angle, b)); // Two+ Angles } else if (a&gt;0 &amp;&amp; b==0 &amp;&amp; c==0) { angles = triangle_angles(a_angle, b_angle, c_angle); triangle(a=a, b=angle_ratio(a,angles[0],angles[1]), c=angle_ratio(a,angles[0],angles[2])); } else if (b&gt;0 &amp;&amp; a==0 &amp;&amp; c==0) { angles = triangle_angles(a_angle, b_angle, c_angle); triangle(a=angle_ratio(b,angles[1],angles[0]), b=b, c=angle_ratio(b,angles[1],angles[2])); } else if (c&gt;0 &amp;&amp; a==0 &amp;&amp; b==0) { angles = triangle_angles(a_angle, b_angle, c_angle); triangle(a=angle_ratio(c,angles[2],angles[0]), b=angle_ratio(c,angles[2],angles[1]), c=c); } else { assert(false, &quot;Insufficient arguments&quot;); } } </code></pre> <p>Like the calculator, only three arguments are needed to specify a triangle. So for example these all define the same shape:</p> <pre><code>triangle(a=3, b=4, c=5); triangle(a=3, b=4, c_angle=90); triangle(a=3, b_angle=53.13, c_angle=90); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T07:42:33.843", "Id": "516183", "Score": "0", "body": "Hello, probably I am wrong but would it be possible define a triangle with just two sides and the angle between them (I don't know openscad) ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T17:34:18.893", "Id": "516241", "Score": "0", "body": "Right, that's the idea. Any three arguments are sufficient." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T20:38:08.320", "Id": "516259", "Score": "0", "body": "I read again your post, please ignore my previous question and thanks for the added details." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T20:11:20.007", "Id": "261351", "Score": "2", "Tags": [ "computational-geometry", "openscad" ], "Title": "Triangle module in OpenSCAD" }
261351
<p>My Python code (part of a Django site) queries data from a redis database and loads it into a Pandas dataframe. I'm new to redis, and I think I'm not using the redis library as efficiently as I could.</p> <p>The database keys are timestamps in epocho format. The values are all json strings. Here's a sample:</p> <pre><code>Keys: ['1622235486.006474000', '1622235486.006760000', '1622235486.114156000'] Values: ['{&quot;timestampx&quot;: &quot;1622235486.006474000&quot;, &quot;length&quot;: &quot;1416&quot;, &quot;dscp&quot;: &quot;0&quot;, &quot;srcip&quot;: &quot;172.17.4.2&quot;, &quot;destip&quot;: &quot;172.16.1.2&quot;}', '{&quot;timestampx&quot;: &quot;1622235486.006760000&quot;, &quot;length&quot;: &quot;108&quot;, &quot;dscp&quot;: &quot;0&quot;, &quot;srcip&quot;: &quot;172.16.1.2&quot;, &quot;destip&quot;: &quot;172.17.4.2&quot;}', '{&quot;timestampx&quot;: &quot;1622235486.114156000&quot;, &quot;length&quot;: &quot;112&quot;, &quot;dscp&quot;: &quot;0&quot;, &quot;srcip&quot;: &quot;172.17.4.2&quot;, &quot;destip&quot;: &quot;172.16.1.2&quot;}'] </code></pre> <p>Four questions about my code:</p> <ol> <li>First I get all keys with .keys(). Then I filter the list of keys. Then I use .mget(keys). Making two connections to redis (once to get keys, again to get values) seems inefficient. Is there a better method?</li> <li>Some of the keys aren't epoch timestamps. They start with &quot;1_&quot;, and they contain None values. I have to filter those out. I use a separate line of code to do that. Can I do that as part of the keys() function?</li> <li>I also have a line to sort the keys. Can I ask redis to return them sorted?</li> <li>Finally, is there an argument for .mget() that filters out None values?</li> </ol> <pre><code>import redis from datetime import datetime from datetime import timedelta import pandas as pd import json INTERVAL = 5 r = redis.StrictRedis(**redis_config) filter = datetime.now() - timedelta(seconds=INTERVAL) recentkeys = [] allkeys = r.keys(pattern=&quot;*&quot;) #Question 1. Is the best query keys() passed to mget()? allkeys = [x for x in allkeys if not x.startswith('1_')] #Question 2. Can I pass a filter to redis and have it filter the response? for k in allkeys: if float(k) &gt; float(filter.timestamp()): recentkeys.append(k) recentkeys.sort() #Question 3. Can redis return a sorted set? values = r.mget(recentkeys) values = [x for x in values if x != None] #Question 4. Can redis filter out None values? recent_values = pd.DataFrame(map(json.loads, values)) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T21:27:44.593", "Id": "261354", "Score": "1", "Tags": [ "python", "redis" ], "Title": "Python and redis. Make queries more efficient" }
261354
<p>this is my first post here!</p> <p>I am working on a Tic Tac Toe AI in Python that uses the Minimax Algorithm to beat either a computer or a normal player. As of now, It has approximately 70% chance of winning each game, but I am trying to increase that number. Here are a few tests that show results of the Perfect Player, which uses the minimax algorithm, against a normal computer player, which randomly chooses spots to play during the game:</p> <p>First test: <code>Perfect Player X won 67 time(s), Player O won 25 time(s), and there were 8 tie(s).</code></p> <p>Second test: <code>Perfect Player X won 70 time(s), Player O won 21 time(s), and there were 9 tie(s).</code></p> <p>Third test: <code>Perfect Player X won 68 time(s), Player O won 25 time(s), and there were 7 tie(s).</code></p> <p>The code I have for both the algorithm player (<code>PerfectPlayer</code>), as well as the normal computer player (<code>ComputerPlayer</code>), is below.</p> <pre><code># Recognise the player as an object, with a specific letter (X or O) class Player: # Set the player's letter (noughts or crosses) def __init__(self, letter): self.letter = letter # Turn-based system def get_move(self, game): pass # Perfect Tic Tac Toe AI using the Minimax Algorithm class PerfectPlayer(Player): # Initialize the player and it's letter def __init__(self, letter): super().__init__(letter) # Get the pefect move for the game -- where the MAGIC happens! def get_move(self, game): # If all moves are open, then do any random move if len(game.open_moves()) == 9: choice = random.choice(game.open_moves()) # If there are tokens on the board, then find the optimal move based on that token's position else: choice = self.minimax(game, self.letter)[&quot;position&quot;] return choice # Minimax, the engine for the magic! def minimax(self, state, player): # Get which player is who max_player = self.letter opponent = &quot;O&quot; if player == &quot;X&quot; else &quot;X&quot; # Check if game is over if state.current_winner == opponent: return { &quot;position&quot;: None, &quot;score&quot;: 1 * (state.empty_square_vals() + 1) if opponent == max_player else -1 * (state.empty_square_vals() + 1) } # Check if there are no empty squares elif not state.empty_squares(): return { &quot;position&quot;: None, &quot;score&quot;: 0 } if player == max_player: # Each score should maximize best = { &quot;position&quot;: None, &quot;score&quot;: -math.inf } else: # Each score should minimize best = { &quot;position&quot;: None, &quot;score&quot;: math.inf } for possible_move in state.open_moves(): # Try a spot state.make_move(possible_move, player) # Simulate a game with that move sim_score = self.minimax(state, opponent) # Undo the move (remember, it's only the simulation) state.board[possible_move] = &quot; &quot; state.current_winner = None sim_score[&quot;position&quot;] = possible_move # Maximize the 'max_player' if player == max_player: # If the simulated score from a specific move is the best option, do it if sim_score[&quot;score&quot;] &gt; best[&quot;score&quot;]: best = sim_score # Minimize the 'opponent' else: if sim_score[&quot;score&quot;] &lt; best[&quot;score&quot;]: best = sim_score return best # Use the inheritance of classes to create a computer player that uses the 'Player' class class ComputerPlayer(Player): # Set the computer's letter with teh super class def __init__(self, letter): super().__init__(letter) # Turn-based system, get a random move from all open possibilities def get_move(self, game): choice = random.choice(game.open_moves()) return choice </code></pre> <p>Does anyone have any recommendations on how to improve my algorithm? Alternatively, suggestions for different methods to win also work.</p> <p>Also, please let me know if I am lacking any necessary code (not all is included here, but I can provide more if wanted). Thank you in advance!</p> <p>EDIT: I've been informed that I should include a few bits of code, so here they are.</p> <p><em><strong>game.py:</strong></em></p> <pre><code># Import other Python file and classes for game from player import NormalPlayer, ComputerPlayer, PerfectPlayer from store import store_results empty = &quot; &quot; # Store results? store = True def update_board(this): print(&quot;╭-----------╮&quot;) this.print_board_values() print(&quot;|-----------|&quot;) this.print_board() print(&quot;╰-----------╯&quot;) # Tic Tac Toe game class TicTacToe: # Initialize the game features def __init__(self): # Create an empty board list with 9 free spots self.board = [empty for _ in range(9)] # Track the current winner of the game self.current_winner = None # Method to print the board def print_board(self): # Create the board rows and print for row in [self.board[x * 3: (x + 1) * 3] for x in range(3)]: print(&quot;| &quot; + &quot; | &quot;.join(row) + &quot; |&quot;) # This is a static method, as it doesn't require the 'self' parameter def print_board_values(self): # Set the board with spot values # | 0, 1, 2... 6, 7, 8 | number_board = [[str(value) for value in range(row * 3, (row + 1) * 3)] for row in range(3)] # Print out the board with the spot values for row in number_board: print(&quot;| &quot; + &quot; | &quot;.join(row) + &quot; |&quot;) # Check for all the possible moves for the game def open_moves(self): # Enumerate, or list, all spot values that are empty return [i for i, spot in enumerate(self.board) if spot == empty] # Return all the empty board spots def empty_squares(self): return empty in self.board # Return the number of possible moves def empty_square_vals(self): return self.board.count(empty) # Method to update the board with player moves def make_move(self, choice, letter): # If the spot is open, then set the board accordingly if self.board[choice] == empty: self.board[choice] = letter # Check for the winner if self.winner(choice, letter): self.current_winner = letter return True return False # If any player makes 3 in a row, they are the winner def winner(self, choice, letter): # Check rows for tic tac toe row_ind = choice // 3 row = self.board[row_ind * 3 : (row_ind + 1) * 3] if all([spot == letter for spot in row]): return True # Check columns for tic tac toe col_ind = choice % 3 col = [self.board[col_ind + i * 3] for i in range(3)] if all([spot == letter for spot in col]): return True # Check diagonals for tic tac toe if choice % 2 == 0: # Left to right diagonal1 = [self.board[i] for i in [0, 4, 8]] if all([spot == letter for spot in diagonal1]): return True # Right to left diagonal2 = [self.board[i] for i in [2, 4, 6]] if all([spot == letter for spot in diagonal2]): return True def play(game, x_player, o_player, print_game = True): # Print the board if print_game: print(&quot;&quot;) update_board(game) print(&quot;&quot;) # Cross player statrts letter = &quot;X&quot; # Keep running the game procedure as long s no one has won, and there are empty spaces while game.empty_squares(): # If the noughts player is going, ask for their move if letter == &quot;O&quot;: choice = o_player.get_move(game) # If the crosses player is going, ask for their move else: choice = x_player.get_move(game) # Print out the game updates if game.make_move(choice, letter): # Print which player went, and where if print_game: print(&quot;&quot;) print(&quot;Player &quot; + letter + &quot; played &quot; + str(choice) + &quot;!&quot;) update_board(game) print(&quot;&quot;) # If there is a winner, announce who won! if game.current_winner: if print_game: print(letter + &quot; won the game!&quot;) return letter # Switch the player turns letter = &quot;O&quot; if letter == &quot;X&quot; else &quot;X&quot; # If no one wins, say it is a tie if print_game: print(&quot;It's a tie!&quot;) # Play the game if __name__ == &quot;__main__&quot;: x_wins = 0 o_wins = 0 ties = 0 # Check how many times the game should be run games = input(&quot;How many games do you want to run? &quot;) if games == &quot;&quot;: games = 100 # Repeat game over and over for _ in range(int(games)): x_player = PerfectPlayer(&quot;X&quot;) # Minimax Player o_player = ComputerPlayer(&quot;O&quot;) ttt = TicTacToe() result = play(ttt, x_player, o_player, print_game = True) if result == &quot;X&quot;: x_wins += 1 elif result == &quot;O&quot;: o_wins += 1 else: ties += 1 # Say who won how many times print(&quot;Perfect Player X won &quot; + str(x_wins) + &quot; time(s), Player O won &quot; + str(o_wins) + &quot; time(s), and there were &quot; + str(ties) + &quot; tie(s).&quot;) if type(x_player).__name__ == &quot;PerfectPlayer&quot; and type(o_player).__name__ == &quot;ComputerPlayer&quot; and store: print(&quot;&quot;) # Store results store_results(x_wins, o_wins, ties) </code></pre> <p><em><strong>player.py:</strong></em></p> <pre><code># Things to keep in mind... # The official term for the X's and O's in Tic-Tac-Toe are Noughts (O) and Crosses (X) # The board is stored as a list, with values ranging from 0 (top left) to 8 (bottom right) # The Tic-Tac-Toe AI uses the minimax algorthim, that predicts possible moves from the current board state # All imports here! import math import random empty = &quot; &quot; # Recognise the player as an object, with a specific letter (X or O) class Player: # Set the player's letter (noughts or crosses) def __init__(self, letter): self.letter = letter # Turn-based system def get_move(self, game): pass # Use the inheritance of classes to create a computer player that uses the 'Player' class class ComputerPlayer(Player): # Set the computer's letter with teh super class def __init__(self, letter): super().__init__(letter) # Turn-based system, get a random move from all open possibilities def get_move(self, game): choice = random.choice(game.open_moves()) return choice # Use the inheritance of classes for the user object that uses the 'Player' class class NormalPlayer(Player): # Set the user's letter with the super class def __init__(self, letter): super().__init__(letter) # Turn-based system, get the player's movement choice def get_move(self, game): # Player's choice must first be verified verified = False # The spot value of the move the player wants to make value = None # Ask for the player's move while not verified: choice = input(self.letter + &quot;'s turn. Which spot do you want to play? &quot;) # Check if the player's choice is valid... try: # Turn the input into an integer value = int(choice) verified = True # If the spot value is not available, catch the error and tell the player if value not in game.open_moves(): verified = False raise ValueError # ...if it is, then announce it except ValueError: # If the choice was invalid, have the player decide their move again print(&quot;The spot value is not valid. Please choose another spot.&quot;) return value # Perfect Tic Tac Toe AI using the Minimax Algorithm class PerfectPlayer(Player): # Initialize the player and it's letter def __init__(self, letter): super().__init__(letter) # Get the pefect move for the game -- where the MAGIC happens! def get_move(self, game): # If all moves are open, then do any random move if len(game.open_moves()) == 9: choice = random.choice(game.open_moves()) # If there are tokens on the board, then find the optimal move based on that token's position else: choice = self.minimax(game, self.letter)[&quot;position&quot;] return choice # Minimax, the engine for the magic! def minimax(self, state, player): # Get which player is who max_player = self.letter opponent = &quot;O&quot; if player == &quot;X&quot; else &quot;X&quot; # Check if game is over if state.current_winner == opponent: return { &quot;position&quot;: None, &quot;score&quot;: 1 * (state.empty_square_vals() + 1) if opponent == max_player else -1 * (state.empty_square_vals() + 1) } # Check if there are no empty squares elif not state.empty_squares(): return { &quot;position&quot;: None, &quot;score&quot;: 0 } if player == max_player: # Each score should maximize best = { &quot;position&quot;: None, &quot;score&quot;: -math.inf } else: # Each score should minimize best = { &quot;position&quot;: None, &quot;score&quot;: math.inf } for possible_move in state.open_moves(): # Try a spot state.make_move(possible_move, player) # Simulate a game with that move sim_score = self.minimax(state, opponent) # Undo the move (remember, it's only the simulation) state.board[possible_move] = empty state.current_winner = None sim_score[&quot;position&quot;] = possible_move # Maximize the 'max_player' if player == max_player: # If the simulated score from a specific move is the best option, do it if sim_score[&quot;score&quot;] &gt; best[&quot;score&quot;]: best = sim_score # Minimize the 'opponent' else: if sim_score[&quot;score&quot;] &lt; best[&quot;score&quot;]: best = sim_score return best </code></pre> <p>Also, please note that the minimax user does indeed lose at time. Although ~70% of the games are won by it, it does lose and tie a small fraction of games to the randomized choice opponent.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T14:07:30.367", "Id": "515799", "Score": "3", "body": "Welcome to CR! This site is for reviews of code that [works to the best of your knowledge](https://codereview.stackexchange.com/help/on-topic). If you intend 100% non-loss rate for your AI (you can't guarantee anything better than a draw given perfect play on both sides), there's more work to be done before the question is ready for CR. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T16:37:52.260", "Id": "516092", "Score": "1", "body": "\"_As of now, It has approximately 70% chance of winning each game, but I am trying to increase that number._\" Are the rest of the games a draw, or does the computer lose a portion of the games as well? This is important to determine whether your program indeed works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T19:49:21.800", "Id": "516104", "Score": "0", "body": "Hello please can you include the code for `game` in your question. The inclusion of missing imports, such as `math`, would also help. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T02:19:30.837", "Id": "516111", "Score": "0", "body": "Thank you all so much for your advice! I've edited my original post with the required code, and the information you asked for. No, the minimax user does not always win, and does lose at times. I've included the two main files, game.py and player.py, into my post, which has the imports needed for the project. if necessary, it is perfectly possible to copy-paste the code into an IDE to test the code for yourself. Once again, thank you so much!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T10:53:19.750", "Id": "516121", "Score": "0", "body": "One of the main \"issues\" in terms of TTT is that no player can _force_ a victory. A single experienced player, no matter their turn order, can force a tie every single time. So the question becomes how the learning algorithm treats a tie. Is it considered a defeat? A victory? Should the engine risk a move where they could win _or_ lose, if there is also the option of forcing a tie, i.e. does the engine _avoid loss_ or does it _seek victory_? Do tied games \"not exist\" in terms of the learning experience? These valuations matter, but they are subjective." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T11:00:17.560", "Id": "516122", "Score": "0", "body": "Secondly, minimax assumes that _both_ players make the same kind of evaluation. If one player picks randomly, that actually throws a wrench in your assumption logic. Minimax does not account for players making decisions _against_ their own interest. This is important, because I also learned that my algorithm (not minimax, but irrelevant) **could not improve against a randomizer** as much as it improved against a second machine (or human player). Randomizers actually make it harder to learn what a proper strategy is, because you could win with a bad strategy if the randomizer throws the game." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T12:53:06.933", "Id": "516201", "Score": "0", "body": "*\"Alternatively, suggestions for different methods to win also work.\"* - there is [this great trick](https://codegolf.stackexchange.com/a/218779/53377). But also, the number of possible tic tac toe boards is so small that you can just store all best responses to every position." } ]
[ { "body": "<p>Tic-tac-toe is easily <em>solved</em>. That means there's no reason for your <code>PerfectPlayer</code> to not actually be perfect: It should <em>never loose</em> (and against a moves-randomly opponent, it should win quite often).</p>\n<p>So clearly there's something wrong with your minimax algorithm. Why is the scoring so complicated? Why does the algorithm care who's turn it &quot;really&quot; is? Is <code>return best</code> <em>supposed</em> to be inside the <code>for possible_move...</code> loop?</p>\n<ul>\n<li>Keep your formatting boring. You can use a checker like <a href=\"https://pycodestyle.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">pycodestyle</a>. (I don't like all its rules, but the point of a checker is to not spend the time worrying <em>if</em> your code's correctly formatted.)</li>\n<li>Try to make invalid states unrepresentable. Using strings for data that isn't arbitrary text isn't great. Using dicts for data with known structure also isn't great.</li>\n<li>For the purpose of limiting what's &quot;representable&quot;, I like to use type annotations. But note that python doesn't inherently check types; if you want your type annotations to be anything more than fancy comments, you'll have to use an external tool like <a href=\"http://mypy-lang.org/\" rel=\"nofollow noreferrer\">mypy</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T14:19:13.563", "Id": "261378", "ParentId": "261355", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T22:06:39.507", "Id": "261355", "Score": "2", "Tags": [ "python", "performance", "algorithm", "tic-tac-toe" ], "Title": "How to increase the success rate of my Tic Tac Toe AI that uses the Minimax Algorithm?" }
261355
<p>I'm using Flask on Python and I'm displaying the username at the top of the site (and it's working) as follows:</p> <pre class="lang-py prettyprint-override"><code>@app.route(&quot;/&quot;) @login_required def index(): &quot;&quot;&quot;Queries the user's First Name to display in the title&quot;&quot;&quot; names = db.execute(&quot;&quot;&quot; SELECT first_name FROM users WHERE id=:user_id &quot;&quot;&quot;, user_id = session[&quot;user_id&quot;] ) return render_template(&quot;index.html&quot;, names = names) </code></pre> <pre class="lang-html prettyprint-override"><code>&lt;header class=&quot;mainHeader&quot;&gt; {% for name in names %} &lt;h1&gt;{{ name[&quot;first_name&quot;] }}' Bookshelf&lt;/h1&gt; {% else %} &lt;h1&gt;Your Bookshelf&lt;/h1&gt; {% endfor %} &lt;/header&gt; </code></pre> <p>I don't know if it is necessary, but here is my database configuration:</p> <p><a href="https://i.stack.imgur.com/Fu0kC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Fu0kC.png" alt="TABLE: users -- id: integer, email: text, first_name: text, last_name: text, picture: text" /></a></p> <p>Although it is working, I believe that it is not ideal to use for loop to display just one name. Does anyone have any suggestions?</p> <hr> Editing to include login routine: <pre class="lang-py prettyprint-override"><code>@app.route(&quot;/login&quot;, methods=[&quot;GET&quot;, &quot;POST&quot;]) def login(): &quot;&quot;&quot;Log user in&quot;&quot;&quot; # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == &quot;POST&quot;: # Ensure email and password was submitted result_checks = is_provided(&quot;email&quot;) or is_provided(&quot;password&quot;) if result_checks is not None: return result_checks # Query database for email rows = db.execute(&quot;SELECT * FROM users WHERE email = ?&quot;, request.form.get(&quot;email&quot;)) # Ensure email exists and password is correct if len(rows) != 1 or not check_password_hash(rows[0][&quot;hash&quot;], request.form.get(&quot;password&quot;)): return &quot;E-mail ou Senha inválidos&quot; # Remember which user has logged in session[&quot;user_id&quot;] = rows[0][&quot;id&quot;] session[&quot;email&quot;] = request.form.get(&quot;email&quot;) # Redirect user to home page return redirect(&quot;/&quot;) # User reached route via GET (as by clicking a link or via redirect) else: return render_template(&quot;login.html&quot;) </code></pre>
[]
[ { "body": "<p>according to the query, it seems that the row count is either 0 or 1. so the loop would either have no iterations (the <code>else</code> part) or have exactly one iteration.</p>\n<p>in terms of performance, I think that any improvement here is not dramatic.</p>\n<p>however, in terms of choosing the right coding tools for the job, it seems that a loop is not the right tool.</p>\n<p>maybe the following would be better:</p>\n<pre><code>@app.route(&quot;/&quot;)\n@login_required\ndef index():\n &quot;&quot;&quot;Queries the user's First Name to display in the title&quot;&quot;&quot;\n names = db.execute(&quot;&quot;&quot;\n SELECT first_name\n FROM users\n WHERE id=:user_id\n &quot;&quot;&quot;,\n user_id = session[&quot;user_id&quot;] \n )\n first_name = names[0][&quot;first_name&quot;] if names else None\n return render_template(&quot;index.html&quot;, first_name = first_name)\n</code></pre>\n<p>and then:</p>\n<pre><code>&lt;header class=&quot;mainHeader&quot;&gt;\n {% if first_name %}\n &lt;h1&gt;{{ first_name }}'s Bookshelf&lt;/h1&gt;\n {% else %}\n &lt;h1&gt;Your Bookshelf&lt;/h1&gt;\n {% endif %}\n&lt;/header&gt;\n</code></pre>\n<p>note: I didn't test the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T23:28:44.653", "Id": "515761", "Score": "0", "body": "It is working fine! I really appreciate! The `else` was there because I was trying to implement an if statement and then I forgot to remove before inserting the code here. Thanks @Ron!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T22:56:36.340", "Id": "261357", "ParentId": "261356", "Score": "1" } }, { "body": "<p>To be honest, this is a case where you are expecting exactly one record (right ?), given that there must be a valid session for a logged-in user. So, if anything else happens (no record or worse, more than one record) I would trigger an exception. Either there is a problem with your database or your programming logic. If I'm not wrong, this is a not a page that allows anonymous access anyway.</p>\n<p>I assume that you use <a href=\"https://flask-login.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\">Flask-Login</a>. Personally I use a custom User class like this, but with Flask SQL Alchemy as the ORM:</p>\n<pre><code>class User(UserMixin, db.Model):\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(50), unique=True, nullable=False)\n # add more ...\n</code></pre>\n<p>So when the login is made some additional fields are already populated from the DB as per the data model. You just have to display them. These are session variables, so they don't have to be reloaded every time. They just have to be refreshed if they change. Your query should not hurt a lot in terms of performance but it is still slightly wasteful.</p>\n<p>The login routine is something like this:</p>\n<pre><code>@cp_bp.route('/login', methods=['GET', 'POST'])\ndef login():\n errors = []\n\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = LoginForm()\n\n if form.validate_on_submit():\n user = User.query.filter_by(username=form.username.data).first()\n if user is None or not user.check_password(form.password.data):\n errors.append('Invalid username or password')\n # log failure\n # return redirect(url_for('login'))\n else:\n login_user(user)\n</code></pre>\n<p>And then in my templates I can use tags like:</p>\n<pre><code>{{ current_user.username }}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T23:03:23.303", "Id": "516020", "Score": "0", "body": "I'm using `flask_session` for login and `cs50` for SQL, I don't know how I could implement this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T19:25:23.170", "Id": "261434", "ParentId": "261356", "Score": "1" } } ]
{ "AcceptedAnswerId": "261357", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T22:43:07.053", "Id": "261356", "Score": "0", "Tags": [ "python", "sqlite", "session", "flask" ], "Title": "Getting a username from a database and displaying it in HTML" }
261356
<p>After wrestling with CMake I now have a fully working solution. It works, however, I completely massacred the CMake File:</p> <p>This is my main cmake file:</p> <pre><code>cmake_minimum_required(VERSION 3.17) project(Odin) include(ProcessorCount) ProcessorCount(N) if(NOT N EQUAL 0) set(CMAKE_BUILD_PARALLEL_LEVEL ${N}) endif() message(&quot;Parallelizing with ${N} Cores&quot;) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED YES) set(CMAKE_CXX_EXTENSIONS NO) include_directories(Odin/engine) include_directories(Odin/uci) include_directories(Odin/util) include_directories(Odin/util/iters) # add our cmake modules under cmake/ list(APPEND CMAKE_MODULE_PATH &quot;${PROJECT_SOURCE_DIR}/cmake&quot;) # Include CPM dependency manager include(CPM) if(WIN64) SET(BOOST_ROOT &quot;C:/Program Files (x86)/boost/boost_1_74_0&quot;) include_directories(${BOOST_ROOT}) include_directories(${BOOST_ROOT}/stage/lib) endif() find_package(Boost 1.74.0 REQUIRED serialization) message(STATUS &quot;---------------------&quot;) message(STATUS &quot;Boost_FOUND: ${Boost_FOUND}&quot;) message(STATUS &quot;Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}&quot;) message(STATUS &quot;Boost_LIBRARY_DIRS: ${Boost_LIBRARY_DIRS}&quot;) message(STATUS &quot;Boost_LIBRARIES: ${Boost_LIBRARIES}&quot;) message(STATUS &quot;---------------------&quot;) #EndBoost add_executable(Odin Odin/engine/Odin.cc Odin/main.cc Odin/engine/Board.cc Odin/util/Utility.cc Odin/util/iters/BoardIterator.cc Odin/engine/Node.cc Odin/engine/Link.cc Odin/engine/Odin.h Odin/engine/Board.h Odin/engine/Figure.h Odin/util/Utility.h Odin/engine/Node.h Odin/engine/Link.h Odin/util/iters/BoardIterator.h) add_library(Engine Odin/engine/Odin.cc Odin/main.cc Odin/engine/Board.cc Odin/util/Utility.cc Odin/util/iters/BoardIterator.cc Odin/engine/Node.cc Odin/engine/Link.cc Odin/engine/Odin.h Odin/engine/Board.h Odin/engine/Figure.h Odin/util/Utility.h Odin/engine/Node.h Odin/engine/Link.h Odin/util/iters/BoardIterator.h) target_link_libraries(Engine PRIVATE Boost::serialization) target_link_libraries(Odin PRIVATE Boost::serialization) if(UNIX) set(CMAKE_CXX_FLAGS &quot;-O3 -march=native&quot;) endif(UNIX) #Make Tests #enable testing enable_testing() # Pull doctest using CPM cpmaddpackage(&quot;gh:onqtam/doctest#2.4.5&quot;) # add the CMake modules for automatic test discovery so we can use # doctest_discover_tests() CMake set(CMAKE_MODULE_PATH &quot;${doctest_SOURCE_DIR}/scripts/cmake&quot; ${CMAKE_MODULE_PATH}) add_subdirectory(Testing) </code></pre> <p>To be honest, sometimes I had no idea what I was doing.</p> <p>You see that I have to add every file into library and into the executable Odin. This is not that smart. I actually want my idea to still be able to add a .cpp file to the Odin - executable. However my test must still run, and they require me to add all the files twice.</p> <p>You can find my tests (cmake) here: <a href="https://github.com/SuchtyTV/Odin/tree/master/Testing" rel="nofollow noreferrer">https://github.com/SuchtyTV/Odin/tree/master/Testing</a></p> <p>Here are some questions:</p> <ul> <li>How do I walk around this library/executable non-sense?</li> <li>How do I ensure the Release build will be well optimized?</li> <li>Can I download Boost with CPM, if so, how would I do that and how would that look in the cmake file?</li> <li>Any other advices?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T05:54:39.393", "Id": "531374", "Score": "0", "body": "In addition to what @arrowd wrote: consider exchanging [`include_directories`](https://cmake.org/cmake/help/latest/command/include_directories.html?highlight=include_directories#command:include_directories) with the now preferred [`target_include_directories`](https://cmake.org/cmake/help/latest/command/target_include_directories.html)." } ]
[ { "body": "<p>The code is mostly fine, however there are some problems:</p>\n<pre><code>SET(BOOST_ROOT &quot;C:/Program Files (x86)/boost/boost_1_74_0&quot;)\n</code></pre>\n<p>^ This is wrong, because other developers may have Boost installed into different directory. Remove this line and let the user set <code>BOOST_ROOT</code> during configuration.</p>\n<pre><code>include_directories(${BOOST_ROOT})\ninclude_directories(${BOOST_ROOT}/stage/lib)\n</code></pre>\n<p>^ Why is this required? The later <code>find_package(Boost ...)</code> call should set all required directories for you, which you can use in <code>include_directories</code>. This actually shouldn't be required at all, because linking to Boost using <code>target_link_libraries</code> should also set correct include directories.</p>\n<pre><code>add_executable(Odin ...\n)\n\nadd_library(Engine ...\n)\n</code></pre>\n<p>^ This looks wrong. First, you can remove code duplication by placing source files list into a variable:</p>\n<pre><code>set(SRCS ...\n)\n\nadd_executable(Odin ${SRCS})\nadd_library(Engine ${SRCS})\n</code></pre>\n<p>Second, it looks strange that both library and executable consist of same source files. You probably want to keep most files being a part of the library and then <strong>link</strong> the library to executable. This is achieved by the same <code>target_link_libraries</code> command.</p>\n<pre><code>set(CMAKE_MODULE_PATH &quot;${doctest_SOURCE_DIR}/scripts/cmake&quot;\n ${CMAKE_MODULE_PATH})\n</code></pre>\n<p>^ Use <code>list(APPEND ...)</code>, just like you did earlier in the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T13:00:22.020", "Id": "515795", "Score": "0", "body": "Thanks for your answer! \nI just need to build the tests with the help of the all source files, therefore I do not see another walk around." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T18:40:02.563", "Id": "515831", "Score": "1", "body": "You're doing right thing with tests - they consist of single source file and link to the library. Why don't do this for the `Odin` executable?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T08:36:15.723", "Id": "261368", "ParentId": "261358", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T23:04:28.963", "Id": "261358", "Score": "1", "Tags": [ "c++", "cmake" ], "Title": "CMake - Usual Build System" }
261358
<p>This is my first time trying solve a game using these techniques.</p> <p>I've looked at pseudocode of <a href="http://people.csail.mit.edu/plaat/mtdf.html#abmem" rel="nofollow noreferrer">alpha-beta pruning with transposition tables</a> and rewritten it in <code>c++</code>.</p> <p>I'm also using bitboards inspired by <a href="https://tromp.github.io/c4/Connect4.java" rel="nofollow noreferrer">Connect4.java</a> as explained in <a href="https://tromp.github.io/c4/c4.html" rel="nofollow noreferrer">John's Connect Four Playground</a>.</p> <p>I'm not solving Connect4, but instead a 5 by 5 variation of tic-tac-toe where the winner is the player that gathers most 3-in-a-row's (vertical, horizontal or diagonal) before the entire board is full.</p> <p>I have managed to solve this game with this code <em>(I believe there should not be any bugs in my code)</em>, but now I'm wondering if this could've been faster.</p> <blockquote> <p>Can either the bitboard Board class or the alpha-beta Solver class be more optimized? Either to be faster or to use less memory, or both?</p> </blockquote> <hr /> <p>Here is the main code containing those two classes: <em>(Size of transposition tables is set to around 1 GB, so you might want or need to reduce that to a lower value if you are running the code. Also notice that there is an option for a 4 by 4 version, which was used for testing before moving onto the 5 by 5 version.)</em></p> <pre><code>#include &lt;iostream&gt; #include &lt;cctype&gt; #include &lt;algorithm&gt; #include &quot;TranspositionTable.hpp&quot; // https://stackoverflow.com/a/109025 int numberOfSetBits(uint32_t i) { i = i - ((i &gt;&gt; 1) &amp; 0x55555555); // add pairs of bits i = (i &amp; 0x33333333) + ((i &gt;&gt; 2) &amp; 0x33333333); // quads i = (i + (i &gt;&gt; 4)) &amp; 0x0F0F0F0F; // groups of 8 return (i * 0x01010101) &gt;&gt; 24; // horizontal sum of bytes } // Inspired by https://tromp.github.io/c4/Connect4.java (https://tromp.github.io/c4/c4.html) #define N 5 class Board { private: unsigned int moves[25] = {0}; public: uint32_t color[2]; static const unsigned int ROW = 3; static const unsigned int ROW1 = ROW-1; #if N == 5 static const unsigned int WIDTH = 5; static const unsigned int HEIGHT = 5; static constexpr unsigned int bitid[5][5] = { {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} }; static constexpr unsigned int directions[3][4] = { {1, 4, 5, 6}, {2, 8, 10, 12}, {7576807, 29596, 32767, 7399} }; #elif N == 4 static const unsigned int WIDTH = 4; static const unsigned int HEIGHT = 4; static constexpr unsigned int bitid[4][4] = { { 0, 1, 2, 3}, { 4, 5, 6, 7}, { 8, 9, 10, 11}, {12, 13, 14, 15} }; static constexpr unsigned int directions[3][4] = { {1, 3, 4, 5}, {2, 6, 8, 10}, {13107, 204, 255, 51} }; #endif static const unsigned int HEIGHT1 = HEIGHT-1; static const unsigned int WIDTH1 = WIDTH-1; unsigned int move; val_t ptsX; val_t ptsO; Board() { reset(); } void reset() { color[0] = 0; color[1] = 0; move = 0; ptsX = 0; ptsO = 0; } bool isplayable(unsigned int col, unsigned int row) const { unsigned int n = bitid[col][row]; return !((color[0] &amp; (1 &lt;&lt; (n))) || (color[1] &amp; (1 &lt;&lt; (n)))); } bool isplayable(unsigned int n) const { return !((color[0] &amp; (1 &lt;&lt; (n))) || (color[1] &amp; (1 &lt;&lt; (n)))); } void backmove() { unsigned int n = moves[--move]; color[move&amp;1] ^= (1 &lt;&lt; (n)); } void makemove(unsigned int col, unsigned int row) { unsigned int n = bitid[col][row]; color[move&amp;1] ^= (1 &lt;&lt; (n)); moves[move++] = n; } void makemove(unsigned int n) { color[move&amp;1] ^= (1 &lt;&lt; (n)); moves[move++] = n; } void updatePointCount() { ptsX = 0; ptsO = 0; for (int j=0; j&lt;HEIGHT1; j++) { uint32_t bitboard0 = color[0]; uint32_t bitboard1 = color[1]; for (int i=0; i&lt;ROW1; i++) { bitboard0 &amp;= (color[0] &gt;&gt; directions[i][j]); bitboard1 &amp;= (color[1] &gt;&gt; directions[i][j]); } bitboard0 &amp;= (directions[ROW1][j]); bitboard1 &amp;= (directions[ROW1][j]); ptsX += numberOfSetBits(bitboard0); ptsO += numberOfSetBits(bitboard1); } } static val_t getPointCount(uint32_t bitboard) { val_t pts0 = 0; for (int j=0; j&lt;HEIGHT1; j++) { uint32_t bitboard0 = bitboard; for (int i=0; i&lt;ROW1; i++) { bitboard0 &amp;= (bitboard &gt;&gt; directions[i][j]); } bitboard0 &amp;= (directions[ROW1][j]); pts0 += numberOfSetBits(bitboard0); } return pts0; } val_t maxPossiblePointCount(bool player_color) { return getPointCount(~color[!player_color]); } key_t key() { return (((key_t) color[0]) &lt;&lt; 32) | ((key_t)color[1]); } friend void operator&lt;&lt;(std::ostream&amp; os, const Board &amp;b) { for (int i=0; i&lt;b.WIDTH; i++) { os &lt;&lt; i &lt;&lt; &quot;. &quot;; for (int j=0; j&lt;b.HEIGHT; j++) { unsigned int n = b.bitid[i][j]; os &lt;&lt; ((b.color[0] &amp; (1 &lt;&lt; (n))) ? 'X' : ((b.color[1] &amp; (1 &lt;&lt; (n))) ? 'O' : '_')) &lt;&lt; ' '; } os &lt;&lt; std::endl; } } }; // https://stackoverflow.com/a/8016853 #if N == 5 constexpr unsigned int Board::bitid[5][5]; #elif N == 4 constexpr unsigned int Board::bitid[4][4]; #endif constexpr unsigned int Board::directions[3][4]; // Inspired by https://en.wikipedia.org/wiki/Alpha–beta_pruning // Inspired by http://people.csail.mit.edu/plaat/mtdf.html#abmem class Solver { private: val_t maxPossibleScore; unsigned long long nodeCount; #if N == 5 unsigned int moveOrder[Board::WIDTH*Board::HEIGHT] = {12,6,7,8,11,13,16,17,18,1,2,3,5,10,15,9,14,19,21,22,23,0,4,20,24}; #elif N == 4 unsigned int moveOrder[Board::WIDTH*Board::HEIGHT] = {5,6,10,9,1,2,4,7,8,11,13,14,0,3,12,15}; #endif TranspositionTable transTable; val_t alphabeta(Board &amp;P, val_t alpha, val_t beta, bool firstPlayer, val_t depth = 0) { //std::cout &lt;&lt; &quot;a: &quot; &lt;&lt; (int)alpha &lt;&lt; &quot;, b: &quot; &lt;&lt; (int)beta &lt;&lt; std::endl; assert(alpha &lt; beta); nodeCount++; // game ended if(P.move == Board::WIDTH*Board::HEIGHT) { P.updatePointCount(); return P.ptsX - P.ptsO; } /* Transposition table lookup */ val_t n_lowerbound = transTable.getLower(P.key()); val_t n_upperbound = transTable.getUpper(P.key()); if (n_lowerbound != 127) { if (n_lowerbound &gt;= beta) return n_lowerbound; alpha = std::max(alpha, n_lowerbound); } if (n_upperbound != 127) { if (n_upperbound &lt;= alpha) return n_upperbound; beta = std::min(beta, n_upperbound); } val_t value, a, b; if (firstPlayer) { value = -maxPossibleScore; a = alpha; for (unsigned int k=0; k&lt;Board::WIDTH*Board::HEIGHT; k++) { unsigned int n = moveOrder[k]; if(P.isplayable(n)) { P.makemove(n); val_t newValue = alphabeta(P, a, beta, false, depth+1); value = std::max(value, newValue); P.backmove(); a = std::max(a, value); if (a &gt;= beta) break; // β cutoff } } return value; } else { value = maxPossibleScore; b = beta; for (unsigned int k=0; k&lt;Board::WIDTH*Board::HEIGHT; k++) { unsigned int n = moveOrder[k]; if(P.isplayable(n)) { P.makemove(n); val_t newValue = alphabeta(P, alpha, b, true, depth+1); value = std::min(value, newValue); P.backmove(); b = std::min(b, value); if (b &lt;= alpha) break; // α cutoff } } } /* Traditional transposition table storing of bounds */ /* Fail low result implies an upper bound */ if (value &lt;= alpha) { transTable.put(P.key(), 127, value); } /* Found an accurate minimax value - will not occur if called with zero window */ if (value &gt; alpha &amp;&amp; value &lt; beta) { transTable.put(P.key(), value, value); } /* Fail high result implies a lower bound */ if (value &gt;= beta) { transTable.put(P.key(), value, 127); } return value; } public: int solve(Board &amp;P, bool weak, bool firstPlayer) { if(weak) return alphabeta(P, -1, 1, firstPlayer); else return alphabeta(P, -maxPossibleScore, maxPossibleScore, firstPlayer); } int solveEach(Board &amp;P, bool weak, bool firstPlayer) { val_t score; val_t maxScore = -maxPossibleScore; val_t minScore = maxPossibleScore; for (unsigned int k=0; k&lt;Board::WIDTH*Board::HEIGHT; k++) { unsigned int n = moveOrder[k]; if(P.isplayable(n)) { P.makemove(n); if(weak) score = alphabeta(P, -1, 1, !firstPlayer); else score = alphabeta(P, -maxPossibleScore, maxPossibleScore, !firstPlayer); if (score &gt; maxScore) maxScore = score; if (score &lt; minScore) minScore = score; P.backmove(); std::cout &lt;&lt; &quot;Move &quot; &lt;&lt; n &lt;&lt; &quot; yields &quot; &lt;&lt; (int)score &lt;&lt; &quot;.&quot; &lt;&lt; std::endl; } } if (firstPlayer) return maxScore; else return minScore; } unsigned long long getNodeCount() { return nodeCount; } void reset() { nodeCount = 0; transTable.reset(); } // Constructor Solver() : maxPossibleScore{4*(N-2)*(N-1)}, nodeCount{0}, transTable(67108747) { // select a prime: 8388593, 16777199, 33554383, 67108747,... to setup maximal memory. // The last prime in above list corresponds to 1 GB of transposition table memory. // (The Board::key() can be optimized to reduce this, but I haven't bothered with that.) assert(4*(N-2)*(N-1) &lt; 127); reset(); } }; // https://stackoverflow.com/a/19555298 #include &lt;chrono&gt; using namespace std::chrono; milliseconds getTimeSec() { return duration_cast&lt; milliseconds &gt;( system_clock::now().time_since_epoch() ); } int main() { Board board; std::cout &lt;&lt; board.WIDTH&lt;&lt;&quot;x&quot;&lt;&lt;board.HEIGHT&lt;&lt;&quot; Cumulative-Tic-Tac-Toe&quot; &lt;&lt; std::endl; Solver solver; bool weak = false; bool solveIndividually; std::cout &lt;&lt; &quot;Solve Individually? Type 1 (yes) or 0 (no): &quot;; std::cin &gt;&gt; solveIndividually; // Test case 5x5 // cin: 2 2 3 2 1 2 1 1 1 3 1 4 2 3 2 4 0 2 0 3 0 4 3 4 0 1 2 1 3 1 3 3 0 0 4 4 1 0 4 3 2 0 4 2 3 0 4 1 4 0 // cout: X: 9, O: 7 // Test case 4x4 // cin: 0 0 3 3 0 1 3 2 0 2 3 1 0 3 3 0 1 1 2 1 2 0 1 2 1 0 2 2 2 3 1 3 // cout: X: 4, O: 5 char c; unsigned int col, row; unsigned int lastMove = Board::WIDTH*Board::HEIGHT; while (true) { std::cout &lt;&lt; std::endl; board.updatePointCount(); val_t maxX = board.maxPossiblePointCount(0); val_t maxO = board.maxPossiblePointCount(1); std::cout &lt;&lt; &quot;X: &quot; &lt;&lt; (int)board.ptsX &lt;&lt; &quot; (&quot; &lt;&lt; (int)maxX &lt;&lt; &quot;)&quot; &lt;&lt; &quot;, O: &quot; &lt;&lt; (int)board.ptsO &lt;&lt; &quot; (&quot; &lt;&lt; (int)maxO &lt;&lt; &quot;)&quot; &lt;&lt; std::endl; std::cout &lt;&lt; board; if (board.move==lastMove) { std::cout &lt;&lt; &quot;Board full, player&quot; &lt;&lt; ((board.ptsX &gt; board.ptsO) ? &quot; X wins!&quot; : ((board.ptsX &lt; board.ptsO) ? &quot; O wins!&quot; : &quot;s drew!&quot;)) &lt;&lt; std::endl; break; } std::cout &lt;&lt; &quot;&gt;&gt; &quot;; std::cin &gt;&gt; c; bool moving = std::isdigit(c); if (c == 'm' || moving) { if (moving) col = (unsigned int)c - 48; else std::cin &gt;&gt; col; std::cin &gt;&gt; row; if (col&lt;board.WIDTH &amp;&amp; row&lt;board.HEIGHT) { if (board.isplayable(col, row)) board.makemove(col, row); else std::cout &lt;&lt; &quot;That square is already occupied.&quot; &lt;&lt; std::endl; } else { std::cout &lt;&lt; &quot;That square is out of bounds.&quot; &lt;&lt; std::endl; } } else if (c == 'u') { if (board.move &gt; 0) board.backmove(); else std::cout &lt;&lt; &quot;Nothing to undo.&quot; &lt;&lt; std::endl; } else if (c == 'x') { // solver.reset(); milliseconds start_time = getTimeSec(); val_t score; if (solveIndividually) score = solver.solveEach(board, weak, board.move%2==0); else score = solver.solve(board, weak, board.move%2==0); milliseconds end_time = getTimeSec(); std::cout &lt;&lt; &quot;Position Score:&quot; &lt;&lt; &quot; &quot; &lt;&lt; (int)score &lt;&lt; &quot;, nodes searched: &quot; &lt;&lt; solver.getNodeCount() &lt;&lt; &quot;, time: &quot; &lt;&lt; (end_time - start_time).count() &lt;&lt; &quot;ms&quot; &lt;&lt; std::endl; // } else { std::cout &lt;&lt; &quot;Command (&quot; &lt;&lt; c &lt;&lt; &quot;) is invalid. Use ('m' x y) for move or ('u') for undo or ('x') for solving.&quot; &lt;&lt; std::endl; } } c = ' '; while(c==' ') {std::cin &gt;&gt; c;} return 0; } </code></pre> <p>Here is the transposition table class: <em>(heavily inspired by <a href="http://blog.gamesolver.org/solving-connect-four/07-transposition-table/" rel="nofollow noreferrer">blog.gamesolver.org</a>)</em></p> <pre><code>// Inspired by http://blog.gamesolver.org/solving-connect-four/07-transposition-table/ #ifndef TRANSPOSITION_TABLE_HPP #define TRANSPOSITION_TABLE_HPP #include&lt;vector&gt; #include&lt;cstring&gt; #include&lt;cassert&gt; typedef uint64_t key_t; typedef int8_t val_t; /** * Transposition Table is a simple hash map with fixed storage size. * In case of collision we keep the last entry and overide the previous one. */ class TranspositionTable { private: struct Entry { key_t key; val_t upper; val_t lower; }; std::vector&lt;Entry&gt; T; unsigned int index(key_t key) const { return key%T.size(); } public: TranspositionTable(unsigned int size): T(size) { assert(size &gt; 0); } /* * Empty the Transition Table. */ void reset() { // fill everything with 0, because 0 value means missing data memset(&amp;T[0], 0, T.size()*sizeof(Entry)); } void put(key_t key, val_t low, val_t up) { unsigned int i = index(key); // compute the index position T[i].key = key; // and overide any existing value. //if (up != 127) T[i].upper = up; //if (low != 127) T[i].lower = low; } val_t getLower(key_t key) const { unsigned int i = index(key); // compute the index position if(T[i].key == key) return T[i].lower; // and return value if key matches else return 127; // signal missing entry } val_t getUpper(key_t key) const { unsigned int i = index(key); // compute the index position if(T[i].key == key) return T[i].upper; // and return value if key matches else return 127; // signal missing entry } }; #endif </code></pre> <p>Here is an example output of how to use the compiled code: <em>(Where I setup first four moves, then solve each of the following possible moves and print out the score for each, in less than a minute.)</em></p> <pre><code>5x5 Cumulative-Tic-Tac-Toe Solve Individually? Type 1 (yes) or 0 (no): 1 X: 0 (48), O: 0 (48) 0. _ _ _ _ _ 1. _ _ _ _ _ 2. _ _ _ _ _ 3. _ _ _ _ _ 4. _ _ _ _ _ &gt;&gt; r Command (r) is invalid. Use ('m' x y) for move or ('u') for undo or ('x') for solving. X: 0 (48), O: 0 (48) 0. _ _ _ _ _ 1. _ _ _ _ _ 2. _ _ _ _ _ 3. _ _ _ _ _ 4. _ _ _ _ _ &gt;&gt; m 2 2 X: 0 (48), O: 0 (36) 0. _ _ _ _ _ 1. _ _ _ _ _ 2. _ _ X _ _ 3. _ _ _ _ _ 4. _ _ _ _ _ &gt;&gt; 3 2 X: 0 (39), O: 0 (36) 0. _ _ _ _ _ 1. _ _ _ _ _ 2. _ _ X _ _ 3. _ _ O _ _ 4. _ _ _ _ _ &gt;&gt; 2 3 X: 0 (39), O: 0 (29) 0. _ _ _ _ _ 1. _ _ _ _ _ 2. _ _ X X _ 3. _ _ O _ _ 4. _ _ _ _ _ &gt;&gt; 21 X: 0 (32), O: 0 (29) 0. _ _ _ _ _ 1. _ _ _ _ _ 2. _ O X X _ 3. _ _ O _ _ 4. _ _ _ _ _ &gt;&gt; x Move 6 yields 1. Move 7 yields 1. Move 8 yields 1. Move 16 yields 1. Move 18 yields 1. Move 1 yields 0. Move 2 yields 1. Move 3 yields 0. Move 5 yields 1. Move 10 yields 1. Move 15 yields 1. Move 9 yields 0. Move 14 yields 1. Move 19 yields 0. Move 21 yields 0. Move 22 yields 1. Move 23 yields 1. Move 0 yields 0. Move 4 yields 0. Move 20 yields 0. Move 24 yields 0. Position Score: 1, nodes searched: 166118770, time: 49715ms </code></pre> <hr /> <p>An optimization that comes to my mind is to optimize the keys used in the transposition class. I have a feeling that their size can be reduced?</p> <p>Also note that I'm not exploiting the symmetry of positions (boards) in the code (in the implementation of keys), so I'm doing repeated work when an equivalent but rotated position is being calculated. We can call the Solver only on non-symmetric positions, but those can still sometimes lead again into symmetric positions in some branches. Would rotating bitmaps and checking for symmetry be a significant improvement, or is there some other best way to do this?</p> <p>Can anything else be improved?</p>
[]
[ { "body": "<h1>Avoid code duplication</h1>\n<p>There is a lot of code duplication going on, based on whether <code>N</code> is 4 or 5. It would be even worse if you wanted to support other board sizes as well. There are several ways to reduce it. The most trivial thing is to use <code>N</code> directly in the code, so instead of writing:</p>\n<pre><code>#if N == 5\n constexpr unsigned int Board::bitid[5][5];\n#elif N == 4\n constexpr unsigned int Board::bitid[4][4];\n#endif\n</code></pre>\n<p>You can just write:</p>\n<pre><code>constexpr unsigned int Board::bitid[N][N];\n</code></pre>\n<p>4 lines eliminated, and now this line of code supports arbitrary board sizes. Of course, this only goes so far. You can't just simplify the intialization of <code>bitid</code> this way. But you can if you start using <code>std::array</code> and templates. You can make <code>constexpr</code> functions that return <code>std::array</code>s with the values initialized with anything that can be done in a <code>constexpr</code> function. For example:</p>\n<pre><code>template&lt;size_t N&gt;\nconstexpr auto make_bitid() {\n std::array&lt;std::array&lt;unsigned int, N&gt;, N&gt; bitid;\n\n for (std::size_t col = 0; col &lt; N; col++)\n for (std::size_t row = 0; row &lt; N; row++)\n arr[col][row] = i * N + j;\n\n return arr;\n}\n</code></pre>\n<p>And then use this inside <code>class Board</code> as follows:</p>\n<pre><code>#define N 5\nclass Board {\n ...\n static constexpr auto bitid = make_bitid&lt;N&gt;();\n ...\n};\n</code></pre>\n<p>Perhaps even the arrays <code>directions</code> and <code>moveOrder</code> could be computed at compile time, and then you don't need to use <code>#define</code>s and <code>#if</code>s anymore, and then you can make <code>Board</code> and <code>Solver</code> templates themselves, with <code>size_t N</code> as the template argument. As a bonus, this would remove a lot of magic constants from the code.</p>\n<h1>Avoid look-up tables for trivially computable values</h1>\n<p>It can be faster for a computer to do a simple calculation on values that are already in registers than it is to read something from memory, even if it is in the cache. So don't create look-up tables for things that are trivial to calculate, such as <code>bitid</code>. I would replace it with a simple function:</p>\n<pre><code>constexpr unsigned int bitid(unsigned int col, unsigned int row) {\n return col * N + row;\n}\n</code></pre>\n<h1>Be consistent with the types of integers</h1>\n<p>I see both <code>uint32_t</code>, <code>unsigned int</code> and <code>int</code> being used, sometimes in the same expressions. Try to be more consistent. First, I strongly suggest you use <code>size_t</code> for all sizes, counts, and indices. Furthermore, anything that should never be negative should be unsigned. If you know exactly how large the range of integers used is,</p>\n<h1>Use <code>constexpr</code> where possible</h1>\n<p>Why is <code>bitid</code> <code>constexpr</code> but <code>WIDTH</code> and <code>HEIGHT</code> only <code>const</code>? You should make those <code>constexpr</code> as well. Also note that if you have a separate <code>WIDTH</code> and <code>HEIGHT</code>, and you made them <code>constexpr</code>, then you could have written <code>bitid[WIDTH][HEIGHT]</code>.</p>\n<h1>Make member functions <code>const</code> where possible</h1>\n<p>You made some member functions <code>const</code>, but you missed a few opportunities, such as <code>getPointCount()</code>, <code>maxPossiblePointCount()</code>, <code>key()</code> and <code>getNodeCount()</code>.</p>\n<h1>Where to define <code>key_t</code> and <code>val_t</code></h1>\n<p>It is a bit strange to see <code>key_t</code> and <code>val_t</code> being <code>typedef</code>'ed inside TranspositionTable.hpp, but used to declare variables in both files. Having the very generic names <code>key_t</code> and <code>val_t</code> defined in global scope is quite bad. First, I would declare <code>key_t</code> and <code>val_t</code> inside the main file, and perhaps even create a <code>namespace</code> to put those types, <code>class Board</code> and <code>class Solver</code> in. Then, make <code>TranspositionTable</code> a template that takes the key and value type as template parameters, like so:</p>\n<pre><code>template&lt;typename key_t, typename val_t&gt;\nclass TranspositionTable {\n ...\n // no changes necessary here\n ...\n};\n</code></pre>\n<p>And inside <code>Solver</code> just pass it the actual types:</p>\n<pre><code>class Solver {\n ...\n TranspositionTable&lt;key_t, val_t&gt; transTable;\n ...\n};\n</code></pre>\n<p>Also prefer creating type aliases with <a href=\"https://en.cppreference.com/w/cpp/language/type_alias\" rel=\"nofollow noreferrer\"><code>using</code></a> instead of <code>typedef</code>, while the semantics are <a href=\"https://stackoverflow.com/questions/10747810/what-is-the-difference-between-typedef-and-using-in-c11\">almost identical</a>, the former has the benefit that it can also be templated.</p>\n<h1>Use <code>'\\n'</code> instead of <code>std::endl</code></h1>\n<p>Prefer using <a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\"><code>'\\n'</code> instead of <code>std::endl</code></a>, the latter is identical to the former, but it also forces the output to be flushed, which is often unnecessary and can have a performance impact.</p>\n<h1>Use <code>static_assert()</code> instead of <code>assert()</code> where possible</h1>\n<p>If you want to assert something that can be checked at compile-time, use <a href=\"https://en.cppreference.com/w/cpp/language/static_assert\" rel=\"nofollow noreferrer\"><code>static_assert()</code></a>. For example:</p>\n<pre><code>static_assert(4 * (N - 2) * (N - 1) &lt; 127, &quot;Board too large for val_t&quot;);\n</code></pre>\n<h1>Avoid magic numbers</h1>\n<p>You use 127 a number of times as a special value. However, consider that if you ever want to change the type of <code>val_t</code> (for example, if you want to solve 8x8 or larger boards), that you'd have to find and replace every occurence of 127, and hope there are no other things that use the number 127.</p>\n<p>Give <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a> a name by declaring a <code>static constexpr</code> variable for them. Also, if there is a way to derive that number from something else programmatically, do that. For example, here you can use <a href=\"https://en.cppreference.com/w/cpp/types/numeric_limits/max\" rel=\"nofollow noreferrer\"><code>std::numeric_limit&lt;&gt;::max()</code></a> to get the maximum value of <code>val_t</code>:</p>\n<pre><code>static constexpr MISSING_ENTRY = std::numeric_limit&lt;val_t&gt;::max();\n</code></pre>\n<p>This is also a case where you might want to explore other ways of signalling a missing value, for example by using <a href=\"https://en.cppreference.com/w/cpp/utility/optional\" rel=\"nofollow noreferrer\"><code>std::optional</code></a> when returning the lower and upper bound:</p>\n<pre><code>std::optional&lt;std::pair&lt;val_t, val_t&gt;&gt; getBounds(key_t key) const {\n unsigned int i = index(key);\n if (T[i].key == key)\n return std::make_pair&lt;T[i].lower, T[i].upper&gt;;\n else\n return std::nullopt;\n}\n</code></pre>\n<p>And then use it like so:</p>\n<pre><code>if (auto bounds = transTable.getBounds(P.key())) {\n auto [n_lowerbound, n_upperbound] = *bounds;\n if (n_lowerbound &gt;= beta)\n return n_lowerbound;\n alpha = std::max(alpha, n_lowerbound);\n if (n_upperbound &lt;= alpha)\n return n_upperbound;\n beta = std::min(beta, n_upperbound); \n}\n</code></pre>\n<h1>Use <code>std::fill()</code> instead of <code>memset()</code></h1>\n<p>There is often no need to use C functions when C++ has perfectly capable, and usually more safe alternatives. For example, if you want to clear an array, then instead of using <code>memset()</code>, you can use <a href=\"https://en.cppreference.com/w/cpp/algorithm/fill\" rel=\"nofollow noreferrer\"><code>std::fill()</code></a> or <a href=\"https://en.cppreference.com/w/cpp/algorithm/fill_n\" rel=\"nofollow noreferrer\"><code>std::fill_n()</code></a>, like so in <code>class Solver</code>:</p>\n<pre><code>void reset() {\n std::fill(T.begin(), T.end(), Entry{});\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T22:04:43.843", "Id": "261392", "ParentId": "261359", "Score": "2" } } ]
{ "AcceptedAnswerId": "261392", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T23:08:58.287", "Id": "261359", "Score": "2", "Tags": [ "c++", "performance", "algorithm", "memory-optimization" ], "Title": "Alpha beta pruning with memorization (transposition tables) and bitboards (5x5 cumulative tic-tac-toe)" }
261359
<p>Right now I'm making a Discord Bot written in Python. I'm using SQLAlchemy to deal with the database.</p> <p>My structure is:</p> <ul> <li>One <code>database.py</code> containing a <code>DatabaseConnection</code> class initializing the SQLAlchemy engine, and making a new session with the DB every time i use it</li> <li>Many <code>.py</code> file(each file for different purposes) containing a class inheriting <code>DatabaseConnection</code></li> </ul> <p>Example:</p> <p><code>database.py</code>:</p> <pre class="lang-py prettyprint-override"><code>from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, Session class DatabaseConnection: def __init__(self): self.engine = create_engine(DB_URI, echo=False) self.session = None def __enter__(self) -&gt; Session: self.session = sessionmaker(bind=self.engine)() return self.session def __exit__(self, exc_type, exc_val, exc_tb): self.session.close() </code></pre> <p><code>example.py</code>:</p> <pre class="lang-py prettyprint-override"><code>from database import DatabaseConnection class Foo(DatabaseConnection): def get_bar(self): with self as session: #do thing </code></pre> <p>My question is, is this a right way to use inheritance? Or is it just better calling directly to <code>DatabaseConnection</code>? Can it cause problems? Are there better/cleaner/more pythonic ways to do it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T04:18:02.730", "Id": "515774", "Score": "0", "body": "@Reinderien it is, if you mean the unclosed/passed `with` statement, or the undeclared \"DB_URI\" variable, i'm aware of them, despite that, the code works like it should. Still, i will try to post more code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T04:25:17.947", "Id": "515776", "Score": "0", "body": "Fixed ; thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T04:29:43.527", "Id": "515777", "Score": "0", "body": "Thanks to you!!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T03:32:03.513", "Id": "261362", "Score": "1", "Tags": [ "python", "postgresql", "sqlalchemy" ], "Title": "Discord bot using SQLAlchemy" }
261362
<p>I have put together a <em>To-do Application</em> with the Slim framework on the back-end (API) and a Vue 3 front-end. I added a <strong><a href="https://www.youtube.com/watch?v=s7eRMfdc8qM" rel="nofollow noreferrer">demo</a></strong> on my <strong>YouTube</strong> channel.</p> <p>In the main <strong>App.vue</strong> file I have:</p> <pre><code>&lt;template&gt; &lt;div id=&quot;app&quot;&gt; &lt;Header title=&quot;My todo list&quot; :unsolvedTodos = unsolvedTodos /&gt; &lt;List :todos=&quot;todos&quot; :dataIsLoaded=dataIsLoaded @delete-todo=&quot;deleteTodo&quot; @toggle-todo=&quot;toggleTodo&quot; /&gt; &lt;Footer :isValidInput=isValidInput newTitle = &quot;&quot; placeholder= &quot;+ Add new todo&quot; validationMsg = &quot;Please add at least 3 characters&quot; @add-todo=&quot;addTodo&quot; /&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import axios from 'axios' import '@fortawesome/fontawesome-free/js/all.js'; import Header from './components/Header.vue' import List from './components/List.vue' import Footer from './components/Footer.vue' export default { name: 'App', components: { Header, List, Footer }, data() { return { apiUrl: &quot;http://todo.com/api&quot;, dataIsLoaded: false, isValidInput: true, todos: [], unsolvedTodos: [], } }, methods: { showTodos: function(){ axios.get(`${this.apiUrl}/todos`) .then((response) =&gt; { this.todos = response.data; }) .then(this.getUnsolvedTodos) .then(this.dataIsLoaded = true); }, getUnsolvedTodos: function(){ this.unsolvedTodos = this.todos.filter(todo =&gt; { return todo.completed == 0; }); }, toggleTodo: function(todo) { let newStatus = todo.completed == &quot;0&quot; ? 1 : 0; axios.put(`${this.apiUrl}/todo/update/${todo.id}`, { title: todo.title, completed: newStatus }) }, deleteTodo: function(id) { axios.delete(`${this.apiUrl}/todo/delete/${id}`) }, addTodo: function(newTitle){ const newToDo = { title: newTitle, completed: 0 } if(newTitle.length &gt; 2){ this.isValidInput = true; axios.post(`${this.apiUrl}/todo/add`, newToDo); } else { this.isValidInput = false; } } }, created() { this.showTodos(); }, watch: { todos() { this.showTodos(); } } } &lt;/script&gt; </code></pre> <p>In <strong>Header.vue</strong>:</p> <pre><code>&lt;template&gt; &lt;header&gt; &lt;span class=&quot;title&quot;&gt;{{title}}&lt;/span&gt; &lt;span class=&quot;count&quot; :class=&quot;{zero: unsolvedTodos.length === 0}&quot;&gt;{{unsolvedTodos.length}}&lt;/span&gt; &lt;/header&gt; &lt;/template&gt; &lt;script&gt; export default { props: { title: String, unsolvedTodos: Array }, } &lt;/script&gt; </code></pre> <p>In <strong>Footer.vue</strong>:</p> <pre><code>&lt;template&gt; &lt;footer&gt; &lt;form @submit.prevent=&quot;addTodo()&quot;&gt; &lt;input type=&quot;text&quot; :placeholder=&quot;placeholder&quot; v-model=&quot;newTitle&quot;&gt; &lt;span class=&quot;error&quot; v-if=&quot;!isValidInput&quot;&gt;{{validationMsg}}&lt;/span&gt; &lt;/form&gt; &lt;/footer&gt; &lt;/template&gt; &lt;script&gt; export default { name: 'Footer', props: { placeholder: String, validationMsg: String, isValidInput: Boolean }, data () { return { newTitle: '', } }, methods: { addTodo() { this.$emit('add-todo', this.newTitle) this.newTitle = '' } } } &lt;/script&gt; </code></pre> <p>The to-do list (List.vue):</p> <pre><code>&lt;template&gt; &lt;transition-group name=&quot;list&quot; tag=&quot;ul&quot; class=&quot;todo-list&quot; v-if=dataIsLoaded&gt; &lt;TodoItem v-for=&quot;(todo, index) in todos&quot; :key=&quot;todo.id&quot; :class=&quot;{done: Boolean(Number(todo.completed)), current: index == 0}&quot; :todo=&quot;todo&quot; @delete-todo=&quot;$emit('delete-todo', todo.id)&quot; @toggle-todo=&quot;$emit('toggle-todo', todo)&quot; /&gt; &lt;/transition-group&gt; &lt;div class=&quot;loader&quot; v-else&gt;&lt;/div&gt; &lt;/template&gt; &lt;script&gt; import TodoItem from &quot;./TodoItem.vue&quot;; export default { name: 'List', components: { TodoItem, }, props: { dataIsLoaded: Boolean, todos: Array }, emits: [ 'delete-todo', 'toggle-todo' ] } &lt;/script&gt; </code></pre> <p>The single to-do item (TodoItem.vue):</p> <pre><code>&lt;template&gt; &lt;li&gt; &lt;input type=&quot;checkbox&quot; :checked=&quot;Boolean(Number(todo.completed))&quot; @change=&quot;$emit('toggle-todo', todo)&quot; /&gt; &lt;span class=&quot;title&quot;&gt;{{todo.title}}&lt;/span&gt; &lt;button @click=&quot;$emit('delete-todo', todo.id)&quot;&gt; &lt;i class=&quot;fas fa-trash-alt&quot;&gt;&lt;/i&gt; &lt;/button&gt; &lt;/li&gt; &lt;/template&gt; &lt;script&gt; export default { name: 'TodoItem', props: { todo: Object } } &lt;/script&gt; </code></pre> <h3>Questions / concerns:</h3> <ol> <li>Is the application well-structured?</li> <li>Could the code be significantly &quot;shortened&quot;?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-01T22:04:39.593", "Id": "520609", "Score": "0", "body": "Were you able to simplify the event passing using `v-bind=\"$attrs\"`?" } ]
[ { "body": "<blockquote>\n<h1>Is the application well-structured?</h1>\n</blockquote>\n<p>On the whole it seems okay, though see the answer to the next question that means the structure could be slightly changed for the better.</p>\n<blockquote>\n<h1>Could the code be significantly &quot;shortened&quot;?</h1>\n</blockquote>\n<h2>Simon Says: use computed properties</h2>\n<p>Like <a href=\"https://codereview.stackexchange.com/a/260915/120114\">Simon suggests: use computed properties</a> - the implementation inside <code>getUnsolvedTodos()</code> could be moved to a computed property, with a <code>return</code> instead of assigning the result from calling <code>.filter()</code> to a data variable. Then there is no need to need to call that method and set up the property within the object returned by the <code>data</code> function.</p>\n<h2>Promise callback consolidation</h2>\n<p>The call to <code>axios.get()</code> in <code>showTodos()</code> has multiple <code>.then()</code> callbacks:</p>\n<blockquote>\n<pre><code>showTodos: function(){ \n axios.get(`${this.apiUrl}/todos`)\n .then((response) =&gt; {\n this.todos = response.data;\n })\n .then(this.getUnsolvedTodos)\n .then(this.dataIsLoaded = true);\n },\n</code></pre>\n</blockquote>\n<p>Those can be consolidated to a single callback - especially since none of them return a promise.</p>\n<pre><code>showTodos: function(){\n axios.get(`${this.apiUrl}/todos`)\n .then((response) =&gt; {\n this.todos = response.data;\n this.getUnsolvedTodos(); //this can be removed - see previous section\n this.dataIsLoaded = true;\n });\n},\n</code></pre>\n<p>While this does require one extra line, it would avoid confusion because somebody reading the code might think the statements passed to <code>.then()</code> should be functions that return promises.</p>\n<h2>Single-use variables</h2>\n<p>In <code>toggleTodo</code> the variable <code>newStatus</code> is only used once so it could be consolidated into the object passed to the call:</p>\n<pre><code>axios.put(`${this.apiUrl}/todo/update/${todo.id}`, {\n title: todo.title,\n completed: todo.completed == &quot;0&quot; ? 1 : 0\n})\n</code></pre>\n<p>If that variable is kept it could be created with <code>const</code> instead of <code>let</code> since it is never re-assigned.</p>\n<h2>Passing events to parent</h2>\n<p>In <code>List.vue</code> the <code>&lt;TodoItem</code> has these attributes:</p>\n<blockquote>\n<pre><code>@delete-todo=&quot;$emit('delete-todo', todo.id)&quot;\n@toggle-todo=&quot;$emit('toggle-todo', todo)&quot;\n</code></pre>\n</blockquote>\n<p>Those seem redundant. In Vue 2 these lines could be replaced with a single line: <a href=\"https://vuejs.org/v2/api/#vm-listeners\" rel=\"nofollow noreferrer\"><code>v-on=&quot;$listeners&quot;</code></a> but apparently <a href=\"https://v3.vuejs.org/guide/migration/listeners-removed.html\" rel=\"nofollow noreferrer\">that was removed with Vue3</a>. I tried replacing those lines with <code>v-bind=&quot;$attrs&quot;</code> but it didn't seem to work - I will search for the VueJS 3 way to do this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-01T21:48:41.750", "Id": "520607", "Score": "2", "body": "Any answer that says \"Simon says\" gets a +1 from me" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T18:18:50.950", "Id": "262948", "ParentId": "261363", "Score": "2" } } ]
{ "AcceptedAnswerId": "262948", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T05:41:26.127", "Id": "261363", "Score": "2", "Tags": [ "javascript", "html", "ecmascript-6", "event-handling", "vue.js" ], "Title": "To-do app front-end in Vue 3" }
261363
<p>This is a Python (3) script that converts numbers among 5 data formats: binary, decimal, hexadecimal and octal, it supports 16 conversions, that is, it can convert each of the five data formats to and from the other four data formats.</p> <p>This script is adapted from my previous PowerShell script that does similar things: <a href="https://codereview.stackexchange.com/questions/260592/powershell-script-binary-decimal-hexadecimal-ipv4-convertor">PowerShell script binary-decimal-hexadecimal-ipv4 convertor</a></p> <p>I know Python 3 has three builtin functions that can convert decimal numbers to respective formats: <code>bin()</code>, <code>hex()</code>, and <code>oct()</code>, and I know I can make a binary number decimal by adding <code>0b</code> to it, and <code>0x</code> for hexadecimal and <code>0o</code> for octal, but this is about what I might come up with if I don't use builtin, and there isn't a builtin function to convert IPv4 to decimal and vice versa.</p> <p>Anyway this script uses 16 switches to identify the source format and target format, the switches are two-letter strings, the first letter specifies the source format and the second letter specifies the target, the letters are the initials of the formats(<em><strong>b</strong></em>inary, <em><strong>d</strong></em>ecimal, <em><strong>h</strong></em>exadecimal, <em><strong>I</strong></em>Pv4 and <em><strong>o</strong></em>ctal), the 16 switches are:</p> <pre><code>bd, bh, bi, bo db, dh, di, do hb, hd, hi, ho ob, od, oh, oi </code></pre> <p>Use it like this:</p> <pre><code>numconversion.py 0b11111101 bd </code></pre> <p>It can accept strings with and without the headers (<code>0b</code>, <code>0x</code> and <code>0o</code>), and can detect whether the input is valid or not, and throws errors if the input isn't valid.</p> <p>So here is the code:</p> <pre class="lang-py prettyprint-override"><code>import re import sys NIBBLES = ( ('0000', 0, '0'), ('0001', 1, '1'), ('0010', 2, '2'), ('0011', 3, '3'), ('0100', 4, '4'), ('0101', 5, '5'), ('0110', 6, '6'), ('0111', 7, '7'), ('1000', 8, '8'), ('1001', 9, '9'), ('1010', 10, 'a'), ('1011', 11, 'b'), ('1100', 12, 'c'), ('1101', 13, 'd'), ('1110', 14, 'e'), ('1111', 15, 'f') ) TYPES = ( ('binary number', '0b' + '1' * 32), ('decimal natural number', 4294967295), ('hexadecimal number', '0x' + 'f' * 8), ('IPv4 address', '255.255.255.255'), ('octal number', '0o' + '3' + '7' * 10) ) ERR = ( &quot;InvalidData: The inputted string isn't a valid {0}, process will now stop.&quot;, &quot;LimitsExceeded: The value of the inputted {0} exceeds the maximum IPv4 value possible, process will now stop.(maximum value allowed: {1})&quot; ) HEADERS = ('0b', '0d', '0x', 'ip', '0o') def splitter(regex, inv): return list(filter(''.__ne__, re.split(regex, inv))) def translator(inv, task): a, b = task outv = [] for i in inv: for j in NIBBLES: if j[a] == i: outv.append(j[b]) if b == 1: outv.reverse() return outv def worker(inv, bits, task): outv = [] for bit in bits: if inv &gt;= bit: n = inv // bit inv = inv % bit if task in (0, 2): for i in NIBBLES: if i[1] == n: outv.append(i[task]) elif task in (3, 4): outv.append(str(n)) elif inv &lt; bit and task in (0, 2): outv.append(NIBBLES[0][task]) elif inv &lt; bit and task in (3, 4): outv.append('0') return outv def converter(inv, task, base): bits = [] if task == 1: decv = 0 for p, n in enumerate(inv): decv += n * base ** p return decv elif task in (0, 2, 4): i = 1 while i &lt;= inv: bits.append(i) i *= base bits.reverse() return HEADERS[task] + ''.join(worker(inv, bits, task)).lstrip('0') elif task == 3: for i in range(3, -1, -1): bits.append(base ** i) return '.'.join(worker(inv, bits, 3)) def binsub(binv, task): if re.match('^(0b)?[01]+$', binv): binv = binv.replace('0b', '') if task in (1, 2): if len(binv) % 4 &gt; 0: binv = binv.zfill(4 * (len(binv) // 4 + 1)) bits = translator(splitter('([01]{4})', binv), (0, task)) if task == 1: return converter(bits, 1, 16) elif task == 2: return '0x' + ''.join(bits).lstrip('0') elif task == 4: bits = translator(splitter('([01]{4})', binv), (0, 1)) return decsub(converter(bits, 1, 16), 4) elif task == 3: if re.match('^[01]{1,32}$', binv): return converter(binsub(binv, 1), 3, 256) else: print('\x1b[30;3;41m' + ERR[1].format(TYPES[0][0], TYPES[0][1]) + '\x1b[0m') else: print('\x1b[30;3;41m' + ERR[0].format(TYPES[0][0]) + '\x1b[0m') def decsub(decv, task): if str(decv).isdigit(): decv = int(decv) if task in (0, 2): return converter(decv, task, 16) elif task == 4: return converter(decv, 4, 8) elif task == 3: if decv &lt;= 4294967295: return converter(decv, 3, 256) else: print('\x1b[30;3;41m' + ERR[1].format(TYPES[1][0], TYPES[1][1]) + '\x1b[0m') else: print('\x1b[30;3;41m' + ERR[0].format(TYPES[1][0]) + '\x1b[0m') def hexsub(hexv, task): hexv = hexv.lower() if re.match('^(0x)?[0-9a-f]+$', hexv): hexv = hexv.replace('0x', '') if task in (0, 1): bits = translator(splitter('([0-9a-f])', hexv), (2, task)) if task == 0: return '0b' + ''.join(bits).lstrip('0') elif task == 1: return converter(bits, 1, 16) elif task == 4: bits = translator(splitter('([0-9a-f])', hexv), (2, 1)) return decsub(converter(bits, 1, 16), 4) elif task == 3: if re.match('^[0-9a-f]{1,8}$', hexv): return converter(hexsub(hexv, 1), 3, 256) else: print('\x1b[30;3;41m' + ERR[1].format(TYPES[2][0], TYPES[2][1]) + '\x1b[0m') else: print('\x1b[30;3;41m' + ERR[0].format(TYPES[2][0]) + '\x1b[0m') def ip4sub(ipv, task): if re.match('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$', ipv): segs = list(map(int, ipv.split('.'))) segs.reverse() decv = converter(segs, 1, 256) if task == 1: return decv elif task in (0, 2, 4): return decsub(decv, task) else: print('\x1b[30;3;41m' + ERR[0].format(TYPES[3][0]) + '\x1b[0m') def octsub(octv, task): if re.match('^(0o)?[0-7]+$', octv): octv = octv.replace('0o', '') bits = list(map(int, splitter('([0-7])', octv))) bits.reverse() decv = converter(bits, 1, 8) if task == 1: return decv elif task in (0, 2): return decsub(decv, task) elif task == 3: if decv &lt;= 4294967295: return decsub(decv, 3) else: print('\x1b[30;3;41m' + ERR[1].format(TYPES[4][0], TYPES[4][1]) + '\x1b[0m') else: print('\x1b[30;3;41m' + ERR[0].format(TYPES[4][0]) + '\x1b[0m') def main(inv, task): a, b = task tasks = {'b': 0, 'd': 1, 'h': 2, 'i': 3, 'o': 4} if {a, b}.issubset(tasks.keys()) and a != b: if a == 'b': print(binsub(inv, tasks[b])) elif a == 'd': print(decsub(inv, tasks[b])) elif a == 'h': print(hexsub(inv, tasks[b])) elif a == 'i': print(ip4sub(inv, tasks[b])) elif a == 'o': print(octsub(inv, tasks[b])) else: print('\x1b[30;3;41m' + 'InvalidOperation: The operation specified is undefined, process will now stop.' + '\x1b[0m') if __name__ == '__main__': inv, task = sys.argv[1:] main(inv, task) </code></pre> <p>The functions are reused heavily, I have made the code as simple as possible, and eliminated duplication as much as I can, though I am sure it can be simpler.</p> <p>Please help me simplify my code and further eliminate code duplication and make it as simple as possible while maintaining the same logic, thank you.</p>
[]
[ { "body": "<blockquote>\n<p>I have made the code as simple as possible</p>\n</blockquote>\n<p>No you haven't, because you've arbitrarily decided to avoid a subset of built-ins. Any simplification advice I would give would be predicated on proper use of the standard library which is not the case here. Other points:</p>\n<ul>\n<li>Your <code>NIBBLES</code> and <code>BYTES</code> would be a good fit for <code>namedtuple</code></li>\n<li><code>NIBBLES</code> second element is redundant and can be assumed to be the index in the tuple</li>\n<li>Represent 4294967295 as <code>0xFFFF_FFFF</code></li>\n<li><code>list(filter(''.__ne__, re.split(regex, inv)))</code> is clearer as <code>[group for group in re.split(regex, inv) if group != '']</code></li>\n<li><code>translator</code> can drop <code>outv</code> and replace <code>append</code> with <code>yield</code>, so long as you externalize the reversal. <code>a</code> and <code>b</code> are very poor variable names, and <code>task</code> seems like it should be two separate arguments rather than a packed string.</li>\n<li>Do not unconditionally bake in ANSI escape sequences. You're not guaranteed a real TTY, so this will explode in dramatic fashion if (for example) you attempt to <code>| less</code>.</li>\n<li>Given how impenetrable some of your variable names are, at least type hinting them will help reveal some of the mystery.</li>\n</ul>\n<p>A bare-bones implementation that is not strictly equivalent - but closer to properly using the standard library - is, for example,</p>\n<pre><code>#!/usr/bin/env python3\n\nfrom dataclasses import dataclass\nfrom functools import partial\nfrom ipaddress import IPv4Address\nfrom sys import argv\nfrom typing import Callable\n\n\n@dataclass\nclass Base:\n parse: Callable[[str], int]\n format: Callable[[int], str]\n\n\nBASES = {\n 'b': Base(partial(int, base=2), '{:_b}'.format),\n 'o': Base(partial(int, base=8), '{:_o}'.format),\n 'd': Base(int, str),\n 'h': Base(partial(int, base=16), '{:_X}'.format),\n 'i': Base(\n lambda s: int(IPv4Address(s)),\n lambda i: str(IPv4Address(i)),\n ),\n}\n\n\ndef convert(original: str, task: str) -&gt; str:\n source_letter, dest_letter = task\n source, dest = BASES.get(source_letter), BASES.get(dest_letter)\n\n if source is None:\n raise ValueError(f'&quot;{source_letter}&quot; is not a valid base')\n if dest is None:\n raise ValueError(f'&quot;{dest_letter}&quot; is not a valid base')\n\n value = source.parse(original)\n return dest.format(value)\n\n\nif __name__ == '__main__':\n print(convert(*argv[1:]))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T14:34:50.577", "Id": "261379", "ParentId": "261366", "Score": "3" } }, { "body": "<p><strong>General comment</strong></p>\n<p>Your code looks good to me from an coding-style point of view and is split into various small functions which is great.</p>\n<p>A pretty easy way to make it much better would be to add documentation:</p>\n<ul>\n<li>Comments for the different constants</li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">Docstrings</a> for module and functions</li>\n</ul>\n<p>Let's see how various other details can be improved (in no specific order because I have yet to understand all the details in the code).</p>\n<p><strong>Main interface</strong></p>\n<p>You've defined a main function and a <code>if __name__ == '__main__'</code> guard which is a great habit.</p>\n<p>Here are a few things which could make things even better:</p>\n<ul>\n<li><p>Argument handling</p>\n<ul>\n<li>Check the number of arguments provided before using <code>sys.argv[1:]</code> to provide a clear error message to the user when the number of argument is incorrect</li>\n<li>Similarly, by performing <code>a, b = task</code>, you assume that <code>task</code> is (a string) of length 2 which may not be the case</li>\n</ul>\n</li>\n<li><p>Signature for the main function</p>\n<ul>\n<li>The name <code>inv</code> stills looks weird to me: I have no idea what it means in that particular context. My suggestions would be things about numbers and strings such as: <code>num_string</code>, <code>str_num</code>, <code>s</code>, <code>n</code> or maybe <code>input_str</code></li>\n<li>The name <code>task</code> is a bit clearer but my suggestions would be something about <code>formats</code>, <code>conversions</code> or <code>bases</code> such as <code>formatting_rule</code>.</li>\n<li>The <code>task</code> parameter is not really interesting as such: the first thing we do is decompose its 2 parts into <code>a</code> and <code>b</code>. The function would be easier to understand if it took 3 parameters which could be named: <code>input_str</code>, <code>input_format</code>, <code>output_format</code>.</li>\n</ul>\n</li>\n</ul>\n<p>At this stage, we have something like:</p>\n<pre><code>def main(input_str, input_format, output_format):\n formats = {\n 'b': 0,\n 'd': 1,\n 'h': 2,\n 'i': 3,\n 'o': 4\n }\n if {input_format, output_format}.issubset(formats.keys()) and input_format != output_format:\n if input_format == 'b':\n print(binsub(input_str, formats[output_format]))\n elif input_format == 'd':\n print(decsub(input_str, formats[output_format]))\n elif input_format == 'h':\n print(hexsub(input_str, formats[output_format]))\n elif input_format == 'i':\n print(ip4sub(input_str, formats[output_format]))\n elif input_format == 'o':\n print(octsub(input_str, formats[output_format]))\n else:\n print('\\x1b[30;3;41m' + 'InvalidOperation: The operation specified is undefined, process will now stop.' + '\\x1b[0m')\n\n\nif __name__ == '__main__':\n # TODO: Better parameter handling\n input_str, (input_format, output_format) = sys.argv[1:]\n main(input_str, input_format, output_format)\n</code></pre>\n<p><strong>More details about the <code>main</code> function</strong></p>\n<p>The validity of the output/input format is pretty smart, relying on set, subset, dictionnary keys... Unfortunately, it is one of those place where simpler is probably better.\nIndeed, you could just check one parameter at a time which would also give a way to have a more precise error message (&quot;THAT particular parameter has in unexpected value&quot;).</p>\n<p>We would get something like:</p>\n<pre><code>def main(input_str, input_format, output_format):\n formats = {\n 'b': 0,\n 'd': 1,\n 'h': 2,\n 'i': 3,\n 'o': 4\n }\n if input_format not in formats:\n print('\\x1b[30;3;41m' + 'InvalidOperation: The input format (&quot;%s&quot;) is invalid, process will now stop.' % input_format + '\\x1b[0m')\n elif output_format not in formats:\n print('\\x1b[30;3;41m' + 'InvalidOperation: The output format (&quot;%s&quot;) is invalid, process will now stop.' % output_format + '\\x1b[0m')\n elif input_format == output_format:\n print('\\x1b[30;3;41m' + 'InvalidOperation: The input/output format are identical (&quot;%s&quot;) is invalid, process will now stop.' % output_format + '\\x1b[0m')\n elif input_format == 'b':\n print(binsub(input_str, formats[output_format]))\n elif input_format == 'd':\n print(decsub(input_str, formats[output_format]))\n elif input_format == 'h':\n print(hexsub(input_str, formats[output_format]))\n elif input_format == 'i':\n print(ip4sub(input_str, formats[output_format]))\n elif input_format == 'o':\n print(octsub(input_str, formats[output_format]))\n else:\n assert False # This should not happen\n</code></pre>\n<p>A first thing that I'd like to point out: converting a number from an input format to an identical output format should probably be considered a valid operation: it would make the program/function easier to use but also, it would make it much easier to test. If converting &quot;42&quot; from decimal to decimal gives me anything else, this will be very straigthforward to notice. At the moment, your implementation does not (easily) easily support this but this is something that will be tackled later.</p>\n<p>Finally, because we are already relying on a dictionnary, we could try to fit all the data we need into that data structure to get rid of any superfluous code.</p>\n<p>Things would look like:</p>\n<pre><code>def main(input_str, input_format, output_format):\n formats = {\n 'b': (0, binsub),\n 'd': (1, decsub),\n 'h': (2, hexsub),\n 'i': (3, ip4sub),\n 'o': (4, octsub),\n }\n if input_format not in formats:\n print('\\x1b[30;3;41m' + 'InvalidOperation: The input format (&quot;%s&quot;) is invalid, process will now stop.' % input_format + '\\x1b[0m')\n return\n _, input_func = formats[input_format]\n if output_format not in formats:\n print('\\x1b[30;3;41m' + 'InvalidOperation: The output format (&quot;%s&quot;) is invalid, process will now stop.' % output_format + '\\x1b[0m')\n return\n output_code, _ = formats[output_format]\n if input_format == output_format: # TODO: Remove this eventually\n print('\\x1b[30;3;41m' + 'InvalidOperation: The input/output format are identical (&quot;%s&quot;) is invalid, process will now stop.' % output_format + '\\x1b[0m')\n print(input_func(input_str, output_code))\n</code></pre>\n<p><strong>Error formatting</strong></p>\n<p>You are using the keycode for colors in the terminal which is a nice touch (and ensuring that the style goes back to normal afterward is great). Unfortunately, having the hard coded values everywhere in the code make it bloated and hard to understand.</p>\n<p>Defining 2 simple constants makes things much clearer already.</p>\n<pre><code># STYLES FOR TERMINAL\nITALIC_RED = '\\x1b[30;3;41m'\nNORMAL = '\\x1b[0m'\n...\nprint(ITALIC_RED + 'InvalidOperation: The input format (&quot;%s&quot;) is invalid, process will now stop.' % input_format + NORMAL)\n</code></pre>\n<p>An even better approach could be to define a function for this so that if you want to change how things are displayed, you have a single place to update.</p>\n<p>You'd get something like:</p>\n<pre><code>def show_error(msg):\n &quot;&quot;&quot;Show error with message msg.&quot;&quot;&quot;\n print(ITALIC_RED + msg + NORMAL)\n</code></pre>\n<p>(Going further, one could also decide to print in stderr instead of stdout).</p>\n<p><strong>Error messages</strong></p>\n<p>The error messages are in a tuple and accessed by index when needed.\nIt would be much clearer to define 2 constants for this:</p>\n<p>We'd have:</p>\n<pre><code># Error message for common conversion errors\nINVALID_DATA_ERR = &quot;InvalidData: The inputted string isn't a valid {0}, process will now stop.&quot;\nLIMITS_EXCEEDED_ERR = &quot;LimitsExceeded: The value of the inputted {0} exceeds the maximum IPv4 value possible, process will now stop.(maximum value allowed: {1})&quot;\n\n...\n\n else:\n show_error(LIMITS_EXCEEDED_ERR.format(TYPES[0][0], TYPES[0][1]))\n else:\n show_error(INVALID_DATA_ERR.format(TYPES[0][0]))\n</code></pre>\n<p>The same logic applies to the values you put into the error messages. The <code>TYPES</code> tuple is accessed by index, it would be easier to define various constants:</p>\n<pre><code># Description (name, limit) of the different formats to be used in error messages\nBIN_DESCR = ('binary number', '0b' + '1' * 32)\nDEC_DESCR = ('decimal natural number', 4294967295)\nHEX_DESCR = ('hexadecimal number', '0x' + 'f' * 8)\nIP4_DESCR = ('IPv4 address', '255.255.255.255')\nOCT_DESCR = ('octal number', '0o' + '3' + '7' * 10)\n\n...\n\n else:\n show_error(LIMITS_EXCEEDED_ERR.format(*HEX_DESCR))\n else:\n show_error(INVALID_DATA_ERR.format(*HEX_DESCR))\n</code></pre>\n<p><strong>Conversion</strong></p>\n<p>I have not tackled the parts about the conversion yet but it looks like this got comments by other reviewers already.</p>\n<p>My main concern is the fact that we always seem to intermix the logic about the input format and the logic about the output format (but I may be wrong entirely).</p>\n<p>In my opinion, the different steps should be:</p>\n<ul>\n<li><p>Convert the input string into a Python integer based on the input format (and maybe check the string validity)</p>\n</li>\n<li><p>Convert that input into a string based on the output format</p>\n</li>\n</ul>\n<p>This is a much better separation of the concerns. Also, adding a new supported format is much easier: you just need to be able to convert a number in a string and a string in a number without worrying about the already existing supporting formats.</p>\n<hr />\n<p>Here is my take on this programming problem:</p>\n<pre><code>\n\nfrom collections import namedtuple\n\nFormat = namedtuple('Format', ['name', 'symbols', 'prefixes'])\n\ndef convert_string_to_number(string, input_fmt):\n &quot;&quot;&quot;Convert a string to a number based on an input format.&quot;&quot;&quot;\n # Create mapping from symbols to values\n symbols_values = { c: i for i, c in enumerate(input_fmt.symbols) }\n base = len(symbols_values)\n # Remove optional prefix (such as Ox)\n for prefix in input_fmt.prefixes:\n if string.startswith(prefix):\n string = string[len(prefix):]\n break\n # Perform the conversion\n n = 0\n for c in string:\n val = symbols_values.get(c, None)\n if val is None:\n show_error('Invalid symbol %s during conversion of %s in %s' % (c, string, input_fmt.name))\n return None\n n = n * base + val\n return n\n\ndef format_number(number, output_fmt):\n &quot;&quot;&quot;Format a number based on an ouput format.&quot;&quot;&quot;\n base = len(output_fmt.symbols)\n symbols = []\n while number:\n number, rem = divmod(number, base)\n symbols.append(output_fmt.symbols[rem])\n return &quot;&quot;.join(reversed(symbols))\n\n\ndef main(input_str, input_format, output_format):\n formats = {\n 'b': Format('binary', '01', []),\n 'd': Format('decimal', '0123456789', []),\n 'o': Format('octal', '01234567', []),\n 'h': Format('hexadecimal', '0123456789ABCDEF', ['0x']),\n }\n input_fmt = formats.get(input_format, None)\n if input_fmt is None:\n show_error('InvalidOperation: The input format (&quot;%s&quot;) is invalid, process will now stop.' % input_format)\n return\n output_fmt = formats.get(output_format, None)\n if output_fmt is None:\n show_error('InvalidOperation: The output format (&quot;%s&quot;) is invalid, process will now stop.' % output_format)\n return\n n = convert_string_to_number(input_str, input_fmt)\n print(format_number(n, output_fmt))\n\n\nif __name__ == '__main__':\n # TODO: Better parameter handling\n input_str, (input_format, output_format) = sys.argv[1:]\n</code></pre>\n<p>Various features are missing compared to your implementation but I think it gives a few ideas.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T15:24:24.713", "Id": "261382", "ParentId": "261366", "Score": "2" } }, { "body": "<p>Hmm, after some hard working I have made huge improvements to my code, I have significantly reduced the number of lines it spans and rewritten almost everything.</p>\n<p>It now uses bit shifts to handle the conversions, and it uses one line to convert the other four formats into decimal, and another line to convert decimal into the other four formats, with some conditional lines to help the conversions.</p>\n<p>I now use one function to handle the data processing, and the script now checks arguments before running the function.</p>\n<p>There might be further improvements but I have done absolutely my best for now, anyway here is the code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import re\nimport sys\nfrom collections import namedtuple\n\nkind = namedtuple('kind', 'name header max regex slicer')\n\nSWITCH = {'b': 0, 'd': 1, 'h': 2, 'i': 3, 'o': 4}\n\nHEXD = (\n '0', '1', '2', '3',\n '4', '5', '6', '7',\n '8', '9', 'a', 'b',\n 'c', 'd', 'e', 'f'\n)\n\nTYPES = (\n kind('binary number', '0b', '0b'+'1'*32, '^(0b)?[01]+$', '([01])'),\n kind('decimal natural', None, 4294967295, '^\\d+$', None),\n kind('hexadecimal number', '0x', '0x'+'f' * 8, '^(0x)?[\\da-f]+$', '([\\da-f])'),\n kind('IPv4 address', None, '255.255.255.255', '^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$', '\\.'),\n kind('octal number', '0o', '0o'+'3'+'7'*10, '^(0o)?[0-7]+$', '([0-7])')\n)\n\nERR = (\n &quot;InvalidData: The inputted string isn't a valid {0}, process will now stop.&quot;,\n &quot;LimitsExceeded: The value of the inputted {0} exceeds the maximum IPv4 value possible, process will now stop.(maximum value allowed: {1})&quot;,\n 'InvalidOperation: The operation specified is undefined, process will now stop.',\n &quot;Invalid Operation: The number of arguments passed to the script isn't three, process will now stop&quot;\n)\n\n\ndef splitter(regex, val):\n return list(filter(''.__ne__, re.split(regex, val)))\n\n\ndef showerror(msg):\n return '\\x1b[30;3;41m' + msg + '\\x1b[0m'\n\n\ndef weights(val, base):\n expos = []\n a, b = 1, 0\n while a &lt;= val:\n expos.append(b)\n a *= base\n b += 1\n expos.reverse()\n return expos\n\n\ndef converter(val, a, b):\n if b == 1:\n val.reverse()\n k = (1, None, 4, 8, 3)\n if a in (0, 3, 4):\n val = list(map(int, val))\n elif a == 2:\n val = [HEXD.index(i) for i in val]\n return sum([int(n) &lt;&lt; k[a] * p for p, n in enumerate(val)])\n elif a == 1:\n c = ((2, 1), None, (16, 4), (256, 8), (8, 3))\n d, e = c[b]\n bits = []\n if b in (0, 2, 4):\n digits = weights(val, d)\n elif b == 3:\n digits = (3, 2, 1, 0)\n for f in digits:\n bit = (val &gt;&gt; e * f) % d\n if b in (0, 3, 4):\n bits.append(str(bit))\n elif b == 2:\n bits.append(HEXD[bit])\n if b in (0, 2, 4):\n return TYPES[b].header + ''.join(bits)\n elif b == 3:\n return '.'.join(bits)\n\n\ndef main(val, a, b):\n if re.match(TYPES[a].regex, val):\n if b != 3:\n if a == 1:\n val = int(val)\n return converter(val, 1, b)\n else:\n bits = splitter(TYPES[a].slicer, val.lstrip(TYPES[a].header))\n decv = converter(bits, a, 1)\n if b == 1:\n return decv\n else:\n return converter(decv, 1, b)\n else:\n if a == 1:\n decv = int(val)\n else:\n decv = main(val, a, 1)\n if decv &lt;= 4294967295:\n return converter(decv, 1, 3)\n else:\n return showerror(ERR[1].format(TYPES[a].name, TYPES[a].max))\n else:\n return showerror(ERR[0].format(TYPES[a].name))\n\n\nif __name__ == '__main__':\n if len(sys.argv[1:]) == 3:\n val, x, y = sys.argv[1:]\n if {x, y}.issubset(SWITCH.keys()) and x != y:\n x = SWITCH[x]\n y = SWITCH[y]\n print(main(val, x, y))\n else:\n print(showerror(ERR[2]))\n else:\n print(showerror(ERR[3]))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T08:24:20.063", "Id": "261413", "ParentId": "261366", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T08:06:49.450", "Id": "261366", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "reinventing-the-wheel", "converting" ], "Title": "Python binary, decimal, hexadecimal, IPv4, octal converter" }
261366
<p>I have a <code>match</code> arm in rust, I think it may be simplified, but after googling and read books, I haven't find the solution. Especially for the <code>str_vec.pop()</code>, it returns an <code>option</code> type, I have to write a meanless <code>()</code> to make it compileable.</p> <pre><code>pub fn simplify_path(path: &amp;String) -&gt; String { let mut str_vec: Vec&lt;&amp;str&gt; = Vec::with_capacity(20); for line in path.split('/') { match line { &quot;&quot; | &quot;.&quot; =&gt; {} &quot;..&quot; =&gt; { str_vec.pop(); () } _ =&gt; str_vec.push(line), } } &quot;/&quot;.to_string() + &amp;str_vec.join(&quot;/&quot;) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T09:42:14.973", "Id": "515786", "Score": "1", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T10:38:07.773", "Id": "515789", "Score": "0", "body": "@Mast Thank you for such great advice, I have fixed the title." } ]
[ { "body": "<p>The <code>()</code> is not needed in this example - the following example compiles fine.</p>\n<pre class=\"lang-rs prettyprint-override\"><code>match line {\n &quot;&quot; | &quot;.&quot; =&gt; {}\n &quot;..&quot; =&gt; {\n str_vec.pop();\n }\n _ =&gt; str_vec.push(line),\n}\n</code></pre>\n<p>This is as all arms need to return the same type, and in this case it is the type <code>()</code>. Luckily this type is inferred, and as such you can just make a block and (as long as it doesn't return anything), it will be inferred that the <code>()</code> type is being returned instead.</p>\n<p>I would recommend making some other changes to your code though - namely changing the <code>&amp;String</code> argument to <code>&amp;str</code>, which can improve performance in some cases and allow more string types (such as a string literal) to be passed to the function. This type of issue can be picked up by running clippy, which also picks up a wide variety of issues - a full list can be found at <a href=\"https://rust-lang.github.io/rust-clippy/master/\" rel=\"nofollow noreferrer\">https://rust-lang.github.io/rust-clippy/master/</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T12:22:56.763", "Id": "261375", "ParentId": "261367", "Score": "3" } } ]
{ "AcceptedAnswerId": "261375", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T08:23:33.020", "Id": "261367", "Score": "2", "Tags": [ "rust" ], "Title": "Simplify a Unix-style absolute path" }
261367
<p><strong>Its an Basic Calculator I worked on, and now I wanna know if I can make something better like not so &quot;much&quot; Code or I made somthing to complicated? Have a nice day! Keep safe!</strong></p> <pre><code> import java.util.Scanner; public class learningCode { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println(&quot;Bitte geben sie einen Rechenoperator für ihre Rechnung ein! (+, -, *, /)&quot;); String numberTest = scan.nextLine(); if (numberTest.equals(&quot;+&quot;)) { String questionOne = &quot;Bitte gebe deine erste Zahl ein: &quot;; System.out.println(questionOne); double number1 = scan.nextDouble(); String questionTwo = &quot;Bitte gebe deine zweite Zahl ein: &quot;; System.out.println(questionTwo); double number2 = scan.nextDouble(); double finalResult = number1 + number2; String Answer = &quot;Dein Ergebnis ist: &quot;; System.out.println(Answer + finalResult ); scan.close(); } else { if (!&quot;+&quot;.equals(numberTest) &amp;&amp; !&quot;-&quot;.equals(numberTest) &amp;&amp; !&quot;*&quot;.equals(numberTest) &amp;&amp; !&quot;/&quot;.equals(numberTest)) { System.out.println(&quot;Das ist kein Rechenoperator. Bitte versuche es erneut!&quot;); } if (numberTest.equals(&quot;*&quot;)) { String questionTwo = &quot;Bitte gebe deine erste Zahl ein: &quot;; System.out.println(questionTwo); double number1 = scan.nextDouble(); String questionThree = &quot;Bitte gebe deine zweite Zahl ein: &quot;; System.out.println(questionThree); double number2 = scan.nextDouble(); double finalResult = number1 * number2; String Answer = &quot;Dein Ergebnis ist: &quot;; System.out.println(Answer + finalResult ); scan.close(); } if (numberTest.equals(&quot;/&quot;)) { String questionThree = &quot;Bitte gebe deine erste Zahl ein: &quot;; System.out.println(questionThree); double number1 = scan.nextDouble(); String questionFour = &quot;Bitte gebe deine zweite Zahl ein: &quot;; System.out.println(questionFour); double number2 = scan.nextDouble(); double finalResult = number1 / number2; String Answer = &quot;Dein Ergebnis ist: &quot;; System.out.println(Answer + finalResult ); scan.close(); } if (numberTest.equals(&quot;-&quot;)) { String questionFive = &quot;Bitte gebe deine erste Zahl ein: &quot;; System.out.println(questionFive); double number1 = scan.nextDouble(); String questionSix = &quot;Bitte gebe deine zweite Zahl ein: &quot;; System.out.println(questionSix); double number2 = scan.nextDouble(); double finalResult = number1 - number2; String Answer = &quot;Dein Ergebnis ist: &quot;; System.out.println(Answer + finalResult ); scan.close(); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T09:42:11.103", "Id": "515785", "Score": "1", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." } ]
[ { "body": "<h2>Naming</h2>\n<h3>Adhere to the Java Naming Conventions.</h3>\n<ul>\n<li><p>Names of methods and variables start with a lowercase letter, names of classes with an uppercase letter.</p>\n</li>\n<li><p>Method names should start with a verb so that they read like an instruction. Names of variables should start with a noun.</p>\n</li>\n<li><p>Exception to that are variables holding or methods returning a boolean which both should start with is, can, has or alike.</p>\n</li>\n</ul>\n<h3>Don't surprise your readers</h3>\n<p>You have a variable named <code>numberTest</code> but it does not contain a <em>test for a number</em> but <em>the current operation</em> or the <em>users choice</em>.</p>\n<h2>Code Quality</h2>\n<h3>Structure your code with methods.</h3>\n<p>You wrote a single long method.\nThis method contains an <code>if/else</code> cascade that somehow separates the method in to different sections.</p>\n<p>You should extract this blocks in to separate Methods (leaving the <code>if/else</code> instructions in <code>main</code>) so that the <code>main</code> method becomes shorter and easier to read (and to maintain).</p>\n<h3>Don't repeat yourself</h3>\n<p>All over your code you repeat this two lines with varying variable names:</p>\n<pre><code> System.out.println(questionSix);\n double number2 = scan.nextDouble();\n</code></pre>\n<p>This two lines could be extracted to a separate method that takes the <code>String</code> as <em>parameter</em> and returns the <code>double</code> value. That would shrink four lines in your code to just one.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T10:46:04.807", "Id": "261371", "ParentId": "261369", "Score": "3" } }, { "body": "<p>since in all if statement you are asking the user to enter the left and right operand aside with receiving (scanning) the input nothing is different but the operand only.\nthe better approach could be to take all those similar statements out of each IF statement and put them at the beginning of the program.\nthen switch the character and perform the arithmetic according to its case.</p>\n<pre><code>public static void main(String[] arg){\n Scanner scan = new Scanner(System.in);\n System.out.println(&quot;Bitte gebe deine erste Zahl ein: &quot;);\n double number1 = scan.nextDouble();\n System.out.println(&quot;Bitte geben sie einen Rechenoperator für ihre Rechnung ein! (+, -, *, /)&quot;);\n String operator = scan.next();\n System.out.println(&quot;Bitte gebe deine zweite Zahl ein: &quot;);\n double number2 = scan.nextDouble();\n double finalResult=0.0;\n switch(operator){\n case &quot;+&quot;:\n finalResult= number1 + number2;\n break;\n case &quot;-&quot;:\n finalResult= number1 - number2;\n break;\n case &quot;/&quot;:\n finalResult= number1 / number2;\n break;\n case &quot;*&quot;:\n finalResult= number1 * number2;\n break;\n default:\n System.out.println(&quot;invalid operator&quot;);\n }\n String Answer = &quot;Dein Ergebnis ist: &quot;;\n System.out.println(Answer + finalResult );\n scan.close();\n}\n</code></pre>\n<p>hope this helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T15:17:19.953", "Id": "261425", "ParentId": "261369", "Score": "0" } } ]
{ "AcceptedAnswerId": "261371", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T09:01:49.510", "Id": "261369", "Score": "2", "Tags": [ "java" ], "Title": "Basic command-line calculator" }
261369
<p>I have this small C++ program for computing the <span class="math-container">\$n\$</span>th Tribonacci number at compile-time. My main concern is: is it possible to get rid of the <code>static</code>keyword (I had to use it in order to silence my compiler (VS 2019))?</p> <p><strong>Code</strong></p> <pre><code>#include &lt;cstdint&gt; #include &lt;iostream&gt; template&lt;uint64_t N&gt; struct tribonacci { constexpr static uint64_t value = tribonacci&lt;N - 1&gt;::value + tribonacci&lt;N - 2&gt;::value + tribonacci&lt;N - 3&gt;::value; }; template&lt;&gt; struct tribonacci&lt;0&gt; { constexpr static uint64_t value = 0; }; template&lt;&gt; struct tribonacci&lt;1&gt; { constexpr static uint64_t value = 0; }; template&lt;&gt; struct tribonacci&lt;2&gt; { constexpr static uint64_t value = 1; }; int main() { std::cout &lt;&lt; tribonacci&lt;6&gt;::value; return 0; } </code></pre>
[]
[ { "body": "<p>This is a pretty cool practice project, and your implementation is sound.</p>\n<p>First to answer your concern… can you drop the <code>static</code>? The answer is no… and yes.</p>\n<p>The way you’ve implemented the solution, no, you really can’t drop the <code>static</code>. The code doesn’t really make sense without it. If you are doing <code>tribonacci&lt;N&gt;::value</code>, and <code>tribonacci&lt;N&gt;</code> is a type (as it is in your code), then <code>value</code> <em>must</em> be a static data member. That’s what the <code>::</code> means (in this context); <code>tribonacci&lt;N&gt;</code> is a type, and <code>value</code> is a property of the type.</p>\n<p><em>However</em>….</p>\n<p>This is how you would implement a <code>constexpr</code> tribonacci sequence generator in C++11. That’s 3 versions old now, and counting. And one of the things that has advanced the most in each new version of C++ is <code>constexpr</code> capability.</p>\n<p>If you don’t want <code>value</code> to be a <em>class</em> data member, you could make it a regular data member, like so:</p>\n<pre><code>template &lt;std::size_t N&gt;\nstruct tribonacci\n{\n std::int_fast64_t const value = tribonacci&lt;N - 1&gt;{} + tribonacci&lt;N - 2&gt;{} + tribonacci&lt;N - 3&gt;{};\n\n constexpr operator std::int_fast64_t() const noexcept { return value; }\n};\n\ntemplate &lt;&gt;\nstruct tribonacci&lt;0&gt;\n{\n std::int_fast64_t const value = 0;\n\n constexpr operator std::int_fast64_t() const noexcept { return value; }\n};\n\ntemplate &lt;&gt;\nstruct tribonacci&lt;1&gt;\n{\n std::int_fast64_t const value = 0;\n\n constexpr operator std::int_fast64_t() const noexcept { return value; }\n};\n\ntemplate &lt;&gt;\nstruct tribonacci&lt;2&gt;\n{\n std::int_fast64_t const value = 1;\n\n constexpr operator std::int_fast64_t() const noexcept { return value; }\n};\n\nauto main() -&gt; int\n{\n constexpr auto sixth_trib_num = tribonacci&lt;6&gt;{}; // to prove it's constexpr\n\n std::cout &lt;&lt; tribonacci&lt;0&gt;{} &lt;&lt; '\\n'; // will auto-convert to std::int_fast64_t\n std::cout &lt;&lt; tribonacci&lt;1&gt;{}.value &lt;&lt; '\\n'; // or you can manually request the value\n std::cout &lt;&lt; tribonacci&lt;2&gt;{} &lt;&lt; '\\n';\n std::cout &lt;&lt; tribonacci&lt;3&gt;{} &lt;&lt; '\\n';\n std::cout &lt;&lt; tribonacci&lt;4&gt;{} &lt;&lt; '\\n';\n std::cout &lt;&lt; tribonacci&lt;5&gt;{} &lt;&lt; '\\n';\n std::cout &lt;&lt; sixth_trib_num &lt;&lt; '\\n';\n}\n</code></pre>\n<p>As you can see, no more <code>static</code>, but now you need to actually create an object (like <code>tribonacci&lt;6&gt;{}</code>) rather than just using the type (like <code>tribonacci&lt;6&gt;</code>), because now <code>value</code> is a property of the <em>object</em>, not the type (like <code>tribonacci&lt;6&gt;{}.value</code>).</p>\n<p>Perhaps an even better option is to use variable templates. After all, each tribonacci number is just a number… it doesn’t need to be a type.</p>\n<pre><code>template &lt;std::size_t N&gt;\ninline constexpr auto tribonacci = tribonacci&lt;N - 1&gt; + tribonacci&lt;N - 2&gt; + tribonacci&lt;N - 3&gt;;\n\ntemplate &lt;&gt;\ninline constexpr auto tribonacci&lt;0&gt; = std::int_fast64_t{0};\n\ntemplate &lt;&gt;\ninline constexpr auto tribonacci&lt;1&gt; = std::int_fast64_t{0};\n\ntemplate &lt;&gt;\ninline constexpr auto tribonacci&lt;2&gt; = std::int_fast64_t{1};\n\nauto main() -&gt; int\n{\n std::cout &lt;&lt; tribonacci&lt;0&gt; &lt;&lt; '\\n';\n std::cout &lt;&lt; tribonacci&lt;1&gt; &lt;&lt; '\\n';\n std::cout &lt;&lt; tribonacci&lt;2&gt; &lt;&lt; '\\n';\n std::cout &lt;&lt; tribonacci&lt;3&gt; &lt;&lt; '\\n';\n std::cout &lt;&lt; tribonacci&lt;4&gt; &lt;&lt; '\\n';\n std::cout &lt;&lt; tribonacci&lt;5&gt; &lt;&lt; '\\n';\n std::cout &lt;&lt; tribonacci&lt;6&gt; &lt;&lt; '\\n';\n}\n</code></pre>\n<p>With this, <code>tribonacci&lt;6&gt;</code> <em>is</em> a <code>std::int_fast64_t</code> constant. There are no classes to instantiate or any other cruft. This probably the way you want to go in C++14 and beyond; certainly in C++20 and beyond.</p>\n<p>So, no, you can’t drop the <code>static</code> if you’re using the design you currently have. But there are other, better, alternatives in more modern versions of C++.</p>\n<p>Now for your actual code review….</p>\n<pre><code>template&lt;uint64_t N&gt;\nstruct tribonacci {\n</code></pre>\n<p>First, if you’re going to use <code>uint64_t</code>, it <em>should</em> be spelled <code>std::uint64_t</code>.</p>\n<p>But using <code>uint64_t</code> is generally a bad idea. You see, <code>uint64_t</code> is an <em>optional</em> type; it is not guaranteed to exist. And if it does, it is not guaranteed to be an efficient type; it could actually require significant emulation to work, and it could be tragically slow.</p>\n<p>Better options are <code>unsigned long long</code>, <code>std::uint_fast64_t</code>, <code>std::uint_least64_t</code>. Which one you choose depends on what you really want:</p>\n<ul>\n<li><code>unsigned long long</code>: This is guaranteed to be at least 64 bits… but could (theoretically) be 128 bits, 256 bits, or anything else. If you only need 64 bits, it could be overkill. However, it will probably be <em>at least</em> as efficient (speed-wise, not space-wise) as any other option, if not more.</li>\n<li><code>std::uint_fast64_t</code>: If you <em>really</em> just need a 64-bit type, this should be your default choice. It will be the fastest type supported by the architecture that is at least 64 bits. So it <em>may</em> be more than 64 bits (like <code>unsigned long long</code> it <em>may</em> be 128 bits, or 256 bits, or whatever). But it may be smaller than <code>unsigned long long</code>, and <em>probably</em> as fast.</li>\n<li><code>std::uint_least64_t</code>: This is what you use when you want a type that is at least 64 bits, but you care more about conserving space than getting maximum speed. This will be the smallest type the platform supports that can hold 64-bit values… even if that type requires lots of code to emulate.</li>\n</ul>\n<p>So, in a table, your options are (note that the size and speed are the <em>worst</em> case estimates):</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Type</th>\n<th>Size</th>\n<th>Speed</th>\n<th>Notes</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>std::uint64_t</code></td>\n<td>Bad</td>\n<td>Bad</td>\n<td>Not guaranteed to exist</td>\n</tr>\n<tr>\n<td><code>unsigned long long</code></td>\n<td>Bad</td>\n<td>Excellent</td>\n<td>Good choice if you need <em>at least</em> 64 bits, but much more is fine too</td>\n</tr>\n<tr>\n<td><code>std::uint_fast64_t</code></td>\n<td>Good</td>\n<td>Good</td>\n<td>Best choice if you <em>only</em> need 64 bits</td>\n</tr>\n<tr>\n<td><code>std::uint_least64_t</code></td>\n<td>Excellent</td>\n<td>Bad</td>\n<td>Best choice for saving space</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>There is another issue with <code>uint64_t</code>, and that is that it’s an unsigned type. Using unsigned types for general purpose numbers is a bad idea, for a number of reasons. You should only use unsigned numbers if you are doing bit-twiddling, or if you explicitly need modulo arithmetic. Otherwise, signed should be the default choice. The problems unsigned numbers cause are not worth the one extra bit of space.</p>\n<p>Of course, you could also let the user pick the type:</p>\n<pre><code>template &lt;std::size_t N, typename T = int&gt; // defaults to regular old int\ninline constexpr auto tribonacci = T(tribonacci&lt;N - 1&gt; + tribonacci&lt;N - 2&gt; + tribonacci&lt;N - 3&gt;);\n\n// note in c++20, you could also constrain the type, like so:\n// template &lt;std::size_t N, std::integral T = int&gt;\n\ntemplate &lt;typename T&gt;\ninline constexpr auto tribonacci&lt;0, T&gt; = T(0);\n\ntemplate &lt;typename T&gt;\ninline constexpr auto tribonacci&lt;1, T&gt; = T(0);\n\ntemplate &lt;typename T&gt;\ninline constexpr auto tribonacci&lt;2, T&gt; = T(1);\n\n// if you're working with int_fast64_t a lot, then make a handy alias\ntemplate &lt;std::size_t N&gt;\ninline constexpr auto tribonacci64 = tribonacci&lt;N, std::int_fast64_t&gt;;\n\nauto main() -&gt; int\n{\n std::cout &lt;&lt; tribonacci&lt;0&gt; &lt;&lt; '\\n'; // int(0)\n std::cout &lt;&lt; tribonacci&lt;1, long&gt; &lt;&lt; '\\n'; // long(0)\n std::cout &lt;&lt; tribonacci&lt;2, std::int64_t&gt; &lt;&lt; '\\n' ; // int64_t(1)\n std::cout &lt;&lt; tribonacci64&lt;3&gt; &lt;&lt; '\\n'; // int_fast64_t(1)\n}\n</code></pre>\n<p>Finally, I don’t know if you noticed, but in all the examples I made, I made the <em>index</em> type <code>std::size_t</code>, and the <em>value</em> type something else: <code>int</code>, <code>std::uint_fast64_t</code> or whatever. That’s because when you do <code>auto v = tribonacci&lt;N&gt;</code>, the <code>N</code> has nothing to do with the actual tribonacci number. It’s just the counter to pick <em>which</em> tribonacci number you want. <code>v</code> is the actual tribonacci number. That’s what you want to be at least 64 bits or whatever. <code>N</code> doesn’t need to be 64 bits; you’re going to blow past 64 bits by the 75th tribonacci number, so you only need <code>N</code> to be able to hold <em>7</em> bits for 64-bit tribonacci numbers.</p>\n<p><code>std::size_t</code> is the default type in C++ for counting, indexing, sizes, and so on. So it makes sense for <code>N</code> to be <code>std::size_t</code>. As for the value type… that should be whatever the user wants. Above I went with <code>int</code> by default (as you always should).</p>\n<p>That’s pretty much it for the review. My recommendations:</p>\n<ol>\n<li>Don’t use <code>uint64_t</code> as the value type for the tribonacci number:\n<ul>\n<li>Don’t use unsigned types for general numbers.</li>\n<li>Don’t use fixed size types. They’re not portable, and even when they are, they might be inefficient.</li>\n<li>Let the user pick the type, though you can offer a sensible default (which should probably be <code>int</code>).</li>\n<li>It’s <code>std::uint64_t</code> anyway.</li>\n</ul>\n</li>\n<li>Don’t use <code>uint64_t</code> as the index type:\n<ul>\n<li>The default index type is <code>std::size_t</code>.</li>\n</ul>\n</li>\n<li>Rather than old-school template meta-programming, using types for each tribonacci number, use variable templates.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T17:21:45.407", "Id": "515821", "Score": "0", "body": "Thanks a lot! You covered quite a bit of issues." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T11:02:59.767", "Id": "515873", "Score": "0", "body": "I think the table you presented is questionable. Why would `unsigned long long` have \"excellent\" speed vs. `uint_fast64_t` only having \"good\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T11:14:27.067", "Id": "515874", "Score": "0", "body": "The table values are explained in the text just above it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T15:47:14.830", "Id": "515894", "Score": "1", "body": "But why would `unsigned long long` \"probably at least as efficient as any other option\", when the whole point of `uint_fast64_t` is to be the fastest type that has at least 64 bits? I would just say: use `uint_fast*_t` if you want the fastest type, `uint_least*_t` if you want the smallest type, `uint*_t` if you want an exact type, and built-in types if you don't care either way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T19:45:50.707", "Id": "516005", "Score": "0", "body": "Isn’t that what the table says? The fast and least types are both “best” for their purposes, and `unsigned long long` is only “good” if you don’t really care." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T15:31:17.693", "Id": "261384", "ParentId": "261372", "Score": "2" } } ]
{ "AcceptedAnswerId": "261384", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T11:05:32.333", "Id": "261372", "Score": "2", "Tags": [ "c++", "template-meta-programming" ], "Title": "Computing nth Tribonacci number at compile time using C++ template metaprogramming facilities" }
261372
<p>I'm learning to set up systemd file-transfer &amp; related services (samba, ftp, http..). So far it's all LAN or WLAN.</p> <p>The configuration file for most these services is under <code>/etc/&lt;bin&gt;.conf</code> (like smbd.conf or vsftpd.conf). Because systemd services running on port &lt; 1000 have to be run as root. (systemd --user won't work.)</p> <p>The idea is that the users connect to a directory, anonymous users only have read privileges, local users read and write. (I am guessing anonymous won't be treated as local user, but this still needs testing). Also from the manpages <strong><a href="http://vsftpd.beasts.org/vsftpd_conf.html" rel="nofollow noreferrer">anonymous_enable</a></strong></p> <blockquote> <p>Controls whether anonymous logins are permitted or not. If enabled, both the usernames ftp and anonymous are recognised as anonymous logins.</p> </blockquote> <p>Communication is TLS encrypted just to avoid people sniffing in the LAN.</p> <pre><code># GENERAL listen_ipv6=YES # accept connections from IPv6 and IPv4 clients. write_enable=YES # enable any form of FTP write command. # choose no for FTP read-only sites. connect_from_port_20=YES # LOGS xferlog_enable=YES # Activate logging of uploads/downloads. xferlog_file=/home/minsky/logs/ftp/vsftpd.log # TIMEOUTS idle_session_timeout=600 #10 min data_connection_timeout=30 # SECURITY (encrypt connections) # Certificate and private file generated with openssl. rsa_cert_file=/etc/pki/tls/certs/ftp_cert.crt rsa_private_key_file=/etc/pki/tls/certs/FTP.key ssl_enable=YES allow_anon_ssl=YES ssl_tlsv1=YES ssl_ciphers=HIGH require_ssl_reuse=NO # Anonymous user (ftp) ftp_username=anonymous # cat /etc/passwd: anonymous:x:996:996:ftp anonymous:/home/anonymous:/bin/bash anonymous_enable=YES # user:ftp or anonymous anon_upload_enable=YES # upload files. no_anon_password=YES #no password anon_root=/home/minsky/public #switch to anon_mkdir_write_enable=NO anon_other_write_enable=NO # Local users (will need pwd unless is user &quot;anonymous&quot;) local_enable=YES # Allow local users to log in. local_root=/home/minsky/ # switch to dir # Special user (requested by vsftpd config file) nopriv_user=unprivileged # cat /etc/passwd: unprivileged:x:997:997:FTP unprivileged acc:/home/unprivileged:/sbin/nologin # Customization #secure_chroot_dir=/var/run/vsftpd/empty #necessary ftpd_banner=Welcome to Raspberry Pi FTP service. # </code></pre> <p>I think one problem here could be that the user could move off the <code>/public</code> directory, though I'm still to test this.</p> <p>Any recommendations or questions about the configuration file or the process are really welcome.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T11:37:52.267", "Id": "261373", "Score": "0", "Tags": [ "linux", "configuration", "web-services", "ftp" ], "Title": "VSFTPD server configuration file" }
261373
<p>I have seen many posts regarding a standard 52-card deck of playing cards. I recently was composing an answer to one such post when I realized my answer should be its own post since (A) the answer diverged greatly from the OP and (B) my classes addressed my own objectives and not the OP's.</p> <p>I have no specific questions other than the implied at CR: please review and critique the code. My particular interest is in the API, but I also welcome comments about the Console UI example. I am using <strong>C#</strong> and <strong>.NET 5</strong>.</p> <p><a href="https://i.stack.imgur.com/KxTrG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KxTrG.png" alt="enter image description here" /></a></p> <p><strong>Here are my objectives:</strong></p> <p>The base objects of <code>Rank</code>, <code>Suit</code>, <code>Card</code>, and <code>Deck</code> will exist in a re-useable API which can be used by any UI application, be it Console-based, WPF, WinForms, Unity, etc.</p> <ul> <li><p>I want to generate a standard 52-deck of cards.</p> </li> <li><p>I also want the versatility to generate many other types of decks from that same API. Maybe I want a deck that includes 1 or more Jokers. Maybe I want a non-standard deck composed of 2 suits of 10 cards each. Maybe I want a casino style super deck composed of 6 standard decks.</p> </li> <li><p>I want to <em><strong>completely</strong></em> avoid the magic numbers of 13, 4, and 52. I want to go as far as avoiding them as constants.</p> </li> <li><p>While many use only an <code>enum</code> for rank or suit, I want a little more meta data associated with each rank and suit. For example, the color is the suit is nice to know in an API.</p> </li> </ul> <p><strong>About the API</strong></p> <p>My <code>Rank</code> struct does have a superficial <code>FaceValue</code> property but that should not be confused with the value or points of a given card under the rules of a particular game. Consider the treatment of various cards for various games:</p> <ul> <li>In Poker, an Ace may be a 1 or a 14.</li> <li>In Blackjack, an Ace may be a 1 or 11.</li> <li>In Freecell, an Ace is a 1.</li> <li>In Hearts, an Ace has a value of 14, but the Ace of Hearts is equal to 1 point.</li> <li>In Crazy Eights, only the facevalue of the Ace matters.</li> </ul> <p>A <code>Deck</code> is not a Game. For this post, a Game is not defined. A <code>Deck</code> is oblivous to the notion that in some games one suit may trump another suit, or that a given rank may be of greater value or points that another rank. Those concerns would be handled by a given game object and its own set of rules and are (rightfully) ignored here.</p> <p>There are a couple of methods in <code>Deck</code> that I chose to be Fluent. One in particular is <code>Shuffle</code>, which began as a <code>void</code> but required 2 lines such as:</p> <pre><code>deck.Shuffle(); deck.WriteLines(); </code></pre> <p>With a Fluent design, I can do that in one line with:</p> <pre><code>deck.Shuffle().WriteLines(); </code></pre> <p><strong>Rank Structure</strong></p> <pre><code>public enum RankName : byte { Ace = 1, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Joker = byte.MaxValue } public struct Rank : IEquatable&lt;Rank&gt; { private Rank(RankName name, string symbol) { this.Name = name; this.Symbol = symbol; } public RankName Name { get; } public string Symbol { get; } // Do not confuse the FaceValue with a card's true Value or rank in a Game. // A Game object woud define its own rules and assign values accordingly. // Examples: // Poker - Ace's Value may be a 14 or a 1. // Blackjack - Ace's Value may be 10 or 11. // FreeCell - Ace's Value is a 1. // A deck of playing cards is oblivous to values assigned by a Game, // but a deck can know about the FaceValue of each card. public byte FaceValue =&gt; (byte)Name; public bool Equals(Rank other) =&gt; Name.Equals(other.Name); public override string ToString() =&gt; Symbol; public static Rank Ace =&gt; new Rank(RankName.Ace, &quot;A&quot;); public static Rank Two =&gt; new Rank(RankName.Two, &quot;2&quot;); public static Rank Three =&gt; new Rank(RankName.Three, &quot;3&quot;); public static Rank Four =&gt; new Rank(RankName.Four, &quot;4&quot;); public static Rank Five =&gt; new Rank(RankName.Five, &quot;5&quot;); public static Rank Six =&gt; new Rank(RankName.Six, &quot;6&quot;); public static Rank Seven =&gt; new Rank(RankName.Seven, &quot;7&quot;); public static Rank Eight =&gt; new Rank(RankName.Eight, &quot;8&quot;); public static Rank Nine =&gt; new Rank(RankName.Nine, &quot;9&quot;); public static Rank Ten =&gt; new Rank(RankName.Ten, &quot;10&quot;); // Alert: 2-character symbol public static Rank Jack =&gt; new Rank(RankName.Jack, &quot;J&quot;); public static Rank Queen =&gt; new Rank(RankName.Queen, &quot;Q&quot;); public static Rank King =&gt; new Rank(RankName.King, &quot;K&quot;); // Other possible Joker symbols: // &quot;WC&quot; for Wildcard // &quot;&lt;Ŵ&gt;&quot; which is a Wild way of using W for Wildcard public static Rank Joker =&gt; new Rank(RankName.Joker, &quot;¡J!&quot;); // VERY special symbol also &gt; 1 character public static IList&lt;Rank&gt; StandardRanks =&gt; new Rank[] { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King }; } </code></pre> <p><strong>Suit Structure</strong></p> <pre><code>public enum SuitColor : byte { None, Black, Red } public enum SuitName : byte { None, Clubs, Diamonds, Hearts, Spades } public struct Suit : IEquatable&lt;Suit&gt; { private Suit(SuitName name, string symbol, SuitColor color) { this.Name = name; this.Symbol = symbol; this.Color = color; } public SuitName Name { get; } public SuitColor Color { get; } public string Symbol { get; } public bool Equals(Suit other) =&gt; Name.Equals(other.Name); public override string ToString() =&gt; Symbol; public static Suit Clubs =&gt; new Suit(SuitName.Clubs, &quot;♣&quot;, SuitColor.Black); public static Suit Diamonds =&gt; new Suit(SuitName.Diamonds, &quot;♦&quot;, SuitColor.Red); public static Suit Hearts =&gt; new Suit(SuitName.Hearts, &quot;♥&quot;, SuitColor.Red); public static Suit Spades =&gt; new Suit(SuitName.Spades, &quot;♠&quot;, SuitColor.Black); public static Suit None =&gt; new Suit(SuitName.None, &quot;&quot;, SuitColor.None); public static IList&lt;Suit&gt; StandardSuits =&gt; new Suit[] { Hearts, Clubs, Diamonds, Spades }; public static IList&lt;Suit&gt; RedSuits =&gt; new Suit[] { Diamonds, Hearts }; public static IList&lt;Suit&gt; BlackSuits =&gt; new Suit[] { Clubs, Spades }; } </code></pre> <p><strong>Card Structure</strong></p> <pre><code>public struct Card : IEquatable&lt;Card&gt; { public Card(Rank rank, Suit suit) { this.Rank = rank; this.Suit = suit; } public Rank Rank { get; } public Suit Suit { get; } public bool Equals(Card other) =&gt; Rank.Equals(other.Rank) &amp;&amp; Suit.Equals(other.Suit); public override string ToString() =&gt; $&quot;{Rank}{Suit}&quot;; } </code></pre> <p><strong>Deck Class</strong></p> <pre><code>public class Deck { public Deck(IEnumerable&lt;Suit&gt; suits, IEnumerable&lt;Rank&gt; ranks, int numberOfDecks = 1, int numberOfJokers = 0) { Suits = suits.ToArray(); Ranks = ranks.ToArray(); DeckCount = numberOfDecks; JokerCount = numberOfJokers; _cards = new Card[(Suits.Count * Ranks.Count * numberOfDecks) + numberOfJokers]; ResetToNewDeck(); } private Card[] _cards { get; } public IReadOnlyList&lt;Card&gt; Cards =&gt; _cards; public IReadOnlyList&lt;Suit&gt; Suits { get; } public IReadOnlyList&lt;Rank&gt; Ranks { get; } public int DeckCount { get; } public int JokerCount { get; } private Random _random = new Random(); public static Deck CreateStandardDeck() =&gt; new Deck(Suit.StandardSuits, Rank.StandardRanks, numberOfDecks: 1, numberOfJokers: 0); public Deck ResetToNewDeck() { int i = 0; for (var d = 1; d &lt;= DeckCount; d++) foreach (var suit in Suits) foreach (var rank in Ranks) { _cards[i++] = new Card(rank, suit); } for (var j = 0; j &lt; JokerCount; j++) { _cards[i++] = new Card(Rank.Joker, Suit.None); } return this; // trying to be a little Fluent } public Deck Shuffle() { // Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle for (var i = 0; i &lt; _cards.Length - 1; i++) { var j = _random.Next(i, _cards.Length); if (i != j) { var temp = _cards[i]; _cards[i] = _cards[j]; _cards[j] = temp; } } return this; // trying to be a little Fluent } } </code></pre> <p><strong>A sample Console UI</strong></p> <p>I wanted a little razzle dazzle when displaying the cards, so I choose to colorize them with a white background and red or black text. I made an concession regarding the Joker to make it stand-out more and not be confused for a &quot;J&quot; or Jack.</p> <p><strong>ConsoleExtensions class</strong></p> <pre><code>// These methods do not extend the Console object, but rather use the Console as the primary UI. public static class ConsoleExtensions { // Tuple of ConsoleColor pair is for Foreground and Background respectively. private static IDictionary&lt;SuitColor, (ConsoleColor, ConsoleColor)&gt; ColorMap =&gt; new Dictionary&lt;SuitColor, (ConsoleColor, ConsoleColor)&gt;() { { SuitColor.Black, (ConsoleColor.Black, ConsoleColor.White) }, { SuitColor.Red, (ConsoleColor.DarkRed, ConsoleColor.White) }, { SuitColor.None, (ConsoleColor.White, ConsoleColor.DarkYellow) } }; private const string DefaultCardSeparator = &quot; &quot;; private const string DefaultLinePrefix = &quot; &quot;; public static void Write(this Card card) { var (foreColor, backColor) = ColorMap[card.Suit.Color]; Console.ForegroundColor = foreColor; Console.BackgroundColor = backColor; Console.Write(card); // Why ResetColor? For other methods that write many cards and use a separator // between each card. That separator should use the default Console colors // so that is cannot be visually mistaken as part of a card. Console.ResetColor(); } private static HashSet&lt;string&gt; NewLineSet =&gt; new HashSet&lt;string&gt;() { &quot;\n\r&quot;, &quot;\r\n&quot;, &quot;\n&quot; }; public static void WriteLine(this IEnumerable&lt;Card&gt; cards, string separator = DefaultCardSeparator, string linePrefix = DefaultLinePrefix) { separator ??= &quot;&quot;; linePrefix ??= &quot;&quot;; var isNewLine = NewLineSet.Contains(separator); var repeatPrefix = true; foreach (var card in cards) { if (repeatPrefix) { Console.Write(linePrefix); repeatPrefix = isNewLine; } card.Write(); Console.Write(separator); } if (!isNewLine) { Console.Write(Environment.NewLine); } } public static void WriteLine(this Deck deck, string separator = DefaultCardSeparator, string linePrefix = DefaultLinePrefix) =&gt; deck.Cards.WriteLine(separator, linePrefix); public static void WriteLines(this Deck deck, int maxPerRow = 0, string separator = DefaultCardSeparator, string linePrefix = DefaultLinePrefix) { if (maxPerRow &lt;= 0) { maxPerRow = deck.Ranks.Count; } var rows = (int)Math.Ceiling(deck.Cards.Count / (double)maxPerRow); for (var i = 0; i &lt; rows; i++) { deck.Cards.Skip(i * maxPerRow).Take(maxPerRow).WriteLine(separator, linePrefix); } } } </code></pre> <p><strong>The Main Program</strong></p> <pre><code>class Program { static void Main(string[] args) { var deck = Deck.CreateStandardDeck(); Console.WriteLine(&quot;Fresh new standard deck:&quot;); deck.WriteLines(); Console.WriteLine($&quot;{Environment.NewLine}Shuffled deck:&quot;); deck.Shuffle().WriteLines(); Console.WriteLine($&quot;{Environment.NewLine}New deck with 2 Jokers:&quot;); deck = new Deck(Suit.StandardSuits, Rank.StandardRanks, numberOfDecks: 1, numberOfJokers: 2); deck.WriteLines(); Console.WriteLine($&quot;{Environment.NewLine}Shuffled deck with 2 Jokers:&quot;); deck.Shuffle().WriteLines(); Console.WriteLine($&quot;{Environment.NewLine}Fresh deck with each card on it's own line.&quot;); // Example (1) deck.ResetToNewDeck().WriteLine(Environment.NewLine); // Example(2) //deck.ResetToNewDeck().WriteLines(maxPerRow: 1, separator: null); // To create a special deck of 2 suits and 10 ranks, use: Console.WriteLine($&quot;{Environment.NewLine}Special deck of 2 suits and 10 ranks&quot;); deck = new Deck(new[] { Suit.Spades, Suit.Hearts }, new[] { Rank.Ace, Rank.Two, Rank.Three, Rank.Four, Rank.Five, Rank.Six, Rank.Seven, Rank.Eight, Rank.Nine, Rank.Ten }); deck.WriteLines(); Console.WriteLine($&quot;{Environment.NewLine}Press ENTER to close.&quot;); Console.ReadLine(); } } </code></pre> <p><strong>Sample Output Images</strong></p> <p><a href="https://i.stack.imgur.com/6N59p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6N59p.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/3dKu0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3dKu0.png" alt="enter image description here" /></a></p> <p><strong>How to create a Casino Super Deck</strong></p> <pre><code>// Fun fact: most Blackjack games in Las Vegas use 6 to 8 decks! // https://en.wikipedia.org/wiki/Blackjack // To create one big deck composed of 6 standard decks, use: deck = new Deck(Suit.StandardSuits, Rank.StandardRanks, numberOfDecks: 6); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-10T09:28:59.520", "Id": "518918", "Score": "0", "body": "First of all congratulation, the implementation is pretty neat. I will leave a proper review today or tomorrow, but I just want to ask that are you aware of the [CA1067](https://docs.microsoft.com/en-gb/dotnet/fundamentals/code-analysis/quality-rules/ca1067) build warnings?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-10T13:37:36.333", "Id": "518930", "Score": "1", "body": "@PeterCsala I am not that familiar with CA1067 build warnings. Thus, I welcome your review because I want to learn about such things, and benefit from the varied experiences of fellow developers. I do not post to win points but rather to gain knowledge that makes me better in my job." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-10T21:00:22.617", "Id": "518953", "Score": "0", "body": "My [Blackjack example](https://codereview.stackexchange.com/questions/214390/my-blackjack-game-in-c-console/215625#215625) includes Deck, Suit, Card, and Shoe classes which you might want to check out." } ]
[ { "body": "<p>In this review I will focus only on the <code>Rank</code> type. I do this because I want to emphasize the importance of immutability.</p>\n<h3>Const vs Readonly vs Immutable</h3>\n<ul>\n<li>Constant: A mechanism to create an alias for a specific literal</li>\n<li>Readonly: A structure/mechanism to prevent modification after initialization</li>\n<li>Immutable: A structure/mechanism to support modification by creating a new copy</li>\n</ul>\n<p>So, as you can see a constant is readonly, but not immutable.</p>\n<p>I have seen some confusion around these terms that's why I wanted to clarify them. The <code>struct</code> data type has value semantics, which means that during assignment a copy will be created. Which might imply that the structs are immutable.</p>\n<p>The thing is you can write code that modifies the state of the struct. You can define properties with <em>setter</em>s and you can create methods which can overwrite <code>this</code> (<a href=\"http://www.devsanon.com/c/c-7-2-lets-talk-about-readonly-structs/\" rel=\"nofollow noreferrer\">Sample</a>). In order to enforce immutability at compilation time you can use <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct#readonly-struct\" rel=\"nofollow noreferrer\">readonly struct</a>s.</p>\n<p>That means we can only assign values inside the constructor. So you can't assign default value to the property. But with C# 9's <a href=\"https://www.thomasclaudiushuber.com/2020/08/25/c-9-0-init-only-properties/\" rel=\"nofollow noreferrer\">init-only</a> properties you can do that and extend this concept even further. So with the <code>init</code> keyword you can make property assignment from constructor, <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties\" rel=\"nofollow noreferrer\">property default value initializer</a> and object creation.</p>\n<p>(Please bear in mind that default value initializers are not allowed in <code>struct</code>s for instance level properties.)</p>\n<pre><code>public readonly struct Rank\n{\n public Rank(RankName name, string symbol)\n {\n Name = name;\n Symbol = symbol;\n }\n\n public RankName Name { get; init; }\n public string Symbol { get; init; }\n}\n\nvar r1 = new Rank(RankName.Ace, &quot;A&quot;);\nRank r2 = new (RankName.Ace, &quot;A&quot;);\nRank r3 = new() { Name = RankName.Ace, Symbol = &quot;A&quot; };\n</code></pre>\n<p>With <code>r3</code> as you can see we are using a parameterless default constructor. The thing is that this ctor is <a href=\"https://stackoverflow.com/questions/341957/how-do-i-enforce-using-a-factory-on-a-struct-in-c-sharp\">always present</a>. Which means that even though you have defined your parameterized ctor as <code>private</code> you can create a <code>Rank</code> instance anywhere. If you want to avoid this then you have to switch from <code>struct</code> to <code>class</code></p>\n<h3>Expression-bodied accessor vs Default value initializer</h3>\n<pre><code>public static Rank Ace =&gt; new(RankName.Ace, &quot;A&quot;);\npublic static Rank Ace { get; } = new(RankName.Ace, &quot;A&quot;);\n</code></pre>\n<ul>\n<li>In the former case you have defined a getter which will always return a <strong>new</strong> <code>Rank</code> instance.</li>\n<li>In the latter case you have defined a getter which will always return the <strong>same</strong> <code>Rank</code> instance.</li>\n</ul>\n<p>As I said before default value intializer can't be used for instance level properties inside struct. But this limitation is not applicable for <code>static</code> properties.</p>\n<h3>static getter only property vs static readonly field</h3>\n<p>If you want to separate <code>Rank</code> type definition from its predefined instances then it might make sense to create a static <code>Ranks</code> class where you define the well-known constants:</p>\n<pre><code>public static class Ranks\n{\n public static readonly Rank Ace = new(RankName.Ace, &quot;A&quot;);\n public static readonly Rank Two = new(RankName.Two, &quot;2&quot;);\n public static readonly Rank Three = new(RankName.Three, &quot;3&quot;);\n public static readonly Rank Four = new(RankName.Four, &quot;4&quot;);\n public static readonly Rank Five = new(RankName.Five, &quot;5&quot;);\n public static readonly Rank Six = new(RankName.Six, &quot;6&quot;);\n public static readonly Rank Seven = new(RankName.Seven, &quot;7&quot;);\n public static readonly Rank Eight = new(RankName.Eight, &quot;8&quot;);\n public static readonly Rank Nine = new(RankName.Nine, &quot;9&quot;);\n public static readonly Rank Ten = new(RankName.Ten, &quot;10&quot;);\n public static readonly Rank Jack = new(RankName.Jack, &quot;J&quot;);\n public static readonly Rank Queen = new(RankName.Queen, &quot;Q&quot;);\n public static readonly Rank King = new(RankName.King, &quot;K&quot;);\n public static readonly Rank Joker = new(RankName.Joker, &quot;¡J!&quot;);\n}\n</code></pre>\n<h3>Manually vs Programmatically listing members</h3>\n<p>With this class in our hand we can use reflection and <code>Lazy</code> to construct the <code>StandardRanks</code> in a programatic way. This would prevent such situation when you define a new <code>Rank</code> and forgot to add it to the <code>StandardRanks</code>. (I know, I know, this might seem a bit overkill, but there are situations where this technique is really useful.)</p>\n<pre><code>public static readonly ImmutableArray&lt;Rank&gt; StandardRanks = _ranks.Value;\n\nprivate static Lazy&lt;ImmutableArray&lt;Rank&gt;&gt; _ranks\n = new(() =&gt; GetAllRanks().Where(r =&gt; r.Name != RankName.Joker).ToImmutableArray(), true);\n\nprivate static IEnumerable&lt;Rank&gt; GetAllRanks()\n =&gt; typeof(Ranks)\n .GetFields(BindingFlags.Public | BindingFlags.Static)\n .Where(f =&gt; f.IsInitOnly &amp;&amp; f.FieldType == typeof(Rank))\n .Select(f =&gt; (Rank)f.GetValue(null));\n</code></pre>\n<h3>IList vs IReadOnlyCollection vs ImmutableArray</h3>\n<p>Here I've used <code>ImmutableArray</code> instead of <code>IList</code> or <code>IReadOnlyCollection</code>.</p>\n<p>In case of <code>IList</code> you can easily do this:</p>\n<pre><code>Ranks.StandardRanks.Remove(Ranks.Ace);\nRanks.StandardRanks.Add(Ranks.Joker);\n</code></pre>\n<p>Which is not good, because you don't want to allow mutation on this collection ifself.</p>\n<p>With <code>IReadOnlyCollection</code> you can prevent the removal or extension of the collection, but you can't prevent the modification of the items:</p>\n<pre><code>var ranks = (Rank[])Ranks.StandardRanks;\nranks[0] = Ranks.Joker;\n</code></pre>\n<p>You can always back cast it to the original data structure and modify its items.</p>\n<p>If you use <code>ImmutableArray</code> you still have <code>Add</code> and <code>Remove</code> methods but they will <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.immutable.immutablearray-1.add?view=net-5.0\" rel=\"nofollow noreferrer\">create a new ImmutableArray</a> rather than modifying the existing one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-14T11:18:38.000", "Id": "519158", "Score": "1", "body": "Thank you for the review. I mostly code with C# 7 and .NET Framework 4.6.2 due to a critical 3rd party library for work. It's nice to learn new things when I dabble with .NET 5 and C# 8." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T08:23:58.787", "Id": "262928", "ParentId": "261381", "Score": "1" } } ]
{ "AcceptedAnswerId": "262928", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T14:57:05.360", "Id": "261381", "Score": "3", "Tags": [ "c#", ".net", "playing-cards", ".net-5" ], "Title": "A versatile deck of playing cards. Standard 52-card deck and more" }
261381
<p>I have DaoFactory that returns DaoImpl and can make connection/transation scope</p> <pre><code>public class MySQLDAOFactory extends DAOFactory { private static final Logger LOGGER = LogManager.getLogger(MySQLDAOFactory.class); private static DataSource DATA_SOURCE; private static boolean isConnectionScope; private static boolean isTransaction; private static Connection connection; public static void createTransaction() throws SQLException { isTransaction = true; try { connection.setAutoCommit(false); } catch (SQLException throwables) { LOGGER.error(throwables); throw new SQLException(throwables.getMessage()); } } public static void endTransaction() throws SQLException { try { connection.commit(); } catch (SQLException throwables) { LOGGER.error(throwables); throw new SQLException(throwables.getMessage()); } } public static void abortTransaction() throws SQLException { try { connection.rollback(); } catch (SQLException throwables) { LOGGER.error(throwables); throw new SQLException(throwables.getMessage()); } } public static void createConnectionScope() throws SQLException { isConnectionScope = true; try { connection = DATA_SOURCE.getConnection(); } catch (SQLException e) { LOGGER.error(e); throw new SQLException(e.getMessage()); } } public static void endConnectionScope() throws SQLException { isConnectionScope = false; try { connection.close(); } catch (SQLException throwables) { LOGGER.error(throwables); throw new SQLException(throwables.getMessage()); } } public static boolean isIsConnectionScope() { return isConnectionScope; } public static void dataSourceInit(){ try { Context initContext = new InitialContext(); Context envContext = (Context) initContext.lookup(&quot;java:comp/env&quot;); DATA_SOURCE = (DataSource) envContext.lookup(&quot;jdbc/UsersDB&quot;); } catch (NamingException e) { LOGGER.error(e); } } public static Connection getConnection() { if(isConnectionScope&amp;&amp;connection!=null){ return connection; } try { connection = DATA_SOURCE.getConnection(); } catch (SQLException e) { LOGGER.error(e); } return connection; } @Override public CarDao getCarDao() { return new MySQLCarDao(); } @Override public UserDao getUserDao() { return new MySQLUserDao(); } @Override public OrderDao getOrderDao() { return new MySQLOrderDao(); } @Override public CarCategoryDao getCarCategoryDao() { return new MySQLCarCategoryDao(); } } </code></pre> <p>Let's take a look on some of DaoImpl</p> <pre><code>public class MySQLUserDao implements UserDao { private static final Logger LOGGER = LogManager.getLogger(MySQLOrderDao.class); private static final String USER_PASSWORD = &quot;userPassword&quot;; @Override public boolean insertUser(User user) { int rowNum = 0; String query = &quot;INSERT INTO user_info(login,userPassword,userType,userEmail)values(?,?,?,?);&quot;; Connection connection = null; PreparedStatement statement = null; ResultSet keys = null; try { connection = MySQLDAOFactory.getConnection(); statement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); statement.setString(1, user.getLogin()); statement.setString(2, PasswordUtil.generateStrongPasswordHash(user.getPassword())); statement.setString(3, user.getUserType()); statement.setString(4, user.getUserEmail()); rowNum = statement.executeUpdate(); keys = statement.getGeneratedKeys(); if (keys.next()) { user.setUserId(keys.getInt(1)); } } catch (SQLException e) { LOGGER.error(e); } finally { if (keys != null) { try { keys.close(); } catch (SQLException e) { LOGGER.error(e); } } if (!MySQLDAOFactory.isIsConnectionScope()) { try { if (connection != null) { connection.close(); } if (statement != null) { statement.close(); } } catch (SQLException e) { LOGGER.error(e); } } } return rowNum &gt; 0; } @Override public boolean deleteUser(String login) { String query = &quot;DELETE FROM user_info WHERE login = ?;&quot;; int rowNum = 0; Connection connection = null; PreparedStatement statement = null; try { connection = MySQLDAOFactory.getConnection(); statement = connection.prepareStatement(query); statement.setString(1, login); rowNum = statement.executeUpdate(); } catch (SQLException e) { LOGGER.error(e); } finally { if (!MySQLDAOFactory.isIsConnectionScope()) { try { if (connection != null) { connection.close(); } if (statement != null) { statement.close(); } } catch (SQLException e) { LOGGER.error(e); } } } return rowNum &gt; 0; } </code></pre> <p>I have more methods but I think this will be enough. So I rightly implement connecton scope?If not could you say what better to do?Thanks for reply.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T15:58:48.313", "Id": "515807", "Score": "0", "body": "Did you yes this? Does it work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T16:05:49.103", "Id": "515808", "Score": "0", "body": "@Mast, Yes i did it , and it has worked well, Thanks a lot. how can i improve this implementation ?And how will this code work in multithreading environment?Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T12:12:57.543", "Id": "516075", "Score": "0", "body": "What do you mean by \"connection scope\" ? Is there any specific points that you want us to review ?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T15:26:37.520", "Id": "261383", "Score": "0", "Tags": [ "java", "database", "jdbc", "connection-pool", "transactions" ], "Title": "Is my implementation of connection scope for Dao right?I have Dao and Service where I implement connection and transaction scope" }
261383
<p>Here is my code that I recently made (I am a beginner). I used BeautifulSoup and Requests to get the data of <a href="https://www.scarymommy.com/best-trivia-questions-answers" rel="nofollow noreferrer">this website</a>. Please read over my code and tell me how to improve it. Thanks.</p> <pre><code>import random import time from os import system import keyring from bs4 import BeautifulSoup import requests def getdata(url): headers = { 'User-agent': &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582&quot;} r = requests.get(url, headers=headers) return r.text def main(): print('This is trivia, made by MY_NAME. Have fun!') print() while True: try: amount = int(input('How many questions would you like to answer? ')) print() except ValueError: print() print('Must be a natural number.') print() else: if amount &lt; 10 or amount &gt; 145: print('Must be a natural number above 10 and less than 145.') print() else: break htmldata = getdata('https://www.scarymommy.com/best-trivia-questions-answers/') soup = BeautifulSoup(htmldata, 'html.parser') q = str(soup.find_all(text=True)) questions = [] answers = [] for x in range(1, amount + 1): question_index = q.find(f'{x}. ') next_index = q.find(f'{x+1}. ') to_add = q[question_index:next_index] to_add = to_add.replace(&quot;', '&quot;, '') to_add = to_add.replace('\n', '') questions.append(to_add[0:-1]) for x in range(amount): unsplit = questions[x] split = unsplit.split(' Answer: ') que = split[0] que = que.replace(f'{x+1}. ', '') ans = split[1] ans = ans.replace('.\\', '') ans = ans.replace('\\n', '') ans = ans.replace('\\', '') answers.append(ans) questions[x] = que music = &quot;/Users/XIA/Desktop/Python/Projects/Trivia/Music/intro_music.wav&quot; system(&quot;afplay &quot; + music) hisc_nme = keyring.get_password('trivia', 'hi') hisc_sce = keyring.get_password('trivia', 'sc') print() print('You will answer {} questions within 15 seconds, and the faster you answer, the more point\'s you\'ll get.'.format(len(questions))) print('Right now, {} has the high score of {}.'.format(hisc_nme, hisc_sce)) print('Good luck, and have fun!') print() time.sleep(1) while True: cor_count = 0 score = 0 count = 0 choices = list(range(len(questions))) for x in range(0, len(questions)): quest = random.choice(choices) choices.remove(quest) start = time.time() answer = input(questions[quest] + ' ').lower() end = time.time() Canswer = answers[quest] pCanswer = Canswer Canswer = Canswer.lower() time_took = end - start if answer != Canswer.strip(): print('Wrong!') count += 1 print('Your current score is {}.'.format(score)) print('The correct answer was {}.'.format(pCanswer)) print() time.sleep(1) else: print('Correct!') cor_count += 1 count += 1 print('You took {} seconds.'.format(round(time_took))) score += 1 + round((15/(time_took))) print('Your current score is {}.'.format(score)) print() time.sleep(1) print('You got {} out of {} right. Your final score is {}.'.format(cor_count, count, score)) if int(score) &gt; int(hisc_sce): print('New high score!') new_name = input('Enter your name to be saved as the high score: ') keyring.set_password('trivia', 'hi', new_name) keyring.set_password('trivia', 'sc', str(score)) again = input('Play again (y/n): ') if again.lower() != 'y': print('Goodbye!') system('say -v Victoria Please do not be salty and rage quit.') break if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>Broadly: this isn't a particularly useful application of scraping. You're scraping static content. You'd be better off literally copying and pasting that content into a local, hand-generated JSON file distributed with your game (while also including copyright attribution to the original source).</p>\n<p>Do that, split up your mega-<code>main</code> into several different functions, and you'll be well on your way to sanity.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T00:26:52.147", "Id": "261398", "ParentId": "261387", "Score": "1" } } ]
{ "AcceptedAnswerId": "261398", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T17:33:14.627", "Id": "261387", "Score": "2", "Tags": [ "beginner", "python-3.x", "game" ], "Title": "Python trivia game getting questions and answers off a website" }
261387
<p>I'm still in the process of learning Java / spring and I think I'm getting better. Now at this point I'm able to build a rest api BUT I'm at a lost at how to ensure I've no concurrency issues . I've read quite a bit of documentation on having my classes stateless and I &quot;think&quot; I've achieved that.</p> <p>Could I get a code review please to see if anything here would be an issue should there be say xxx concurrent requests to the controller below.</p> <p>Below i have a POJO called User:</p> <pre><code>@Getter @Setter @Document(collection = &quot;UserProfiles&quot;) public class User { @Id @JsonIgnore private String _id; @JsonView({ProfileViews.Intro.class, ProfileViews.Full.class}) private String userId; @JsonView({ProfileViews.Intro.class, ProfileViews.Full.class}) private String name; @JsonView({ProfileViews.Intro.class, ProfileViews.Full.class}) private String displayName; @DBRef @JsonView({ProfileViews.Full.class}) private UserInterests personalInterests; @DBRef @JsonIgnore private ProfileFollows profileFollowDetails; } </code></pre> <pre><code>@Getter @Setter @Document(collection = &quot;ProfileFollows&quot;) public class ProfileFollows { @Id //Id of The Mongo Document private String id; //The Id of the User Profile who owns the document private String userId; //A list containing the Ids of the Users who have followed the Profile belonging to userId private List&lt;String&gt; profileFollowedByUserIds; //A list containing the Ids of the Profiles the current user has followed private List&lt;String&gt; profileFollowingByUserList; } </code></pre> <p>And here is my Service layer where I create and update the user</p> <pre><code>@Service public class UserService { @Autowired UserDal userDal; public User createNewUserAccount(String userId, String userName) { //check If userId already in DB if (checkIfUserIdExits(userId)) { throw new UserAlreadyExistsException(&quot;Cannot create User with Id { &quot; + userId + &quot; }, a user with this Id already &quot; + &quot;exists&quot;); } //Create a Empty / Base New User Object User newUser = new User(); UserInterests userInterests = new UserInterests(); userInterests.setUserId(userId); userInterests.setPersonalInterestsExtras(null); userInterests.setCreatedDate(Instant.now()); userInterests.setLastUpdatedAt(Instant.now()); userInterestsDAL.save(userInterests); newUser.setPersonalInterests(userInterests); ProfileFollows userProfileFollows = new ProfileFollows(); userProfileFollows.setUserId(userId); userProfileFollows.setProfileFollowedByUserIds(new ArrayList&lt;&gt;()); userProfileFollows.setProfileFollowingByUserList(new ArrayList&lt;&gt;()); newUser.setProfileFollowDetails(profileFollowsDAL.save(userProfileFollows)); newUser.setUserId(userId); newUser.setDisplayName(generateUserDisplayName(userName)); newUser.setCreatedDate(Instant.now()); newUser.setLastUpdatedAt(Instant.now()); //save the new User Profile to the DB return userDal.save(newUser); } </code></pre> <p>Here is my UserDAL:</p> <pre><code>public interface UserDal { /** * Method to check if a user exists with a given user Id * @param Id -- Id of user to look up where id is a string * @return */ Boolean existsById(String Id); /** * Method to save a user to the DB * @param user -- User object to save to the DB * @return */ User save(User user); } </code></pre> <p>My User Repository / DALImpl:</p> <pre><code>@Repository public class UserDALImpl implements UserDal { private final MongoTemplate mongoTemplate; @Autowired public UserDALImpl(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } @Override public User save(User user) { return mongoTemplate.save(user); } </code></pre> <p>And lastly my controller:</p> <pre><code>@RestController @RequestMapping(&quot;/profile&quot;) public class CreateProfileController { @Autowired public CreateProfileController() { } @Autowired UserService userService; @ApiOperation(value = &quot;Allows for the creation of a user Profile&quot;) @PostMapping(&quot;/create&quot;) public User createUserProfile(@RequestParam(name = &quot;userId&quot;) String userId, @RequestParam(name = &quot;displayName&quot;, required = true, defaultValue = &quot;AnonymousDev&quot;) String displayName) { if (userId.equals(&quot;&quot;)) throw new BadRequestException(&quot;UserId cannot be blank&quot;); if (userService.checkIfUserIdExits(userId)) { throw new UserAlreadyExistsException(&quot;Unable to create user with Id { &quot; + userId + &quot; }, the &quot; + &quot;userId already exists&quot;); } return userService.createNewUserAccount(userId, displayName); } } </code></pre> <p>Thank you for your time</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T18:47:06.463", "Id": "515832", "Score": "1", "body": "Is the code currently working as expected? That is one of the requirements for asking a question on the Code Review Community. Please read [How do I ask a good question?(https://codereview.stackexchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T19:13:47.207", "Id": "515837", "Score": "0", "body": "Ah sorry I should have read the guide. But to answer your question it \"seems\" to be working as expected. However i'm slightly junior here so I'm not sure if there's something that will bite me from a thread safety POV" } ]
[ { "body": "<p>Welcome to Code Review, because Spring demands to the user the responsibility of avoiding concurrency issues better always check if the possibility of concurrent issues exists. About your <code>CreateProfileController</code> controller:</p>\n<pre><code>public class CreateProfileController {\n\n @Autowired\n public CreateProfileController() {\n }\n\n @Autowired\n UserService userService;\n}\n</code></pre>\n<p>The possibility of concurrency issues is related to the field <code>userService</code> but it is directly handled by Spring with the use of the <code>@Autowired</code> annotation so the possibility of accidentally mutating it in someway is excluded (it is a singleton with no setter methods). There's no possibility of storing data between successive requests like in an http session because the controller is also handled by Spring and you haven't defined the <code>session</code> scope of the controller. I haven't checked it but I think you could rewrite your controller bounding the <code>@Autowired</code> annotation to the constructor like below:</p>\n<pre><code>public class CreateProfileController {\n\n @Autowired\n public CreateProfileController(UserService userService) {\n this.userService = userService;\n }\n\n private UserService userService;\n}\n\n</code></pre>\n<p>About the other classes, I find a little strange you haven't used the <code>@GeneratedValue</code> annotation with the present <code>@Id</code> annotation. Without combining them a generic api user has to manually assign the id in the request like your code below:</p>\n<pre><code>@PostMapping(&quot;/create&quot;)\n public User createUserProfile(@RequestParam(name = &quot;userId&quot;) String userId,...)\n \n</code></pre>\n<p>So the user knows informations about his internal database id and for me this is bad, unless you are thinking that <code>userId</code> is like an email address with a one to one relationship with the profile; in this case I think there are should be no issues but I'm not sure about it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T15:44:42.950", "Id": "515892", "Score": "0", "body": "Wow thank you for your answer. This is my first time using stack codereview and I'm amazed by the detailed answer so thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T15:45:45.427", "Id": "515893", "Score": "0", "body": "Ok so I think i'm ok and i'll take your advice with the @Autowired. Also you make a very good point in general about the userId in the POST request. This endpoint is only called from Auth0 and has a scope permission on it (sorry i shouldn't have left that out). Once again thank you for taking the time!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T15:47:33.467", "Id": "515895", "Score": "0", "body": "Actually one question if i may. In the above code, is one way I could generate a concurrency issue (just for my learning) by declaring a class level variable (imagine Integer count) and having THAT accessed / mutated by methods in the Service class" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T15:57:48.923", "Id": "515897", "Score": "1", "body": "@Philban You are welcome and your example of an `int count` hits the point of a pretty sure concurrency issue, for example if your service read the `count` value to obtain a new record id an api user would risk to have his request refused because an already present record with the same id in your database." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T14:01:11.680", "Id": "520034", "Score": "0", "body": "Sorry for the delayed response, I've been off on leave plus I killed my laptop (yay) excellent thanks for your response again" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T16:51:19.293", "Id": "520048", "Score": "0", "body": "@Philban No problem and welcome back to Code Review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T18:06:54.287", "Id": "520053", "Score": "0", "body": "haha thanks :-) It's good to be back.....and good to back asking questions :D hope you're keeping well and safe dude!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T10:38:21.477", "Id": "261418", "ParentId": "261389", "Score": "4" } }, { "body": "<p>A few additional areas to consider, not directly related to you concurrency question...</p>\n<h2>UserAlreadyExistsException</h2>\n<p>This takes an argument that appears to be an error message. The message that's being passed in feels very much like it's essentially the name of the exception, along with the userId that already existed. If you own this exception, consider changing it so that the <code>userId</code> is passed into the constructor instead and the exception itself is responsible for constructing the error message (if it's necessary). This would simplify each of the callers...</p>\n<h2>Duplication</h2>\n<p>Both your Service and Controller perform validation on the UserId to see if it exists:</p>\n<pre><code>if (userService.checkIfUserIdExits(userId)) {\n throw new UserAlreadyExistsException(&quot;Unable to create user with Id { &quot; + userId + &quot; }, the &quot; +\n &quot;userId already exists&quot;);\n}\n</code></pre>\n<p>The error message reported is very slightly different between each of the calls, however I'd consider if you really need to check it in both places. It seems like the Controller could probably trust the service to perform the exist validation if it's required. Think about what it is each of the classes is responsible for. To me, the Controller class is responsible for orchestrating the API, it doesn't actually do any work, it passes requests to the right destination and responses back to the client.</p>\n<p>I'd also consider if it actually makes sense for <code>checkIfUserIdExits</code> to return a flag. Do you have any code that calls this method and doesn't throw if the user exists? If not then it might be better for the check method to throw directly.</p>\n<h2>Typo</h2>\n<p><code>checkIfUserIdExits</code> should probably be <code>checkIfUserIdExists</code>...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T14:44:56.587", "Id": "262681", "ParentId": "261389", "Score": "1" } } ]
{ "AcceptedAnswerId": "261418", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T17:46:46.840", "Id": "261389", "Score": "4", "Tags": [ "java", "multithreading", "spring", "mongodb" ], "Title": "Spring Boot API - Avoiding Concurrency issues" }
261389
<p>This class acts as an asynchronous event handler that will execute all attached tasks in an async/await context. Requires Nuget <code>Immutables</code>. Example usage:</p> <pre><code>class MyEventArgs : EventArgs {} async Task SomeAsyncMethodAobject src, EventArgs args) { Console.WriteLine(&quot;Task A...&quot;); await Task.Delay(2000); } async Task SomeAsyncMethodB(object src, EventArgs args) { Console.WriteLine(&quot;Task B...&quot;); await Task.Delay(1000); } static async Task Main(string[] args) { AsyncEvent&lt;MyEventArgs&gt; Events; Events = new AsyncEvent&lt;MyEventArgs&gt;(); Events += SomeAsyncMethodA; Events += SomeAsyncMethodB; await Events?.InvokeAsync(this, new MyEventArgs()); // Use below to discard task and not await event task to finish. // _ = Events?.InvokeAsync(this, new MyEventArgs()).ConfigureAwait(false); } </code></pre> <p>Source for the <code>AsyncEvent&lt;EventArgsT&gt;</code> class:</p> <pre><code>// T is the EventArgs class type to pass to the callbacks on Invoke. public class AsyncEvent&lt;T&gt; where T : EventArgs { // List of task methods to await. public ImmutableList&lt;Func&lt;object, T, Task&gt;&gt; Invokables; // on += add new callback method to AsyncEvent. public static AsyncEvent&lt;T&gt; operator+(AsyncEvent&lt;T&gt; source, Func&lt;object, T, Task&gt; callback) { if (callback == null) throw new NullReferenceException(&quot;Callback is null! &lt;AsyncEvent&lt;T&gt;&gt;&quot;); if (source == null) return null; if (source.Invokables == null) source.Invokables = ImmutableList&lt;Func&lt;object, T, Task&gt;&gt;.Empty; source.Invokables = source.Invokables.Add(callback); return source; } // on -= remove existing callback from AsyncEvent. public static AsyncEvent&lt;T&gt; operator -(AsyncEvent&lt;T&gt; source, Func&lt;object, T, Task&gt; callback) { if (callback == null) throw new NullReferenceException(&quot;Callback is null! &lt;AsyncEvent&lt;T&gt;&gt;&quot;); if (source == null) return null; source.Invokables = source.Invokables.Remove(callback); return source; } // Invoke the tasks asynchronously with a cancelation token. public async Task InvokeAsync(object source, T evArgs, CancellationToken token) { List&lt;Task&gt; tasks = new List&lt;Task&gt;(); if (Invokables != null) foreach (var callback in Invokables) if (!token.IsCancellationRequested) tasks.Add(callback(source, evArgs)); await Task.WhenAll(tasks.ToArray()); } // Invoke the tasks asynchronously. public async Task InvokeAsync(object source, T evArgs) { List&lt;Task&gt; tasks = new List&lt;Task&gt;(); if (Invokables != null) foreach (var callback in Invokables) tasks.Add(callback(source, evArgs)); await Task.WhenAll(tasks.ToArray()); } } </code></pre> <p>Is there anything wrong with this asynchronous paradigm?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T00:00:05.350", "Id": "515914", "Score": "0", "body": "What's the purpose of the solution? Is it only for waiting when all the callbacks are completed? If so, here's [some read](https://blog.stephencleary.com/2013/02/async-oop-5-events.html)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T01:04:56.730", "Id": "515916", "Score": "0", "body": "@aepot in my particular situation I am using this to run events asynchronously for my async/await TCP server. Primary usefulness is that I can send data packets to events and let the events run async and continue reading data on client sockets without waiting for the events to finish from the previous data received from the client." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T01:06:24.400", "Id": "515917", "Score": "0", "body": "@aepot the generic use here is that you can execute a bunch of different methods with similar contexts asynchronously to boost performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T06:13:55.300", "Id": "515928", "Score": "0", "body": "Looks like you added async overhead to Server Core with no reason. OK, how many different really asynchronous subscribers to the `AsyncEvent` do you have? What jobs are they doing on the event was fired? What data is passed by Args? How often the event is fired, ~times/sec, peak/avg? Why I'm asking: It looks like you've solved some problem in a wrong way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T19:09:06.653", "Id": "515997", "Score": "0", "body": "@aepot standard server design uses the async/await pattern with cancelation tokens. Its not overhead. The `AsyncEvent` isn't firing too often nor doing any sort of long sustained tasks." } ]
[ { "body": "<p>Not a review but an alternative solution to leave here. Just because the above one is overkill, as for me.</p>\n<p>Probably you want to implement Publisher/Subscriber pattern in awaitable/Command mode. But it's possible using delegate itself.</p>\n<p>Consider the extension method</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static class DelegateExtensions\n{\n public static Task InvokeAsync&lt;TArgs&gt;(this Func&lt;object, TArgs, Task&gt; func, object sender, TArgs e)\n {\n return func == null ? Task.CompletedTask\n : Task.WhenAll(func.GetInvocationList().Cast&lt;Func&lt;object, TArgs, Task&gt;&gt;().Select(f =&gt; f(sender, e)));\n }\n}\n</code></pre>\n<p>And the test</p>\n<pre class=\"lang-cs prettyprint-override\"><code>class Program\n{\n public static event Func&lt;object, EventArgs, Task&gt; MyAsyncEvent;\n\n static async Task SomeAsyncMethodA(object src, EventArgs args)\n {\n Console.WriteLine(&quot;Task A...&quot;);\n await Task.Delay(2000);\n Console.WriteLine(&quot;Task A finished&quot;);\n }\n\n static async Task SomeAsyncMethodB(object src, EventArgs args)\n {\n Console.WriteLine(&quot;Task B...&quot;);\n await Task.Delay(1000);\n Console.WriteLine(&quot;Task B finished&quot;);\n }\n\n static async Task Main(string[] args)\n {\n MyAsyncEvent += SomeAsyncMethodA;\n MyAsyncEvent += SomeAsyncMethodB;\n\n await MyAsyncEvent.InvokeAsync(null, EventArgs.Empty);\n\n Console.WriteLine(&quot;Invoked&quot;);\n Console.ReadKey();\n }\n}\n</code></pre>\n<p>Output</p>\n<pre class=\"lang-none prettyprint-override\"><code>Task A...\nTask B...\nTask B finished\nTask A finished\nInvoked\n</code></pre>\n<p>Looks like it works.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T00:19:29.313", "Id": "516031", "Score": "0", "body": "I like the solution. One problem though is that `Delegate[]` does not contain a definition for `*.Cast`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T05:58:46.180", "Id": "516049", "Score": "1", "body": "@FatalSleep add `using System.Linq;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T06:16:08.347", "Id": "516113", "Score": "0", "body": "thank you. Also how did you find `DelegateExtensions`? I've search the internet and cannot find any info on it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T06:30:04.090", "Id": "516115", "Score": "0", "body": "@FatalSleep the class with extensions must be `public` and `static`. The name can be any." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T06:34:08.507", "Id": "516116", "Score": "0", "body": "Right, but how do I and the compiler know that this is an extension method particularly for delegates? That's what's confusing me most." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T07:29:05.457", "Id": "516117", "Score": "0", "body": "@FatalSleep `this Func<object, TArgs, Task> func` <--- this type marked as `this`. That's not for delegates but only for this type." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T20:40:19.450", "Id": "261483", "ParentId": "261396", "Score": "1" } } ]
{ "AcceptedAnswerId": "261483", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T00:08:33.547", "Id": "261396", "Score": "0", "Tags": [ "c#", "async-await" ], "Title": "Asynchronous Event Handler" }
261396
<p>I wrote a short bash script for a completion check of downloading images.</p> <p><strong>goal of this code (Added)</strong></p> <p>I have some downloading content directories. Each of them has a script for downloading images(<code>tmp.sh</code>), for example, the following one:</p> <pre class="lang-sh prettyprint-override"><code>wget -nc ¥ http://www.example.com/001.jpg ¥ http://www.example.com/002.jpg ¥ ... http://www.example.com/123.jpg ¥ </code></pre> <p>I want to know which wget completes downloading all or failed.</p> <p>If you have any good ideas, please tell me them. Thank you.</p> <p><strong>done.sh</strong></p> <pre class="lang-sh prettyprint-override"><code>#!/bin/sh # if a directory name is assigned if [ $# -eq 1 ]; then a=`ls -1 $1/*.jpg | wc -l` b=`grep jpg $1/tmp.sh | wc -l` if [ $a = $b ]; then echo $1 fi exit fi # if some directory names are assigned if [ $# -gt 1 ]; then for dir1 in &quot;$@&quot;; do ./done.sh $dir1 done fi # if directory names are not assigned if [ $# -eq 0 ]; then ls -d */ | xargs ./done.sh fi <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h1>Good</h1>\n<ul>\n<li>good indentation</li>\n<li>somewhat helpful comments</li>\n<li>good to do the <code>; then</code> bit on the same line as the <code>if</code></li>\n</ul>\n<h1>Suggestions</h1>\n<ul>\n<li>use double brackets for conditionals</li>\n<li>try shellcheck (It will tell you to put quotes around your variable substitutions.)</li>\n<li>put your arguments into named variables so you don't keep have to referring to <code>$1</code></li>\n<li>put the 3 sections into <code>if</code>...<code>elif</code>...<code>else</code> structure to make clear that you're only going to go into one of them</li>\n<li>check for the existance of <code>./done.sh</code> at the beginning</li>\n<li>explain what the goal of the script is somewhere.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T04:04:02.190", "Id": "515853", "Score": "0", "body": "Thanks for the great suggestions. I forgot the programming fundamental techniques in shell programming. I'll correct my code and paste it below the original code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T04:10:03.753", "Id": "515854", "Score": "0", "body": "@HaruoWakakusa You may want to read [What I can and cannot do after receiving answers](https://codereview.meta.stackexchange.com/a/1765/71574) before you do that. As it is one of the things that you can't do under this site's rules." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T04:20:46.030", "Id": "515855", "Score": "1", "body": "Yes, I'll add only the purpose of this code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T03:04:08.517", "Id": "261401", "ParentId": "261399", "Score": "1" } } ]
{ "AcceptedAnswerId": "261401", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T00:33:10.950", "Id": "261399", "Score": "1", "Tags": [ "bash", "sh" ], "Title": "Testable and self-contained bash script" }
261399
<p>So I've been trying to implement a Token class in C++. At first I wanted to use a simple <code>enum class</code> to store the <code>Kind</code> of the Token.</p> <p>But then I came across a problem. Some Tokens (such as keywords, identifiers, numeric literals, etc.) would need to store an external value along with their <code>Kind</code>, while others wouldn't. I tried to get around the problem by creating a struct for each Token Kind and then using an <code>std::variant</code> for the <code>Kind</code> type. Here's the code I ended up with:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;cstdint&gt; #include &lt;string&gt; #include &lt;variant&gt; class Token { public: struct Num { std::int64_t val; }; struct Float { double val; }; struct String { std::string val; }; struct Keyword { std::string val; }; struct Identity { std::string val; }; struct LParen { }; struct RParen { }; struct LBrace { }; struct RBrace { }; struct LBracket { }; struct RBracket { }; struct Semicolon { }; struct Colon { }; struct Dot { }; struct Operator { enum class Name : std::uint_fast8_t { Add = 0, Sub, Mult, Div, Pow }; Name val; }; struct EndOfFile { }; struct Invalid { }; using Kind = std::variant&lt;Num, Float, String, Keyword, Identity, LParen, RParen, LBrace, RBrace, LBracket, RBracket, Semicolon, Colon, Dot, Operator, EndOfFile, Invalid&gt;; struct Span { std::uint_fast64_t row; std::uint_fast64_t col; }; Token() = delete; Token(Kind const&amp; kind, Span span) : m_kind(kind), m_span(span) {} auto kind() const -&gt; Kind { return m_kind; } auto span() const -&gt; Span { return m_span; } auto isEOF() const -&gt; bool { return std::holds_alternative&lt;EndOfFile&gt;(m_kind); } auto isValid() const -&gt; bool { return !std::holds_alternative&lt;Invalid&gt;(m_kind); } private: Kind m_kind; Span m_span; }; </code></pre> <p>Is this a valid way to do what I originally intended to do? Or is it way too complicated and there's a simpler way?</p>
[]
[ { "body": "<p>Seems great to me — a nice way to simulate algebraic data types in C++.</p>\n<p>The only improvement I can think of:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct Operator\n{\n enum class Name : std::uint_fast8_t\n {\n Add = 0,\n Sub,\n Mult,\n Div,\n Pow\n };\n\n Name val;\n};\n</code></pre>\n<p>Why not make <code>Operator</code> itself an <code>enum class</code>?</p>\n<p>I might consider changing</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>Token(Kind const&amp; kind, Span span) : m_kind(kind), m_span(span) {}\n</code></pre>\n<p>to</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template &lt;typename T&gt;\nToken(T&amp;&amp; kind, Span span)\n : m_kind(std::forward&lt;T&gt;(kind)) // #include &lt;utility&gt;\n , m_span(span)\n{\n}\n</code></pre>\n<p>to avoid the overhead of constructing an extra <code>variant</code>.</p>\n<hr />\n<p>The OP mentioned grouping the symbols together into an <code>enum class</code> in the comments. Whether this is beneficial depends on how the symbols will be used. It is easier to handle all the symbols together:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum class Symbol {\n LParen, RParen, LBrace, RBrace, LBracket, RBracket, Semicolon, Colon, Dot,\n};\n\n// ...\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, Symbol symbol) {\n static const std::unordered_map&lt;Symbol, char&gt; table {\n { Symbol::LParen, '(' },\n { Symbol::RParen, ')' },\n // etc.\n };\n\n return os &lt;&lt; table.at(symbol);\n}\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Token&amp; token) {\n std::visit(Overloaded {\n // ...\n [&amp;](Symbol symbol) { os &lt;&lt; symbol; }, // uniform handling\n // ...\n }, token.kind);\n // ...\n}\n</code></pre>\n<p>versus</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct LParen {};\nstruct RParen {};\nstruct LBrace {};\nstruct RBrace {};\n// etc.\n\n// ...\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Token&amp; token) {\n std::visit(Overloaded {\n // ...\n [&amp;](LParen) { os &lt;&lt; '('; },\n [&amp;](RParen) { os &lt;&lt; ')'; },\n [&amp;](LBrace) { os &lt;&lt; '{'; },\n [&amp;](RBRace) { os &lt;&lt; '}'; }, // manual handling\n // ...\n }, token.kind);\n // ...\n}\n</code></pre>\n<p>But it is harder to check if a token is a given symbol:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum class Symbol {\n LParen, RParen, LBrace, RBrace, LBracket, RBracket, Semicolon, Colon, Dot,\n};\n\n// ...\n\nbool is_symbol(const Token&amp; token, Symbol symbol) {\n if (auto p = std::get_if&lt;Symbol&gt;(token)) {\n return *p == symbol;\n } else {\n return false;\n }\n}\n</code></pre>\n<p>versus simply a call to <code>std::holds_alternative</code>.</p>\n<p>The same applies to the operators.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T04:22:50.087", "Id": "515856", "Score": "0", "body": "Ah yeah, changing operator itself to an enum class is something I should do. Also, I don't quite get what you did with the constructor. I don't even know if it's possible to make a template constructor for a non-template class" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T04:25:55.540", "Id": "515857", "Score": "0", "body": "@Famiu It is indeed possible - I edited the answer to clarify. The difference here is that the argument is directly forwarded to the constructor of `std::variant`, whereas in your version, a temporary `std::variant` is constructed and then copied to `m_kind`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T04:28:24.553", "Id": "515858", "Score": "0", "body": "I see, thanks a lot for that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T04:29:26.077", "Id": "515859", "Score": "0", "body": "Do you think I should group all symbols together inside a symbols enum, or is it fine how it is?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T04:33:09.123", "Id": "515860", "Score": "0", "body": "@Famiu Ultimately, it depends on the usage pattern. Grouping them together is beneficial when the code handles all symbols in a uniform manner, but it would be slightly more work (a helper function, that is) to check if a token is a specific symbol (`get_if` + `==`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T04:36:12.143", "Id": "515861", "Score": "0", "body": "Does the same apply for the operators, then? Should I flatten them out as well or keep them as an enum?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T04:55:25.767", "Id": "515862", "Score": "0", "body": "@Famiu Yes - both have their advantages and drawbacks. I'll edit my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T05:16:22.023", "Id": "515864", "Score": "0", "body": "Thanks for taking the time to write all that. I'm going to accept your answer" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T04:16:32.653", "Id": "261404", "ParentId": "261403", "Score": "4" } } ]
{ "AcceptedAnswerId": "261404", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T04:02:27.287", "Id": "261403", "Score": "4", "Tags": [ "c++", "c++17", "variant-type", "lexer" ], "Title": "Token class implementation with std::variant" }
261403
<p>My very first computer program, a very simple income tax calculator. What can I do to get the same outcome with better efficiency?</p> <pre><code># 2021 income tax calculator print ('What\'s your yearly income after you deduct all expenses?') myincome = int(input()) base = (myincome*.1) e = (max(myincome-9950,0)*.02) ex = (max(myincome-40525,0)*.1) ext = (max(myincome-86376,0)*.02) extr = (max(myincome-164926,0)*.08) extra = (max(myincome-209426,0)*.03) extras = (max(myincome-523601,0)*.02) tax = base + e + ex + ext + extr + extra + extras print ('You\'re gonna get screwed about~$',str(tax) + ' dollars in Federal income tax') print () while True: print ('Try Different Income:') myincome = int(input()) base = (myincome*.1) e = (max(myincome-9950,0)*.02) ex = (max(myincome-40525,0)*.1) ext = (max(myincome-86376,0)*.02) extr = (max(myincome-164926,0)*.08) extra = (max(myincome-209426,0)*.03) extras = (max(myincome-523601,0)*.02) tax = base + e + ex + ext + extr + extra + extras print ('You\'re gonna get screwed about~$',str(tax) + ' dollars in Federal income tax') print () continue </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T08:24:17.273", "Id": "515867", "Score": "1", "body": "Hi @JJZ - what if someone enters a negative value for income? Or zero? And where's the formula from (maybe add where the calcuation is from - since you mention the YR the calc is for).. AND it's for US Federal Taxes?" } ]
[ { "body": "<ol>\n<li>This code is repeating 2 times</li>\n</ol>\n<pre><code>myincome = int(input())\nbase = (myincome*.1)\ne = (max(myincome-9950,0)*.02)\nex = (max(myincome-40525,0)*.1)\next = (max(myincome-86376,0)*.02)\nextr = (max(myincome-164926,0)*.08)\nextra = (max(myincome-209426,0)*.03)\nextras = (max(myincome-523601,0)*.02)\ntax = base + e + ex + ext + extr + extra + extras\nprint ('You\\'re gonna get screwed about~$',str(tax) + ' dollars in Federal income tax')\nprint ()\n</code></pre>\n<p>Instead of repeating 2 times, create a function named <code>getIncome</code>, call it after <code>print ('What\\'s your yearly income after you deduct all expenses?')</code> and <code>print ('Try Different Income:')</code></p>\n<ol start=\"2\">\n<li><p>Why calling <code>print()</code> with no string, if you want to add a EOL, add <code>+'\\n'</code> while calling the print statement before it.</p>\n</li>\n<li><p>Your code is looking a bit dirty, use a code style guideline, like <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a></p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T06:52:50.683", "Id": "261408", "ParentId": "261407", "Score": "0" } }, { "body": "<ol>\n<li>You should split your code into reusable functions instead of manually rewriting / copying code.</li>\n<li>You should put your code into a <code>main()</code> function and wrap the call to it in a <code>if __name__ == &quot;__main__&quot;</code> condition. More info <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">here</a>.</li>\n<li>Variable names like <code>e, ex, ext, ...</code> aren't descriptive.</li>\n<li>You should include error handling for user input.</li>\n<li>You don't need seperate variables for every single tax bracket, rather you want a list of all tax brackets to iterate over.</li>\n<li>Depending on the income, you shouldn't always need to calculate all tax brackets. Once a bracket doesn't apply to the income, the subsequent brackets won't apply either.</li>\n<li>There should not be a space in <code>print (...)</code></li>\n<li>There should be spaces around operators and commas in <code>e = (max(myincome-9950,0)*.02)</code> -&gt; <code>e = (max(myincome - 9950, 0) * .02)</code></li>\n<li>If applicable, use your IDEs auto-formatting feature (e.g. <code>Ctrl</code> + <code>Alt</code> + <code>L</code> in PyCharm) to automatically avoid the aforementioned formatting issues.</li>\n<li>f-Strings make printing text including variables really convenient and handle string conversion for you.</li>\n<li>Type annotations are generally a good idea. They're beneficial to readability and error-checking.</li>\n</ol>\n<hr />\n<p><strong>Suggested code</strong></p>\n<pre><code>TAX_BRACKETS = [\n (0, 0.1),\n (9950, 0.02),\n (40525, 0.1),\n (86376, 0.02),\n (164926, 0.08),\n (209426, 0.03),\n (523601, 0.02)\n]\n\n\ndef get_income(prompt: str = &quot;&quot;, force_positive: bool = False) -&gt; int:\n try:\n income = int(input(prompt))\n except ValueError:\n print(&quot;Could not convert income to integer, please try again.&quot;)\n return get_income(prompt=prompt, force_positive=force_positive)\n\n if force_positive and income &lt; 0:\n print(&quot;Income must not be negative, please try again.&quot;)\n return get_income(prompt=prompt, force_positive=force_positive)\n\n return income\n\n\ndef calculate_income_tax(income: float) -&gt; float:\n tax = 0\n\n for bracket, rate in TAX_BRACKETS:\n if bracket &gt; income:\n break\n\n tax += (income - bracket) * rate\n\n return tax\n\n\ndef print_tax(tax: float) -&gt; None:\n print(f&quot;You're gonna get screwed about~${tax} dollars in Federal income tax\\n&quot;)\n\n\ndef main():\n income = get_income(prompt=&quot;What's your yearly income after you deduct all expenses?\\n&quot;)\n federal_income_tax = calculate_income_tax(income)\n print_tax(federal_income_tax)\n\n while True:\n income = get_income(prompt=&quot;Try different income:\\n&quot;)\n federal_income_tax = calculate_income_tax(income)\n print_tax(federal_income_tax)\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T10:18:34.293", "Id": "261416", "ParentId": "261407", "Score": "3" } } ]
{ "AcceptedAnswerId": "261416", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T06:32:29.213", "Id": "261407", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Simple Income Tax Calculator" }
261407
<p>I'm using a web crawler/scraper to keep tracking of products prices change. The bot fetches products' data and extracts needed info in this form:</p> <pre><code># (product_id, name, price, available) ( (&quot;601eda922b90d826a99d514c&quot;, &quot;iPhone ...&quot;, 800, True), ... .. . ) </code></pre> <p>I only need to keep last two days prices, so I created a collection like this (using <a href="https://github.com/art049/odmantic" rel="nofollow noreferrer">odmantic</a>):</p> <pre><code>class Products: product_id: str = Field(primary_field=True) # That ID comes from the web as a string so I thought to store it as is instead of creating ObjectId of it every iteration. name: Optional[str] price: Optional[int] old_price: Optional[int] available: Optional[bool] </code></pre> <p>When the crawler fetches tracked products, it returns them as tuple to this function (I know it's horrible):</p> <pre><code>async def update_products(fetched_products: Tuple[Tuple]): current_products = await engine.find(Products) modified_products = [] for np in fetched_products: try: existing_product = [x for x in current_products if x.product_id == np[0]][0] existing_product.old_price = existing_product.price existing_product.name = np[1] existing_product.price = np[2] existing_product.available = np[3] modified_products.append(existing_product) except IndexError: modified_products.append( Taager( product_id=np[0], name=np[1], price=np[2], old_price=0, available=np[3], ) ) return await engine.save_all(modified_products) </code></pre> <p>That was lazy approach and although It only gets executed once every day, I'd love to know how to optimize it in case I need to solve similar problem in the future.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T07:44:53.047", "Id": "261411", "Score": "0", "Tags": [ "python", "mongodb" ], "Title": "Tracking product prices" }
261411
<p>I created a class to handle maps in my RPG game, before it became a class this was a collection of functions I created, but I thought it could be used as a class. although this code is working but i am not sure what i made. changing the function set to OOP confuses me.</p> <pre><code>import os import pygame import helper_func as hf class Map: def __init__(self): self.map = [] self.images = {} self.tile_size = (50, 50) def load_map(self, path): ''' load map from txt to 2d list ''' f = open(path, &quot;r&quot;) file = f.read() f.close() sep = file.split(&quot;\n&quot;) for tile in sep: numbers = tile.split(&quot;,&quot;) self.map.append(numbers) @staticmethod def generate_key(image): result = [] for char in image: try: if isinstance(int(char), int): result.append(char) except Exception: pass return &quot;&quot;.join(result) def map_images(self, path): ''' load tileset image to dictionary ''' images = os.listdir(path) for image in images: key = Map.generate_key(image) self.images[key] = hf.load_image(f&quot;{path}/{image}&quot;, self.tile_size[0], self.tile_size[1]) def render(self, screen): y = 0 for row in self.map: x = 0 for tile in row: screen.blit(self.images[tile], (x, y)) x += self.tile_size[0] y += self.tile_size[1] </code></pre> <p>Is there anything that needs to be fixed?</p>
[]
[ { "body": "<p><code>Map.tile_size</code> seems awkward. You never use the tuple as whole, only the individual <code>[0]</code> and <code>[1]</code> components. Perhaps use two members (<code>Map.tile_width</code> and <code>Map.tile_height</code>) would be clearer, and possibly slightly faster due to removing one level of lookup.</p>\n<p>In <code>Map.load_map</code>, you split lines of text on commas, and assign it to <code>numbers</code>, but actually you just have a list of strings which presumably happen to look like numbers. What are these numbers? <code>0</code> to <code>9</code>? <code>00</code> to <code>99</code>? If they are small integers (0-255), you might store them very compactly as a <code>bytearray()</code>, or <code>bytes()</code> object. If the range of values is larger that a byte, you could use <code>array.array()</code>.</p>\n<p><code>Map.generate_key</code>: you’re using <code>try: catch:</code> to test if a character is in the range <code>'0'</code> to <code>'9'</code>? That is very expensive test, more so because you then test <code>isinstance(…, int)</code> which must be true if <code>int(char)</code> didn’t return an exception! The <code>isdecimal()</code> function can easily determine if the character is a digit, and the entire function body could be replaced with a single statement:</p>\n<pre><code> return &quot;&quot;.join(char for char in image if char.isdecimal())\n</code></pre>\n<p><code>map_images</code> is a very uninformative name. <code>load_map_images</code> would be better. <code>os.listdir(path)</code> is giving you ALL the files in the directory, which means you can’t have any backup files, readme files, or source-code control files in that directory. You should probably use a <code>glob()</code> to find only <code>*.png</code> files (or .gif, or whatever image format you are using).</p>\n<p>Your images are stored by by “key”, which is only the digits in the filename. So, <code>water0.png</code> and <code>grass0.png</code> would both be stored as under the key <code>&quot;0&quot;</code>, with the last one overwriting any previous ones. You might want to check for uniqueness or collisions.</p>\n<p>Which begs the question, why are you storing the map as numbers? Maybe “grass”, “forest”, “nw-road” would be clearer than “12”, “17”, “42”.</p>\n<p><code>render</code> seems to be only able to render the entire map. Perhaps that is all that is necessary for the game in question, but in many games, you’d usually render a small region around a given x,y coordinate.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T23:32:36.920", "Id": "261490", "ParentId": "261412", "Score": "2" } } ]
{ "AcceptedAnswerId": "261490", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T07:49:08.107", "Id": "261412", "Score": "4", "Tags": [ "python", "python-3.x", "object-oriented", "game", "pygame" ], "Title": "class that handles the rpg game map" }
261412
<p>I am working on an SMS marketing project based on Yii2 Framework (PHP 7.3 &amp; MariaDb (innodb engine)) where we have to move the logs from different tables to the archive db, which is total a different DB server from the live one.</p> <p>The log tables keep growing and we had to setup an automated job which runs 3 times a week at midnight and will keep filtering out the logs that are older than 45 days and move them to another database.</p> <p>I decided to use the Range partitioning and then use <code>EXCHANGE PARTITION</code> to move all the related data to a separate new table so that i keep the main/live table locked for partition process only and keep the copying/moving process that involves <code>Select</code> operation on a different table.</p> <p>So I divided the whole process into 2 different processes.</p> <ul> <li>Partitioning</li> <li>Archiving</li> </ul> <p>The partition process is further divided into</p> <ul> <li>Drop any Previously created Backup tables</li> <li>Create a new backup table like live table</li> <li>Create Partition on live table</li> <li>Exchange the partition with the backup table</li> <li>Remove the partition from the live table.</li> </ul> <p>My main focus is on the partition process if it can be improved to work more efficiently and less time. Currently I have the following stats for the partition process; I am only adding for one of the large tables</p> <h2>Transaction History table stats</h2> <p>Rows : total 172,899,990 rows approx</p> <p>Time to Partition : 1472.429115057 secs(24.54048525095 Mins) with total rows in the partition (12,937,902)</p> <p>Exchange partition : 0.062991857528687 secs</p> <p>Removed Partition : 1293.8012390137 secs.(21.56335398356167 Mins)</p> <h2>Transaction History Schema</h2> <pre><code>CREATE TABLE `transaction_history` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `amount` decimal(19,6) NOT NULL, `description` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, `transaction_type` varchar(30) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'blast', `remaining_balance` decimal(19,6) NOT NULL, `created_at` timestamp NOT NULL DEFAULT current_timestamp(), `updated_at` timestamp NULL DEFAULT NULL ON UPDATE current_timestamp(), PRIMARY KEY (`id`,`created_at`), KEY `transaction_type` (`transaction_type`), KEY `user_id_transaction_type` (`user_id`,`transaction_type`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci </code></pre> <p>The code is for the Yii2 console app.</p> <pre><code>&lt;?php namespace console\controllers; use Yii; use DateTime; use Exception; use DateInterval; use yii\helpers\Console; use yii\console\Controller; use yii\helpers\ArrayHelper; use console\controllers\traits\ArchiveTraits; class PartitionController extends Controller { use ArchiveTraits; /** * Contains array of tables and their range column to be used for partition * in the key=&gt;value format like [table_name=&gt;range_column_name] * * Note: before you add any new table to the below list make sure you have * added the range column to unique index or part of the primary key */ const BACKUP_TABLES = [ 'message_inbound' =&gt; 'created_at', 'transaction_history' =&gt; 'created_at', 'sms_api_log' =&gt; 'created_at', 'balance_history' =&gt; 'created_on', 'buy_number_logs' =&gt; 'created_at', 'destination_delivery' =&gt; 'created_at', 'message_delivery' =&gt; 'created_at', 'email_delivery_logs' =&gt; 'created_at', 'responder_keywords_logs' =&gt; 'created_at', 'sms_alert_logs' =&gt; 'created_at', 'suppression_message_logs' =&gt; 'created_at', ]; private $_date = null; /** * @var batch size for the * inserts in the database */ const BATCH_SIZE = 10000; /** * @var limit for the rows to be migrated to the * database in one iteration */ const MIGRATE_LIMIT = 50000; public function actionIndex($date = null) { $this-&gt;_date = $date; $this-&gt;startNotification(&quot;Partition Process started&quot;, 'partition-start'); ini_set(&quot;memory_limit&quot;, 0); $this-&gt;stdout(&quot;Starting Partition Process.\n&quot;); $this-&gt;startPartition(); $this-&gt;stdout(&quot;Completed Partition Process.\n&quot;); $date = date(&quot;Y-m-d&quot;); $this-&gt;sendSummaryReport(&quot;Partitioning Process Complete for {$date}&quot;, &quot;partition-complete&quot;, &quot;partition&quot;); } /** * @param int $start the start timestamp */ public function end($start) { return microtime(true) - $start; } public function start() { return microtime(true); } /** * Starts the partitioning process for the live DB log tables * * @return null * @throws Exception */ protected function startPartition() { foreach (self::BACKUP_TABLES as $tableName =&gt; $rangeColumn) { try { $this-&gt;partitionNow($tableName, $rangeColumn); $this-&gt;stdout(&quot;\n&quot;); } catch (Exception $e) { $this-&gt;sendExceptionEmail($tableName, $e, &quot;Exception on Partitioning table&quot;, &quot;partition-exception&quot;); $this-&gt;stdout(&quot;There was an error while trying to archive the {$tableName} .\n&quot;); $this-&gt;stdout($e-&gt;getMessage() . &quot;\n===============\n&quot;); $this-&gt;stdout(&quot;Continuing to archive the next table.\n&quot;); } } } /** * Creates the backup for the specified table and the range column * by creating a partition and then exchanging the old data * partition with the backup table and then move the data to the * archive database * * @param string $tableName the name of the table to backup data from live DB * @param string $rangeColumn the name of the column used for the range partition * * @return null */ protected function partitionNow($tableName, $rangeColumn = 'created_at') { $rangeOldPartition = $this-&gt;rangeOldPartition(); $backupTableName = $this-&gt;generateBackupTableName($tableName); $dbLive = self::_getDsnAttribute('dbname'); //drop backup table if exists $this-&gt;dropBackupTables($tableName); $this-&gt;stdout(&quot;Started Partitioning {$tableName}\n&quot;); $startTime = $this-&gt;start(); try { $sql = &lt;&lt;&lt;SQL -- create the backup table and remove partitioning from the backup table CREATE TABLE `{$dbLive}`.{{%{$backupTableName}}} LIKE `{$dbLive}`.{{%{$tableName}}}; -- start partitioning the source table ALTER TABLE `{$dbLive}`.{{%{$tableName}}} PARTITION BY RANGE(UNIX_TIMESTAMP({$rangeColumn})) ( PARTITION oldPt VALUES LESS THAN (UNIX_TIMESTAMP(&quot;{$rangeOldPartition}&quot;)), PARTITION activePt VALUES LESS THAN (MAXVALUE) ); SQL; $command = Yii::$app-&gt;db-&gt;createCommand($sql); $command-&gt;execute(); //necessary to catch exceptions or errors when // using multiple SQL statements with createcommand while ($command-&gt;pdoStatement-&gt;nextRowSet()) { //leave blank do nothing } $this-&gt;stdout(&quot;Partitioned table in {$this-&gt;end($startTime)} secs.\n&quot;, Console::FG_GREEN); $startTime = $this-&gt;start(); $sql = &lt;&lt;&lt;SQL -- exchange the partition with the backup table ALTER TABLE `{$dbLive}`.{{%{$tableName}}} EXCHANGE PARTITION oldPt WITH TABLE `{$dbLive}`.{{%{$backupTableName}}}; SQL; $command = Yii::$app-&gt;db-&gt;createCommand($sql); $command-&gt;execute(); $this-&gt;stdout(&quot;Completed Exchange partition {$this-&gt;end($startTime)} secs\n&quot;); $startTime = $this-&gt;start(); $sql = &lt;&lt;&lt;SQL -- remove partition from the source table once data moved to separate table ALTER TABLE `{$dbLive}`.{{%{$tableName}}} REMOVE PARTITIONING; SQL; $command = Yii::$app-&gt;db-&gt;createCommand($sql); $command-&gt;execute(); $this-&gt;stdout(&quot;Removed Partition in {$this-&gt;end($startTime)} secs.\n&quot;); $this-&gt;stdout(&quot;Filterd out data from live table.\n&quot;); } catch (Exception $e) { throw $e; } } /** * Takes the source table name ad * * @param $tableName */ protected function dropBackupTables($tableName) { $backupTableName = $this-&gt;generateBackupTableName($tableName); $sql = &lt;&lt;&lt;SQL DROP TABLE IF EXISTS {{%{$backupTableName}}}; SQL; Yii::$app-&gt;db-&gt;createCommand($sql)-&gt;execute(); } /** * Generates the backup table name from the source table name * * @param string $tableName the source table to mock the backup table from * * @return string $backupTableName the name of the backup table */ protected function generateBackupTableName($tableName) { $backupTableAlias = 'bkp_' . date('Ymd') . '_'; return &quot;{$backupTableAlias}{$tableName}&quot;; } /** * Returns the create table command for the given table * @param $tableName */ protected function getCreateTable($tableName) { $data = Yii::$app-&gt;db-&gt;createCommand(&quot;show create table {{%{$tableName}}}&quot;)-&gt;queryOne(); return str_replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS', $data['Create Table']); } /** * @param $tableName */ protected function getPageData($tableName, $offset = 0) { $limit = self::MIGRATE_LIMIT; $sql = &lt;&lt;&lt;SQL SELECT * FROM {{%{$tableName}}} order by id LIMIT {$offset},{$limit} SQL; return Yii::$app-&gt;db-&gt;createCommand($sql)-&gt;queryAll(); } /** * @param $tableName */ protected function getRowCount($tableName) { $sql = &lt;&lt;&lt;SQL SELECT COUNT(*) as total FROM {{%{$tableName}}} SQL; $data = Yii::$app-&gt;db-&gt;createCommand($sql)-&gt;queryOne(); $this-&gt;stdout(&quot;Found {$data['total']} records.&quot;); return $data['total']; } /** * Returns the columns names for a table * * @param string $db the database name * @param string $tableName the table name * * @return mixed */ protected function getTableColumns($db, $tableName) { $sql = &lt;&lt;&lt;SQL select COLUMN_NAME from information_schema.columns where table_schema = &quot;{$db}&quot; and table_name=&quot;{$tableName}&quot; order by table_name,ordinal_position; SQL; return ArrayHelper::getColumn( Yii::$app-&gt;db-&gt;createCommand($sql)-&gt;queryAll(), 'COLUMN_NAME' ); } /** * Returns the date for the specified interval * to backup default interval is 45 days. * * @return mixed */ protected function rangeOldPartition() { $date = new DateTime(); $date-&gt;sub(new DateInterval('P0M45D')); return $date-&gt;format(&quot;Y-m-d&quot;); } /** * Returns the database name after extracting the * specific string from the Dsn property * * @param string $name the name of the property in dsn string. * @param string $target the target connection of the database live|archive, default &quot;live&quot; * * @return mixed */ private static function _getDsnAttribute($name, $target = 'live') { if ($target === 'live') { if (preg_match(&quot;/{$name}=([^;]*)/&quot;, Yii::$app-&gt;getDb()-&gt;dsn, $match)) { return $match[1]; } } else { if (preg_match(&quot;/{$name}=([^;]*)/&quot;, Yii::$app-&gt;db_backup-&gt;dsn, $match)) { return $match[1]; } } throw new Exception(&quot;Unable to extract the db Name&quot;); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T11:40:19.777", "Id": "520774", "Score": "0", "body": "Can you please provide the complete class definition? It would be helpful to know more about some methods referenced within methods like `partitionNow()` and `generateBackupTableName()`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T15:04:58.477", "Id": "520789", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ i think the method `partitionNow()` is the first method listed in the code, and the `generateBackupTableName()` is only generating the table name for the bakcup i have added it too" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-05T01:00:24.303", "Id": "520815", "Score": "1", "body": "@SᴀᴍOnᴇᴌᴀ i have added the complete class definition." } ]
[ { "body": "<p>This review will focus on the PHP to generate the queries. Other reviewers may have suggestions about improving the partition process.</p>\n<h1>General feedback</h1>\n<p>The code is easy to read and mostly is in line with the recommendations in the <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">PSR-12</a> style guide. The methods have good docblocks to describe the purpose and list parameters, return values and possible exceptions thrown.</p>\n<h1>Suggestions</h1>\n<h3>Coding Style</h3>\n<p><a href=\"https://stackoverflow.com/a/5766153/1575353\">the underscore to indicate private properties and methods is a convention from PHP 4</a> though <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">PSR-12</a> advises against this practice:</p>\n<blockquote>\n<h3>4.3 Properties and Constants</h3>\n<p>Visibility MUST be declared on all properties.</p>\n<p>Visibility MUST be declared on all constants if your project PHP minimum version supports constant visibilities (PHP 7.1 or later).</p>\n<p>The <code>var</code> keyword MUST NOT be used to declare a property.</p>\n<p>There MUST NOT be more than one property declared per statement.</p>\n<p>Property names MUST NOT be prefixed with a single underscore to indicate protected or private visibility. That is, an underscore prefix explicitly has no meaning.</p>\n</blockquote>\n<blockquote>\n<h3>4.4 Methods and Functions</h3>\n<p>Visibility MUST be declared on all methods.</p>\n<p>Method names MUST NOT be prefixed with a single underscore to indicate protected or private visibility. That is, an underscore prefix explicitly has no meaning.</p>\n</blockquote>\n<p>Also note it recommends declaring the visibility on constants when using PHP 7.1 or later.</p>\n<h3>Type declarations</h3>\n<p><a href=\"https://www.php.net/manual/en/migration70.new-features.php\" rel=\"nofollow noreferrer\">Type declarations</a> can be added for arguments and return values of methods, plus with PHP 7.4 they can be added to properties.</p>\n<h3>Method length</h3>\n<p>Most methods are quite short and concise, though<code>partitionNow()</code> is rather long- perhaps moving the code to get the queries to sub-methods would help. Also at the end are these lines:</p>\n<blockquote>\n<pre><code> catch (Exception $e) {\n throw $e;\n }\n</code></pre>\n</blockquote>\n<p>If there was code to handle the exception or at least log it somewhere then it would make sense to catch it but this makes the <code>try/catch</code> seem useless.</p>\n<p>In the function <code>generateTableBackupName()</code> does this:</p>\n<blockquote>\n<pre><code>$backupTableAlias = 'bkp_' . date('Ymd') . '_';\n return &quot;{$backupTableAlias}{$tableName}&quot;;\n</code></pre>\n</blockquote>\n<p>There seems little point in creating a variable used only once - it would be simpler to merely have it be:</p>\n<pre><code> return = 'bkp_' . date('Ymd') . '_' . $tableName;\n</code></pre>\n<h3>Repetitive code</h3>\n<p>The method <code>_getDsnAttribute()</code> could be simplified from the current code:</p>\n<blockquote>\n<pre><code>if ($target === 'live') {\n if (preg_match(&quot;/{$name}=([^;]*)/&quot;, Yii::$app-&gt;getDb()-&gt;dsn, $match)) {\n return $match[1];\n }\n} else {\n if (preg_match(&quot;/{$name}=([^;]*)/&quot;, Yii::$app-&gt;db_backup-&gt;dsn, $match)) {\n return $match[1];\n }\n}\nthrow new Exception(&quot;Unable to extract the db Name&quot;);\n</code></pre>\n</blockquote>\n<p>The only thing that appears to be different is the second argument in the call to <code>preg_match()</code>. That difference can be stored in a variable which allows the regular expression condition to only be listed once, in turn reducing indentation levels.</p>\n<pre><code>if ($target === 'live') {\n $dsn = Yii::$app-&gt;getDb()-&gt;dsn;\n} else {\n $dsn = Yii::$app-&gt;db_backup-&gt;dsn;\n}\nif (preg_match(&quot;/{$name}=([^;]*)/&quot;, $dsn, $match)) {\n return $match[1];\n}\nthrow new Exception(&quot;Unable to extract the db Name&quot;);\n</code></pre>\n<p>And the assignment of <code>$dsn</code> could be consolidated to a ternary unless that is too long for one line:</p>\n<pre><code>$dsn = $target === 'live' ? Yii::$app-&gt;getDb()-&gt;dsn : Yii::$app-&gt;db_backup-&gt;dsn;\n</code></pre>\n<h3>docblock inaccuracy</h3>\n<p>The docblock for <code>startPartition</code> states that it “<code>@throws Exception</code>” however that doesn’t appear to be true since it <em>catches</em> <code>Exception</code>s.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T14:39:36.613", "Id": "270667", "ParentId": "261415", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T09:33:22.967", "Id": "261415", "Score": "3", "Tags": [ "performance", "php", "sql", "php7", "yii" ], "Title": "Archiving / Moving Data from one database server to another database server" }
261415
<p>This is a random word generator I wrote in Python 3 today, I don't know how many Python implemetations of this exist, but this is my first try and it is completely working.</p> <p>It returns a random word like string that is pronounceable (most likely pronounceable), I used some English letter frequency statistics data to ensure the letter frequencies in the result would follow English letter distribution patterns, and shuffled that data to make the result truly random;</p> <p>And then I used some English letter following rules (what letters can follow a letter) to make the result pronounceable.</p> <p>Beware this script is feature incomplete, new features will be added tomorrow, but it is now completely stable and achieved like 70% of the intended ends, anyway here is the code:</p> <pre class="lang-py prettyprint-override"><code>import random from collections import Counter SAMPLE = Counter({ 'e': 1202, 't': 910, 'a': 812, 'o': 768, 'i': 731, 'n': 695, 's': 628, 'r': 602, 'h': 592, 'd': 432, 'l': 398, 'u': 288, 'c': 271, 'm': 261, 'f': 230, 'y': 211, 'w': 209, 'g': 203, 'p': 182, 'b': 149, 'v': 111, 'k': 69, 'x': 17, 'q': 11, 'j': 10, 'z': 8 }) pool = list(SAMPLE.elements()) randpool = [] while len(pool) &gt; 0: elem = random.choice(pool) randpool.append(elem) pool.remove(elem) LETTERS = 'abcdefghijklmnopqrstuvwxyz' tails = { 'a': LETTERS, 'b': 'aeioubjlry', 'c': 'aeiouchjklry', 'd': 'aeioudgjwy', 'e': LETTERS, 'f': 'aeioufjlry', 'g': 'aeioughjlrwy', 'h': 'aeiouy', 'i': LETTERS, 'j': 'aeiouy', 'k': 'aeiouhklrvwy', 'l': 'aeioulvwy', 'm': 'aeioucmy', 'n': 'aeiougny', 'o': LETTERS, 'p': 'aeioufhlprsty', 'q': 'aeiou', 'r': 'aeiouhrwy', 's': 'aeiouchjklmnpqrstvwy', 't': 'aeiouhjrstwy', 'u': LETTERS, 'v': 'aeioulvy', 'w': 'aeiouhry', 'x': 'aeiouhy', 'y': 'aeiousvwy', 'z': 'aeiouhlmvwy' } def randomword(): count = random.randint(1, 6) heads = [random.choice(randpool) for i in range(count)] i = 0 segments = [] while count &gt; 0: h = heads[i] w = h while True: r = random.choice(randpool) if r in tails[h]: if i == 0 and r == h: continue else: break w += r while True: f = r r = random.choice(randpool) if r in tails[f]: w += r if random.randint(0, 9999) % 2 == 0: segments.append(w) count -= 1 break i += 1 return ''.join(segments) if __name__ == '__main__': print(randomword()) </code></pre> <p>Please share your thoughts on my script, about how it can be improved, about what new rules I need to add to make the result resemble real words more.</p> <p>I currently am thinking about making consecutive vowels less than three and no more than three consecutive consonants without a vowel, I am able to implement these, but they are all I can think of now.</p> <p>Please share your thoughts on possible improvements, any help is welcome!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T08:57:09.087", "Id": "515945", "Score": "0", "body": "Hi Xeнεi Ξэnвϵς. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the question & answer style of Code Review. As such I have rolled back your latest edit. Please see [what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)." } ]
[ { "body": "<p>This isn't Python specific, but in <code>tails</code>, every letter will map to at least all the vowels. Since every entry contains the vowels <code>aeiou</code>, I'd probably make that implicit for the sake of brevity, maintainability, and space. You could automatically append the voewels to the result of the lookup, then only store in the dictionary the unique letters (<code>&quot;bjlry&quot;</code> for the case of &quot;b&quot; for example). You'd have to figure out how to handle letters like &quot;a&quot; that map to everything though, but that might be made easier with my next suggestions.</p>\n<hr />\n<p><code>LETTERS</code> is unnecessary. Python already has this in the <code>string</code> module:</p>\n<pre><code>from string import ascii_lowercase\n</code></pre>\n<p>You could use that with <code>set</code>s to generate consonants:</p>\n<pre><code>LETTERS = set(ascii_lowercase)\nVOWELS = set(&quot;aeiou&quot;)\nCONSONANTS = LETTERS - VOWELS\n</code></pre>\n<p>Then you could change your <code>tails</code> to something like:</p>\n<pre><code>unique_tails = {\n 'a': CONSONANTS,\n 'b': 'bjlry',\n 'c': 'chjklry',\n 'd': 'dgjwy',\n 'e': CONSONANTS,\n . . .\n</code></pre>\n<p>And then change your loops to something like:</p>\n<pre><code>if r in tails[h] or r in VOWELS:\n</code></pre>\n<p>You may find this ends up nicer. I like to avoid duplication, so I'd go in this direction, but you may find it complicates matters.</p>\n<hr />\n<p>You use a lot of single-letter variable names, and it's hurting readability. <code>i</code> for an index is common and fine, but <code>h</code>, <code>w</code>, and <code>r</code> should really be spelled out so their purpose is clearer.</p>\n<hr />\n<p><code>random.randint(0, 9999) % 2 == 0</code> seems convoluted. As far as I can tell, that's just basically a &quot;coin-flip&quot;, but it's basing it on a random number from 0-9999 for some reason. I think the <code>9999</code> is a red-herring that makes the code harder to understand,and it would be clearer to just generate a single random bit:</p>\n<pre><code>if random.getrandbits(1) == 0: # Or maybe just if random.getrandbits(1):\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T16:21:16.030", "Id": "261429", "ParentId": "261421", "Score": "5" } }, { "body": "<p>Since you've requested input on how to improve the algorithm in addition to directly improving code (and I know very little about Python anyways), I'll share my idea on it.</p>\n<h1>Use Markov chains</h1>\n<p>It's pretty close to what you're already doing, but determines the following letter based on many letters before it, not just one. Obviously, it will have vastly bigger lookup table, so you'll also want to write a (probably separate) program that parses dictionary and stores that data for word generation. It's up to you how to store result, one of viable options is to use sqlite due to relative ease of use, great speed and ability to operate in-memory. My testing reveals that optimal amount of letters to account for is 3: less gives incoherent results and more leads to words being too close to existing ones.</p>\n<p>Also, Markov chains aren't limited to word generation. With some tweaking it should be possible to produce (rather odd) texts.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T00:00:17.183", "Id": "261445", "ParentId": "261421", "Score": "3" } }, { "body": "<p>I had made a few improvements to the code, its outputs are now much better, though still it isn't not quite what I had in mind when I wrote the code, but it is much closer than before, though it still isn't ideal.</p>\n<p>It now imports ascii_lowercase from String module, has a constant that stores vowels, and gets consonants by subtracting vowels from letters.</p>\n<p>I capitalized the name of tails because it acts as a constant during code execution, and only store unique entries in it.</p>\n<p>I made a few corrections to the letter following rules, and extended the definition of vowels to include the letter &quot;y&quot;, because y can follow virtually any letter.</p>\n<p>I lowered the maximum limit of heads a word can have to four, and set the limit to the maximum number of tails a head can have to a random integer in the range between two and five, just in the improbable case the coin-flip fails to break the loops.</p>\n<p>I have also made the script discard the random letter if there are already two consecutive vowels or consonants or same letters.</p>\n<p>So this is the updated code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import random\nfrom collections import Counter\nfrom string import ascii_lowercase\n\nSAMPLE = Counter({\n 'e': 1202,\n 't': 910,\n 'a': 812,\n 'o': 768,\n 'i': 731,\n 'n': 695,\n 's': 628,\n 'r': 602,\n 'h': 592,\n 'd': 432,\n 'l': 398,\n 'u': 288,\n 'c': 271,\n 'm': 261,\n 'f': 230,\n 'y': 211,\n 'w': 209,\n 'g': 203,\n 'p': 182,\n 'b': 149,\n 'v': 111,\n 'k': 69,\n 'x': 17,\n 'q': 11,\n 'j': 10,\n 'z': 8\n})\n\npool = list(SAMPLE.elements())\nrandpool = []\n\nwhile len(pool) &gt; 0:\n elem = random.choice(pool)\n randpool.append(elem)\n pool.remove(elem)\n\nLETTERS = set(ascii_lowercase)\nVOWELS = set('aeiouy')\nCONSONANTS = LETTERS - VOWELS\n\nTAILS = {\n 'a': CONSONANTS,\n 'b': 'bjlr',\n 'c': 'chjklr',\n 'd': 'dgjw',\n 'e': CONSONANTS,\n 'f': 'fjlr',\n 'g': 'ghjlrw',\n 'h': '',\n 'i': CONSONANTS,\n 'j': '',\n 'k': 'hklrvw',\n 'l': 'l',\n 'm': 'cm',\n 'n': 'gn',\n 'o': CONSONANTS,\n 'p': 'fhlprst',\n 'q': '',\n 'r': 'hrw',\n 's': 'chjklmnpqstw',\n 't': 'hjrstw',\n 'u': CONSONANTS,\n 'v': 'lv',\n 'w': 'hr',\n 'x': 'h',\n 'y': 'sv',\n 'z': 'hlvw'\n}\n\n# variables expanded:\n# w: Word, r: Random Letter, sc: Serial Consonants count, sv: Serial Vowels Count, ss: Serial Same-letter count, lm: Max Length of tails, l: Length of tails\n\ndef randomword():\n count = random.randint(1, 4)\n heads = [random.choice(randpool) for i in range(count)]\n i = 0\n segments = []\n while count &gt; 0:\n sc, ss, sv = 0, 0, 0 \n w = heads[i]\n if w in CONSONANTS: sc += 1\n else: sv += 1\n while True:\n r = random.choice(randpool)\n if r in TAILS[w] or r in VOWELS:\n if i == 0 and r == w: continue\n else:\n if r in VOWELS:\n sc = 0\n sv += 1\n break\n else:\n sv = 0\n sc += 1\n break\n w += r\n l = 1\n lm = random.randint(2, 5)\n while True:\n if l == lm:\n segments.append(w)\n count -= 1\n break\n f = r\n r = random.choice(randpool)\n if r in TAILS[f] or r in VOWELS:\n if r in VOWELS:\n sc = 0\n sv += 1\n elif r in CONSONANTS:\n sv = 0\n sc += 1\n if sv == 3 or sc == 3: continue\n if r != f: ss = 0\n if r == f and ss == 1: continue\n if r == f: ss += 1\n w += r\n l += 1\n if random.getrandbits(1):\n segments.append(w)\n count -= 1\n break\n i += 1\n return ''.join(segments)\n\nif __name__ == '__main__':\n print(randomword())\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T09:32:30.120", "Id": "261460", "ParentId": "261421", "Score": "0" } } ]
{ "AcceptedAnswerId": "261429", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T13:38:12.797", "Id": "261421", "Score": "4", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge", "random" ], "Title": "Python random word generator that generates a wordlike pronounceable string" }
261421
<p>Looking for some help on how to speed up the code below as I'm still relatively new to using Pandas.</p> <p>The playoff_stats function makes thousands of calls to the PlayerCareerStats API - and while it does work in getting me exactly what I want, it is pretty slow.</p> <p>Just wondering if there is a method to make these repeated function calls that is more efficient than what I'm currently doing.</p> <pre><code>import pandas as pd from nba_api.stats.endpoints import commonallplayers from nba_api.stats.endpoints import playercareerstats from matplotlib import pyplot as plt import numpy as np import seaborn as sns pd.set_option('display.max_columns', None) player_data = commonallplayers.CommonAllPlayers(timeout = None) player_df = player_data.common_all_players.get_data_frame().set_index('PERSON_ID') id_list = player_df.index.tolist() def playoff_stats(player_id): player_stats = playercareerstats.PlayerCareerStats(player_id, timeout = None) yield player_stats.career_totals_post_season.get_data_frame()[['GP', 'PTS']].values.tolist() stats_dict = {} for i in id_list: try: stats_call = next(playoff_stats(i)) if len(stats_call) &gt; 0: stats_dict[player_df.loc[i]['DISPLAY_FIRST_LAST']] = [stats_call[0][0], stats_call[0][1]] except KeyError: continue </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T13:54:43.877", "Id": "515880", "Score": "2", "body": "Where does `commonallplayers` come from? You need to show more of your code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T14:46:01.483", "Id": "515884", "Score": "0", "body": "Added up top - thx" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T13:42:53.293", "Id": "261422", "Score": "0", "Tags": [ "python-3.x", "api", "pandas" ], "Title": "How to most efficiently make repeated calls to API with Pandas/Python" }
261422
<p>I've been learning Rust for a few weeks in my free time, and as a first project I decided to make a simple terminal Game of Life program (without UI, that might come later). It just starts with a glider and loops indefinitely (Torus topology). I decided to keep it simple so I can learn from early mistakes before I start to make it more complex. Here are the 3 files of the project (The only dependency I'm using is termion for colored terminal output):</p> <p><strong>grid.rs</strong></p> <pre><code>use std::fmt; pub struct Grid { rows: usize, cols: usize, data: Vec&lt;bool&gt;, aux_data: Vec&lt;bool&gt;, } impl Grid { pub fn new(rows: usize, cols: usize) -&gt; Self { Grid { rows: rows, cols: cols, data: vec![false; rows * cols], aux_data: vec![false; rows * cols], } } pub fn get_rows(&amp;self) -&gt; usize { self.rows } pub fn get_cols(&amp;self) -&gt; usize { self.cols } pub fn get_cell(&amp;self, row: usize, col: usize) -&gt; bool { self.data[row*self.get_cols() + col] } pub fn set_cell(&amp;mut self, value: bool, row: usize, col: usize) { let ncols = self.get_cols(); self.data[row*ncols + col] = value; } fn count_alive_neighbours(&amp;self, row: usize, col: usize) -&gt; i32 { let offsets: [(usize, usize); 8] = [ (self.get_rows()-1, self.get_cols()-1), (self.get_rows()-1, 0), (self.get_rows()-1, 1), ( 0, self.get_cols()-1), ( 0, 1), ( 1, self.get_cols()-1), ( 1, 0), ( 1, 1) ]; let mut count = 0; for offset in offsets.iter() { let is_alive = self.get_cell( (row + offset.0)%self.get_rows(), (col + offset.1)%self.get_cols() ); if is_alive { count += 1 } } count } pub fn update(&amp;mut self) { use std::mem::swap; self.aux_data.resize(self.data.len(), false); let ncols = self.get_cols(); for row in 0..self.get_rows() { for col in 0..self.get_cols() { let is_alive = self.get_cell(row, col); let alive_neighbours = self.count_alive_neighbours(row, col); self.aux_data[row*ncols + col] = match (is_alive, alive_neighbours) { (true, n) if n &lt; 2 || 3 &lt; n =&gt; false, (false, 3) =&gt; true, (cell, _) =&gt; cell, }; } } swap(&amp;mut self.data, &amp;mut self.aux_data); } } impl fmt::Display for Grid { fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result { use termion::color; for index_row in 0..self.get_rows() { for index_col in 0..self.get_cols() { match self.get_cell(index_row, index_col) { false =&gt; write!(f, &quot;{}\u{25FC} &quot;, color::Fg(color::White))?, true =&gt; write!(f, &quot;{}\u{25FC} &quot;, color::Fg(color::Red))?, } } write!(f, &quot;\n&quot;)? } Ok(()) } } </code></pre> <p><strong>lib.rs</strong></p> <pre><code>pub mod grid; </code></pre> <p><strong>main.rs</strong></p> <pre><code>extern crate game_of_life; use game_of_life::grid::Grid; use std::{thread, time}; fn main() { let mut grid = Grid::new(5, 5); grid.set_cell(true, 1, 2); grid.set_cell(true, 2, 3); grid.set_cell(true, 3, 1); grid.set_cell(true, 3, 2); grid.set_cell(true, 3, 3); loop { print!(&quot;{}\n&quot;, grid); grid.update(); thread::sleep(time::Duration::from_secs(1)); } } </code></pre> <p>I come from a very strong C++ background, so some C++ practices might leak in my Rust code, but I promise I want to learn about them and try to think in the Rust way.</p> <p>Thank you everyone and have a nice day!</p>
[]
[ { "body": "<p>Firstly, there are a few simple changes I would recommend (for future reference, these can be picked up by running <code>cargo clippy</code>):</p>\n<ul>\n<li>In <code>main</code>, you have <code>print!(&quot;{}\\n&quot;, grid);</code> - this can be replaced with <code>println!(&quot;{}&quot;, grid);</code></li>\n<li>In your <code>Display</code> implementation for <code>Grid</code>, you have <code>write!(f, &quot;\\n&quot;)?;</code> - this can be replaced with a <code>writeln!(f)?;</code></li>\n<li>In <code>Grid::new</code>, you have</li>\n</ul>\n<pre class=\"lang-rust prettyprint-override\"><code>Grid {\n rows: rows,\n cols: cols,\n ...\n}\n</code></pre>\n<p>This can be replaced with a more succinct</p>\n<pre class=\"lang-rust prettyprint-override\"><code>Grid {\n rows,\n cols,\n ...\n}\n</code></pre>\n<ul>\n<li>You have the condition <code>if n &lt; 2 || 3 &lt; n</code> in <code>Grid::update</code> - clippy recommends changing this to <code>if !(2..=3).contains(&amp;n)</code> which is more clear to me.</li>\n<li>I also recommend running <code>cargo fmt</code> which ensures you're using the standard rust formatting, but this removes your special formatting on <code>offsets</code> in <code>Grid::count_alive_neighbours</code>. If you want to keep this, you can add <code>#[rustfmt::skip]</code> to the line before the variable declaration.</li>\n</ul>\n<p>Now for changes which cargo clippy cannot pick up:</p>\n<ul>\n<li>Your type annotation on <code>offsets</code> is unneeded.</li>\n<li>It isn't really common practice to have <code>use</code> statements in functions - most of the time you simply place them at the top of the file.</li>\n<li><code>for offset in offsets.iter()</code> can be written more succinctly as <code>for offset in &amp;offsets</code></li>\n<li>In fact, that code block can be rewritten to completely avoid the need for a mutable variable, using iterators.</li>\n</ul>\n<pre class=\"lang-rust prettyprint-override\"><code>let count = offsets\n .iter()\n .filter(|offset| {\n self.get_cell(\n (row + offset.0) % self.get_rows(),\n (col + offset.1) % self.get_cols(),\n )\n })\n .count() as i32;\n</code></pre>\n<p>And in doing so, you can also remove the need for the <code>count</code> variable entirely - by just returning that iterator statement instead of assigning to a variable and then returning. It is up to you to decide if you prefer this, but in general it is good practice to avoid mutable variables where possible.</p>\n<ul>\n<li>I'm not sure if <code>self.aux_data.resize(self.data.len(), false);</code> is required in <code>Grid::update</code>? <code>aux_data</code> and <code>data</code> are created with the same size, and new items are never added - so both the size and the capacity should remain the same.</li>\n<li>I would also recommend adding doc comments and potentially doc tests. As an example, you could write <code>Grid::new</code> as</li>\n</ul>\n<pre class=\"lang-rust prettyprint-override\"><code>/// Initialises a new grid with the given size, with both data and aux_data filled with empty cells.\npub fn new(rows: usize, cols: usize) -&gt; Self {\n Grid {\n rows,\n cols,\n data: vec![false; rows * cols],\n aux_data: vec![false; rows * cols],\n }\n}\n</code></pre>\n<p>More information on doc comments &amp; tests can be found at <a href=\"https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html\" rel=\"nofollow noreferrer\">https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html</a>.</p>\n<ul>\n<li>In general, simple getters &amp; setters (like <code>get_cols</code>) should not be used in other methods - so you could replace</li>\n</ul>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn set_cell(&amp;mut self, value: bool, row: usize, col: usize) {\n let ncols = self.get_cols();\n self.data[row * ncols + col] = value;\n}\n</code></pre>\n<p>with</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn set_cell(&amp;mut self, value: bool, row: usize, col: usize) {\n self.data[row * self.cols + col] = value;\n}\n</code></pre>\n<p>and so on for your other methods (such as <code>count_alive_neighbours</code>). The getters used here don't provide any extra functionality, and as such they're not really useful since you have access to private members anyways.</p>\n<ul>\n<li>It might also be worth storing enum variants for cells instead of a boolean. For example, you could define an enum (the <code>Clone</code> derive is needed for the vector initialization, <code>Copy</code> for <code>get_cell</code>, and <code>PartialEq</code> for checking whether cells are alive/dead in <code>count_alive_neighbours</code>)</li>\n</ul>\n<pre class=\"lang-rust prettyprint-override\"><code>#[derive(Clone, Copy, PartialEq)]\nenum Cell {\n Dead,\n Alive,\n}\n</code></pre>\n<p>and then store that in <code>data</code> and <code>aux_data</code>, replacing all <code>false</code> with <code>Cell::Dead</code> and <code>true</code> with <code>Cell::Alive</code>. This helps to make it more immediately understandable. This enum and a bool also have the same size (1 byte) so it won't have performance impacts. As an example, the match part of your <code>Display</code> implementation might look like the following:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>match self.get_cell(index_row, index_col) {\n Cell::Dead =&gt; write!(f, &quot;{}\\u{25FC} &quot;, color::Fg(color::White))?,\n Cell::Alive =&gt; write!(f, &quot;{}\\u{25FC} &quot;, color::Fg(color::Red))?,\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T16:45:51.387", "Id": "515898", "Score": "0", "body": "Thank you very much for taking your time in reviewing my code! I've learnt a lot with this single review (didn't know about clippy, nor fmt). There's only one thing I don't really agree, and it's about the getters/setters. While I agree those don't do anything special in this case, I prefer to interface with them everywhere in case I want to change my underlyned representation. Maybe in the future I want to use an array2d crate and get rid of rows and cols variables. I know this is very object oriented and opinionated, but I prefer to make a change in just one place rather in many places." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T16:54:55.510", "Id": "515899", "Score": "0", "body": "For the getters, I'd normally agree with you - I just pointed it out here since the logic for getting the number of columns/rows is very unlikely to change (in fact, the only way I can see it changing is if you change the underlying representation, and in that case you'd have more code to change anyways). So for me, I'd rather just use the variables directly, as that removes one layer of indirection, making it simpler to understand - but yes, like you said, this is very subjective and it's really up to you to decide." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T14:40:00.740", "Id": "261424", "ParentId": "261423", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T13:54:33.457", "Id": "261423", "Score": "3", "Tags": [ "beginner", "rust", "game-of-life" ], "Title": "Simple terminal Game of Life in Rust" }
261423
<p>Can some one help me on how to eliminate repetition to reduce duplication score on the below classes created in the code</p> <pre><code>class EnquiryFilterSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = '__all__' class EnquirySerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = '__all__' def update(self, instance, validated_data): # making sure if broker is not fetched then replace null value with # some resonable data as it will help in duing filter if len(validated_data.get('email_broker', instance.email_broker)) == 0: instance.email_broker = not_avbl instance.save() return instance class EnquiryBrokerNameSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['broker_email_id'] class EnquiryAssignedUserSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['email_assigned_user'] class EnquiryInsuredNameSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['ef_insured_name'] class EnquiryObligorNameSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['ef_obligor_name'] class EnquiryCountryNameSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['el_country_name'] class EnquiryLimitSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['enquirylog_limit'] class EnquiryDecisionSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['ef_underwriter_decision'] class NotesSerializer(serializers.ModelSerializer): class Meta: model = notes fields = '__all__' </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T07:22:17.073", "Id": "520455", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<p><code>type</code> is just another type. Classes can be created in, and returned from, functions just fine. An approach kind of like</p>\n<pre><code>def basic_model_serializer(model, fields):\n _model, _fields = model, fields\n\n class _internal(serializers.ModelSerializer):\n class Meta:\n model = _model\n fields = _fields\n\n return _internal\n\nEnquiryFilterSerializer = basic_model_serializer(enquirylog, '__all__')\nEnquiryBrokerNameSerializer = basic_model_serializer(enquirylog, ['broker_email_id'])\n...\nNotesSerializer = basic_model_serializer(notes, '__all__')\n\nclass EnquirySerializer(serializers.ModelSerializer):\n ... # unchanged due to update()\n</code></pre>\n<p>would let you abstract over the few differences of the most similar classes in a pretty natural way. Is it an improvement over your existing code? Maybe in some ways, maybe not in others.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T06:35:08.027", "Id": "515929", "Score": "0", "body": "I am getting error saying Unresolved reference to 'model' and Unresolved reference to 'fields'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T06:45:55.590", "Id": "515932", "Score": "0", "body": "@Sherlock Right, sorry about that, I got it too but forgot to put my workaround in the answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T13:48:56.897", "Id": "515969", "Score": "0", "body": "Thank you I resolved the errors" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T19:48:23.747", "Id": "261435", "ParentId": "261426", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T15:52:44.647", "Id": "261426", "Score": "1", "Tags": [ "python", "database", "django", "serialization", "rest" ], "Title": "Wanted to eliminate the repetition in the classes created to reduce duplication" }
261426
<p>Hello Code Review community !</p> <p>I'm making a bot with discord.py that listens to every message sent in a server and stores it in a database that could be retrieved by admin/mod later.</p> <p>Here's the structure of the database currently</p> <pre><code>guild_id = guild.id statements = [ f&quot;&quot;&quot; CREATE TABLE guild{guild_id}_members ( id BIGSERIAL PRIMARY KEY NOT NULL, user_id bigint UNIQUE NOT NULL ); &quot;&quot;&quot;, f&quot;&quot;&quot; CREATE TABLE guild{guild_id}_messages ( id BIGSERIAL PRIMARY KEY NOT NULL, member_id INTEGER NOT NULL, at_time TIMESTAMP NOT NULL, message VARCHAR(2000) NOT NULL, CONSTRAINT fk_memberid FOREIGN KEY(member_id) REFERENCES guild{guild_id}_members(id) ON UPDATE CASCADE ON DELETE CASCADE ); &quot;&quot;&quot; ] sql_queries(self.conn, statements) </code></pre> <p>(sql_queries basically is just a function for executing each statement one after the other then commit)</p> <p>Then i use on_message event from discord.py that executes this part of the code:</p> <pre><code>@commands.Cog.listener() async def on_message(self, message): if message.content == '': #or message.author.id == self.logbot.user.id: return guild_id = message.guild.id author_id = message.author.id at_time = message.created_at statement = f&quot;&quot;&quot; INSERT INTO guild{guild_id}_members (user_id) VALUES ('{author_id}') ON CONFLICT DO NOTHING; &quot;&quot;&quot; sql_query(self.conn, statement) statement = f&quot;&quot;&quot; SELECT id FROM guild{guild_id}_members WHERE user_id = '{author_id}'; &quot;&quot;&quot; member_id = int(sql_select(self.conn, statement)[0]) print(f'{member_id}') statement = f&quot;&quot;&quot; INSERT INTO guild{guild_id}_messages (member_id, at_time, message) VALUES ('{member_id}', '{at_time}', '{message.content}') &quot;&quot;&quot; sql_query(self.conn, statement) </code></pre> <p>To explain further, first i create a user identity in my guild{guild_id}_members (with unique constraint) then i select the id through a select query to use it to insert the message with the id i just got from the select query.</p> <p>I know it's optimizable but i don't know how.</p> <p>Thank you for reading me. :)</p> <p><strong>EDIT :</strong> Here's my sql_query and my sql_select functions : Sql query :</p> <pre><code>def sql_query(conn, statement): cur = conn.cursor() cur.execute(str(statement)) conn.commit() </code></pre> <p>Sql Select :</p> <pre><code>def sql_select(conn, statement): cur = conn.cursor() cur.execute(str(statement)) return cur.fetchone() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T19:13:33.073", "Id": "515998", "Score": "0", "body": "What library does `commands.Cog.listener` come from?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T19:15:57.133", "Id": "516000", "Score": "0", "body": ">What library does `commands.Cog.listener` come from?\nIt comes from [discord.py library](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=cog#discord.ext.commands.Cog)\n>And can you show your source for sql_query\nsql query is basically 3 lines, it just executes the query then commit with the cursor" } ]
[ { "body": "<pre><code>BIGSERIAL \n</code></pre>\n<p>is a <a href=\"https://www.postgresql.org/docs/13/datatype-numeric.html#DATATYPE-SERIAL\" rel=\"nofollow noreferrer\">PostgreSQL extension</a> and non-standard. Consider instead <code>GENERATED ALWAYS AS IDENTITY</code>.</p>\n<p>Otherwise, the biggest problem with this code is that it's directly vulnerable to injection attacks. <code>message</code> is a <code>discord.Message</code> (you should typehint it as such) - I don't know how much validation it gets nor how robust it is, so the severity of this vulnerability is unclear.</p>\n<p>In PsycoPG there is a feature for prepared statements that allows for parameters to be <a href=\"https://www.psycopg.org/docs/usage.html#the-problem-with-the-query-parameters\" rel=\"nofollow noreferrer\">passed safely into queries</a>; quoting the docs:</p>\n<blockquote>\n<p>Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.</p>\n</blockquote>\n<p>Rule number one of database security is - do not format your own query parameters into a string; tell the connector to do that for you. Your <code>sql_query</code> and <code>sql_select</code> are doing more harm than good, since they can only accept a static string.</p>\n<p>Your second query can be avoided entirely by adding a <code>RETURNING</code> clause to your first query.</p>\n<p>Also it seems like you have a dynamically-generated, separate table for every different &quot;guild&quot;. This is unwise. Include the guild ID as a column on a single table instead. When this column is properly indexed, there will be no advantage to having separated tables.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T19:58:03.287", "Id": "516008", "Score": "0", "body": "Also i'm creating a table by guilds because each guild could have a giant amount of data in, why creating a table per guild is that bad ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T20:04:17.403", "Id": "516010", "Score": "0", "body": "Sorry sorry, i'm being kinda stupid right now x( Here's the documentation about [message](https://discordpy.readthedocs.io/en/stable/api.html?highlight=message#discord.Message)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T19:50:28.460", "Id": "261481", "ParentId": "261428", "Score": "2" } }, { "body": "<blockquote>\n<p>Also i'm creating a table by guilds because each guild could have a\ngiant amount of data in, why creating a table per guild is that bad ?</p>\n</blockquote>\n<p>Well, first of all it adds <strong>complexity</strong> for no real benefit. The database design is poor. There should be a single table, guild_id should simply be an additional column, and very probably you will want to <strong>index</strong> it too (unless the table is going to contain a small number of messages, in which case an index may not improve performance). With proper indexing and optimizing the table size should not matter. Also do learn about primary keys.</p>\n<p>In fact, that's the reason why you are doing <strong>dynamic SQL</strong> whereas you should be using <strong>prepared queries</strong> instead. So this is one reason why it's &quot;bad&quot;. And in 2021 there is no excuse for writing code that is vulnerable to <strong>SQL injections</strong>.</p>\n<p>I realize you have a steep learning curve ahead, but consider using an ORM, rather than doing plain SQL. For V2 perhaps.</p>\n<p>When doing multiple, related inserts, use <strong>transactions</strong> for data integrity.</p>\n<p>Avoid <strong>assumptions</strong> - if you are going to retrieve a row from a SELECT statement, make sure that the statement has succeeded and that it actually returns rows. In fact, you are expecting just one row, no more no less, anything else is an anomaly and should trigger an exception.</p>\n<p>But this SELECT statement is nonsense, because you are trying to retrieve a bit of information that should already be available.</p>\n<p>I am not familiar with psycopg but every database wrapper normally has a function to return the last row id, in Postgress this could be achieved with a RETURNING statement but please do your own research.</p>\n<p><a href=\"https://github.com/mozillazg/blog/blob/master/content/python/psycopg2-how-to-get-lastrowid-when-insert-a-new-row.md\" rel=\"nofollow noreferrer\">Example</a>:</p>\n<pre><code>&gt;&gt;&gt; cursor.execute(&quot;INSERT INTO users (username) VALUES ('hello') RETURNING id;&quot;)\n&gt;&gt;&gt; cursor.fetchone()\n(11,)\n</code></pre>\n<p>Also have a look here for more details: <a href=\"https://zetcode.com/python/psycopg2/\" rel=\"nofollow noreferrer\">https://zetcode.com/python/psycopg2/</a></p>\n<p>It's possible and even likely that an ORM like SQL Alchemy already implements the feature for you, thus easing your development efforts.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T00:36:11.600", "Id": "516032", "Score": "0", "body": "Re. _use transactions for data integrity_ - OP has `conn.commit` so implicit transactions are being used already" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T00:39:34.583", "Id": "516033", "Score": "0", "body": "Re. _It's possible and even likely that [...] SQL Alchemy [supports returning only one row]_ - not only is it possible and likely, it is implemented; see https://docs.sqlalchemy.org/en/14/orm/query.html#sqlalchemy.orm.Query.one . However, I would stop short of pushing an ORM while the OP does not yet fully understand SQL. That will introduce a kind of complexity that may end up causing more harm than good." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T21:29:26.743", "Id": "261484", "ParentId": "261428", "Score": "2" } } ]
{ "AcceptedAnswerId": "261481", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T16:14:27.173", "Id": "261428", "Score": "1", "Tags": [ "python", "sql", "postgresql", "discord" ], "Title": "A discord.py bot that logs every messages sent in a discord server" }
261428
<p>This module is the main GUI for a project I'm working on. It's not yet final, but I feel I've become somewhat blind to potential improvements / refactorings, but I'm sure there are plenty. The module started out as a mess, as I generated the code with QtDesigner. The code was neither readable nor maintainable (it's probably not meant to be), and I feel it's come a long way since then. Most text and error messages are in German, but they should be relatively irrelevant for functionality.</p> <p>This is my first time using PyQt, so I'm thankful for all types of feedback. I've intentionally left out the other project modules, as the code's already quite long and most of the functionality is completely seperate from the GUI. If a code snippet isn't clear without knowing the other modules I'd say it isn't relevant for this review. I'm mainly looking for feedback on the code structure. The one functionality still left to implement is securely storing and using the password entered by the user. Right now it's all plaintext. I'm thinking about a seperate prompt using <code>getpass</code> or similiar, any advice is welcome.</p> <pre><code>import sys import logging from typing import (Type, Callable) from pathlib import Path from io import StringIO from contextlib import (redirect_stdout, redirect_stderr) from PyQt5 import QtGui from PyQt5.QtWidgets import * from PyQt5.QtCore import (QMetaObject, QRect) from src.Backend import config_handler from src.Backend.Executors.EmailAnalyzer import EmailAnalyzer from src.Backend.Objects.exceptions import MessageException from PATHS import (ROOT_DIR, ICONS_DIR, FONTS_DIR) log = logging.getLogger(__name__) MAIN_GUI = None def show() -&gt; None: &quot;&quot;&quot; Creates and runs an instance of UIMainWindow &quot;&quot;&quot; global MAIN_GUI # do nothing if MAIN_GUI is still running if MAIN_GUI is not None: return app = QApplication(sys.argv) MAIN_GUI = UIMainWindow() MAIN_GUI.show() app.exec_() MAIN_GUI = None def get_date_list() -&gt; list[str]: &quot;&quot;&quot;Opens a QDialog box that requests a list of dates from the user&quot;&quot;&quot; if MAIN_GUI is None: raise RuntimeError(&quot;get_date_list cannot be called before running Main GUI&quot;) # only import DateListGUI if it's actually needed from src.Frontend.DateListGUI import DateListGUI dialog = DateListGUI(parent=MAIN_GUI) dialog.show() dialog.exec_() return dialog.datelist # noinspection PyAttributeOutsideInit class UIMainWindow(QMainWindow): def __init__(self): super().__init__() self.width = 1000 self.border_margin = 10 self.widget_width = self.width - 2 * self.border_margin # vertical distance between sections self.section_margin = 30 self.horizontal_separator_height = int(self.section_margin * (2 / 3)) # UI is vertically arranged self.row_height = 37 # height for each row # rows may have a text label that describes functionality / purpose self.label_width = 20 # width for each label icon_path = ICONS_DIR.joinpath(&quot;IconGUI.ico&quot;) if icon_path.exists(): self.setWindowIcon(QtGui.QIcon(icon_path.as_posix())) self.setup_fonts() self.setFont(self.font_regular) self.setup_ui() @staticmethod def load_fonts(font_files: list[str]) -&gt; None: &quot;&quot;&quot; Loads fonts from the filesystem to QFontDatabase &quot;&quot;&quot; for ttf_file in font_files: font_path = FONTS_DIR.joinpath(ttf_file) QtGui.QFontDatabase().addApplicationFont(font_path.as_posix()) def setup_fonts(self) -&gt; None: &quot;&quot;&quot; Sets attributes for regular, bold and italic font variations &quot;&quot;&quot; font_files = [&quot;OpenSans-Regular.ttf&quot;, &quot;OpenSans-Bold.ttf&quot;, &quot;OpenSans-Italic.ttf&quot;] self.load_fonts(font_files) # Only font_regular is currently in use self.font_regular = QtGui.QFont(&quot;Open Sans&quot;) self.font_bold = QtGui.QFont(&quot;Open Sans&quot;) self.font_bold.setBold(True) self.font_italic = QtGui.QFont(&quot;Open Sans&quot;) self.font_italic.setItalic(True) def setup_ui(self) -&gt; None: &quot;&quot;&quot; Creates basic UI layout and widgets &quot;&quot;&quot; # UI is created in rows from top to bottom # current_y keeps track of how far down we've come for dynamic placement current_y = self.border_margin if self.objectName(): self.setObjectName(u&quot;main_window&quot;) self.centralwidget = QWidget(self) self.centralwidget.setObjectName(u&quot;centralwidget&quot;) self.setCentralWidget(self.centralwidget) # ---------- FORM LAYOUT FOR E-MAIL SERVER DATA ---------- # form layout, will be passed as parent to all contained widgets self.widget_server_data = QWidget(self.centralwidget) self.widget_server_data.setObjectName(u&quot;widget_server_data&quot;) self.widget_server_data.setGeometry( QRect(self.border_margin, current_y, self.widget_width, self.row_height * 4)) self.form_layout_data = QFormLayout(self.widget_server_data) self.form_layout_data.setObjectName(u&quot;form_layout_data&quot;) self.form_layout_data.setContentsMargins(0, 0, 0, 0) # create widgets for form self.create_form_widget(self.widget_server_data, self.form_layout_data, QLabel, &quot;label_base_path&quot;, 0, QFormLayout.LabelRole) self.create_form_widget(self.widget_server_data, self.form_layout_data, QLabel, &quot;textlabel_base_path&quot;, 0, QFormLayout.FieldRole) self.create_form_widget(self.widget_server_data, self.form_layout_data, QLabel, &quot;label_email_address&quot;, 1, QFormLayout.LabelRole) self.create_form_widget(self.widget_server_data, self.form_layout_data, QLineEdit, &quot;textedit_email_address&quot;, 1, QFormLayout.FieldRole) self.create_form_widget(self.widget_server_data, self.form_layout_data, QLabel, &quot;label_password&quot;, 2, QFormLayout.LabelRole) self.create_form_widget(self.widget_server_data, self.form_layout_data, QLineEdit, &quot;textedit_password&quot;, 2, QFormLayout.FieldRole) self.create_form_widget(self.widget_server_data, self.form_layout_data, QCheckBox, &quot;checkbox_gui_save_password&quot;, 3, QFormLayout.FieldRole) # ---------- HORIZONTAL SEPARATOR ---------- current_y += self.widget_server_data.height() + 10 self.place_horizontal_line(parent=self.centralwidget, number=1, pos=(self.border_margin, current_y), size=(self.widget_width, self.horizontal_separator_height)) # ---------- FORM LAYOUT FOR MAIN OUTPUT ---------- current_y += self.section_margin # form layout, will be passed as parent to all contained widgets self.widget_main_output = QWidget(self.centralwidget) self.widget_main_output.setObjectName(u&quot;widget_main_output&quot;) self.widget_main_output.setGeometry( QRect(self.border_margin, current_y, self.widget_width, self.row_height * 2)) self.form_layout_main_output = QFormLayout(self.widget_main_output) self.form_layout_main_output.setObjectName(u&quot;form_layout_main_output&quot;) self.form_layout_main_output.setContentsMargins(0, 0, 0, 0) # create widgets for form self.create_form_widget(self.widget_main_output, self.form_layout_main_output, QLabel, &quot;label_main_output_directory&quot;, 1, QFormLayout.LabelRole) self.create_form_widget(self.widget_main_output, self.form_layout_main_output, QLineEdit, &quot;textedit_main_output_directory&quot;, 1, QFormLayout.FieldRole) self.create_form_widget(self.widget_main_output, self.form_layout_main_output, QPushButton, &quot;pushbutton_main_output_directory&quot;, 2, QFormLayout.FieldRole) # ---------- HORIZONTAL SEPARATOR ---------- current_y += self.widget_main_output.height() + 10 self.place_horizontal_line(parent=self.centralwidget, number=2, pos=(self.border_margin, current_y), size=(self.widget_width, self.horizontal_separator_height)) # ---------- FORM LAYOUT FOR WRITING EMAILS TO FILE ---------- current_y += self.section_margin # form layout, will be passed as parent to all contained widgets self.widget_email_output = QWidget(self.centralwidget) self.widget_email_output.setObjectName(u&quot;widget_email_output&quot;) self.widget_email_output.setGeometry( QRect(self.border_margin, current_y, self.widget_width, self.row_height * 3)) self.form_layout_email_output = QFormLayout(self.widget_email_output) self.form_layout_email_output.setObjectName(u&quot;form_layout_email_output&quot;) self.form_layout_email_output.setContentsMargins(0, 0, 0, 0) # create widgets for form self.create_form_widget(self.widget_email_output, self.form_layout_email_output, QLabel, &quot;label_email_output&quot;, 0, QFormLayout.LabelRole) self.create_form_widget(self.widget_email_output, self.form_layout_email_output, QCheckBox, &quot;checkbox_email_write_to_file&quot;, 0, QFormLayout.FieldRole) self.create_form_widget(self.widget_email_output, self.form_layout_email_output, QLabel, &quot;label_email_output_directory&quot;, 1, QFormLayout.LabelRole) self.create_form_widget(self.widget_email_output, self.form_layout_email_output, QLineEdit, &quot;textedit_email_output_directory&quot;, 1, QFormLayout.FieldRole) self.create_form_widget(self.widget_email_output, self.form_layout_email_output, QPushButton, &quot;pushbutton_email_output_directory&quot;, 2, QFormLayout.FieldRole) # ---------- HORIZONTAL SEPARATOR ---------- current_y += self.widget_email_output.height() + 10 self.place_horizontal_line(parent=self.centralwidget, number=3, pos=(self.border_margin, current_y), size=(self.widget_width, self.horizontal_separator_height)) # ---------- VERTICAL LAYOUT FOR MISC SETTINGS ---------- current_y += self.section_margin # vertical layout, will be passed as parent to all contained widgets self.widget_options = QWidget(self.centralwidget) self.widget_options.setObjectName(u&quot;widget_options&quot;) self.widget_options.setGeometry( QRect(self.border_margin, current_y, self.widget_width, self.row_height * 3)) self.vertical_layout_options = QVBoxLayout(self.widget_options) self.vertical_layout_options.setObjectName(u&quot;vertical_layout_options&quot;) self.vertical_layout_options.setContentsMargins(0, 0, 0, 0) # create widgets for vertical layout self.create_layout_widget(self.widget_options, self.vertical_layout_options, QCheckBox, &quot;checkbox_email_mark_read&quot;) self.create_layout_widget(self.widget_options, self.vertical_layout_options, QCheckBox, &quot;checkbox_output_print_timeinfo&quot;) self.create_layout_widget(self.widget_options, self.vertical_layout_options, QCheckBox, &quot;checkbox_output_print_form_counts&quot;) # ---------- HORIZONTAL SEPARATOR ---------- current_y += self.widget_options.height() + 10 self.place_horizontal_line(parent=self.centralwidget, number=5, pos=(self.border_margin, current_y), size=(self.widget_width, self.horizontal_separator_height)) # ---------- MAIN PROCEDURE BUTTONS ---------- button_width = int(self.widget_width / 2 - self.border_margin) current_y += self.section_margin self.place_pushbutton(parent=self.centralwidget, name=&quot;pushbutton_analyse_forms&quot;, pos=(self.border_margin, current_y), size=(button_width, 31)) self.place_pushbutton(parent=self.centralwidget, name=&quot;pushbutton_quit&quot;, pos=(self.border_margin * 2 + button_width, current_y), size=(button_width, 31)) # Main Window self.setCentralWidget(self.centralwidget) self.menubar = QMenuBar(self) self.menubar.setObjectName(u&quot;menubar&quot;) self.menubar.setGeometry(QRect(0, 0, self.width, 22)) self.setMenuBar(self.menubar) self.statusbar = QStatusBar(self) self.statusbar.setObjectName(u&quot;statusbar&quot;) self.setStatusBar(self.statusbar) self.setup_widgets() QMetaObject.connectSlotsByName(self) self.resize(self.width, current_y + (self.border_margin * 7)) def place_horizontal_line(self, parent: QWidget, number: int, pos: tuple[int, int], size: tuple[int, int]) -&gt; None: &quot;&quot;&quot; Places a horizontal separator line on the parent widget &quot;&quot;&quot; line = QFrame(parent) line_name = f&quot;horizontal_line{number}&quot; line.setObjectName(line_name) line.setGeometry(QRect(*pos, *size)) line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) # probably not necessary, since horizontal lines are never changed setattr(self, line_name, line) def place_pushbutton(self, parent: QWidget, name: str, pos: tuple[int, int], size: tuple[int, int]) -&gt; None: &quot;&quot;&quot; Places a QPushButton line on the parent widget &quot;&quot;&quot; button = QPushButton(parent) button.setObjectName(name) button.setGeometry(QRect(*pos, *size)) setattr(self, name, button) def create_form_widget(self, parent_widget: QWidget, parent_form: QFormLayout, widget_type: Type[QWidget], widget_name: str, form_index: int, form_role: int) -&gt; None: &quot;&quot;&quot; Creates and places a widget of widget_type on parent_form &quot;&quot;&quot; widget = widget_type(parent_widget) widget.setObjectName(widget_name) parent_form.setWidget(form_index, form_role, widget) setattr(self, widget_name, widget) def create_layout_widget(self, parent_widget: QWidget, parent_layout: QVBoxLayout, widget_type: Type[QWidget], widget_name: str) -&gt; None: &quot;&quot;&quot; Creates and places a widget of widget_type on parent_form &quot;&quot;&quot; widget = widget_type(parent_widget) widget.setObjectName(widget_name) parent_layout.addWidget(widget) setattr(self, widget_name, widget) def setup_widgets(self) -&gt; None: &quot;&quot;&quot; Sets text and connects functionality for all widgets on the main UI &quot;&quot;&quot; self.setWindowTitle(&quot;CLIENT_NAME - E-Mail Formular-Auswertung&quot;) # FORM LAYOUT --&gt; E-MAIL SERVER DATA self.label_base_path.setText(&quot;Aktueller Ordner:&quot;.ljust(self.label_width)) self.label_base_path.setFont(self.font_bold) self.textlabel_base_path.setText(ROOT_DIR.as_posix()) self.label_email_address.setText(&quot;E-Mail Adresse:&quot;.ljust(self.label_width)) self.label_email_address.setFont(self.font_bold) self.label_password.setText(&quot;Passwort:&quot;.ljust(self.label_width)) self.label_password.setFont(self.font_bold) self.connect_widget_to_setting(self.textedit_email_address, &quot;server_data&quot;, &quot;email_address&quot;) self.connect_widget_to_setting(self.textedit_password, &quot;server_data&quot;, &quot;password&quot;) # FORM LAYOUT --&gt; MAIN OUTPUT self.label_main_output_directory.setText(&quot;Ausgabe-Ordner:&quot;.ljust(self.label_width)) self.label_main_output_directory.setFont(self.font_bold) self.connect_widget_to_setting(self.textedit_main_output_directory, &quot;output&quot;, &quot;directory&quot;) self.textedit_main_output_directory.textChanged.connect(lambda t: self.replace_on_textchange(t, &quot;/&quot;, &quot;\\&quot;)) self.setup_pushbutton(self.pushbutton_main_output_directory, &quot;Ausgabe-Ordner für Formular-Auswertungen ändern&quot;, lambda: self.get_and_set_directory(self.textedit_main_output_directory)) # FORM LAYOUT --&gt; WRITE EMAIL TO FILE self.label_email_output.setText(&quot;E-Mail Ablage:&quot;.ljust(self.label_width)) self.label_email_output.setFont(self.font_bold) self.checkbox_email_write_to_file.setText(&quot;Ausgewertete E-Mails as .txt-Dateien ablegen&quot;) self.connect_widget_to_setting(self.checkbox_email_write_to_file, &quot;handle_emails&quot;, &quot;write_to_file&quot;) self.label_email_output_directory.setText(&quot;Ablage-Ordner:&quot;.ljust(self.label_width)) self.label_email_output_directory.setFont(self.font_bold) self.connect_widget_to_setting(self.textedit_email_output_directory, &quot;handle_emails&quot;, &quot;directory&quot;) self.textedit_email_output_directory.textChanged.connect(lambda t: self.replace_on_textchange(t, &quot;/&quot;, &quot;\\&quot;)) self.setup_pushbutton(self.pushbutton_email_output_directory, &quot;Ablage-Ordner für E-Mails ändern&quot;, lambda: self.get_and_set_directory(self.textedit_email_output_directory)) # VERTICAL LAYOUT --&gt; SETTINGS self.checkbox_gui_save_password.setText(&quot;Passwort speichern&quot;) self.connect_widget_to_setting(self.checkbox_gui_save_password, &quot;gui&quot;, &quot;save_password&quot;) self.checkbox_email_mark_read.setText(&quot;Ausgewertete E-Mails als gelesen markieren&quot;) self.connect_widget_to_setting(self.checkbox_email_mark_read, &quot;handle_emails&quot;, &quot;mark_read&quot;) self.checkbox_output_print_timeinfo.setText(&quot;Prozedur-Laufzeiten ausgeben&quot;) self.connect_widget_to_setting(self.checkbox_output_print_timeinfo, &quot;output&quot;, &quot;print_timeinfo&quot;) self.checkbox_output_print_form_counts.setText(&quot;Anzahl der ausgewerteten Formulare nach Formular-Typ ausgeben&quot;) self.connect_widget_to_setting(self.checkbox_output_print_form_counts, &quot;output&quot;, &quot;print_form_counts&quot;) self.setup_pushbutton(self.pushbutton_analyse_forms, &quot;Formulare aus E-Mail-Postfach auswerten&quot;, self.analyse_forms) self.setup_pushbutton(self.pushbutton_quit, &quot;Programm beenden&quot;, self.quit) def replace_on_textchange(self, text: str, to_replace: str, replace_with: str) -&gt; None: &quot;&quot;&quot; Replaces certain user inputs while typing in a QLineEdit or QTextEdit &quot;&quot;&quot; sender = self.sender() if isinstance(sender, (QLineEdit, QTextEdit)): sender.setText(text.replace(to_replace, replace_with)) @staticmethod def update_widget_from_setting(widget: QWidget, *config_keys: str) -&gt; None: &quot;&quot;&quot; Reads setting from config_handler and writes value to QWidget &quot;&quot;&quot; if isinstance(widget, QCheckBox): config_value = config_handler.get_setting(*config_keys, default=False) widget.setChecked(config_value) elif isinstance(widget, QLineEdit): config_value = config_handler.get_setting(*config_keys, default=&quot;&quot;) widget.setText(str(config_value)) elif isinstance(widget, QTextEdit): config_value = config_handler.get_setting(*config_keys, default=&quot;&quot;) widget.setText(str(config_value)) def connect_widget_to_setting(self, widget: QWidget, *config_keys: str) -&gt; None: &quot;&quot;&quot; Connects Qwidget to update a config_handler setting on every change &quot;&quot;&quot; self.update_widget_from_setting(widget, *config_keys) if isinstance(widget, QCheckBox): widget.clicked.connect(lambda c: self.update_setting_from_widget(c, *config_keys)) elif isinstance(widget, QLineEdit): widget.textChanged.connect(lambda t: self.update_setting_from_widget(t, *config_keys)) elif isinstance(widget, QTextEdit): widget.textChanged.connect(lambda t: self.update_setting_from_widget(t, *config_keys)) @staticmethod def update_setting_from_widget(value: (str, bool), *config_keys: str) -&gt; None: &quot;&quot;&quot; Wrapper for setting settings through config_handler &quot;&quot;&quot; config_handler.set_setting(value, *config_keys) @staticmethod def setup_pushbutton(pushbutton: QPushButton, text: str, click_function: Callable) -&gt; None: &quot;&quot;&quot; Sets up text and click functionality for QPushButton &quot;&quot;&quot; pushbutton.setText(text) pushbutton.clicked.connect(click_function) def get_and_set_directory(self, target_lineedit: QLineEdit) -&gt; None: &quot;&quot;&quot; Opens a QFileDialog and writes selected directory to target_lineedit &quot;&quot;&quot; sender = self.sender() # sender is a QPushButton sender.setEnabled(False) try: initial_directory = Path(target_lineedit.text()) if not initial_directory.exists(): initial_directory = ROOT_DIR user_directory = str( QFileDialog.getExistingDirectory(self, &quot;Ordner auswählen&quot;, initial_directory.as_posix())) if user_directory: target_lineedit.setText(user_directory) except Exception as e: log.exception(&quot;Unerwarteter Fehler&quot;) print(e.__str__()) sender.setEnabled(True) def analyse_forms(self) -&gt; None: &quot;&quot;&quot; Main functionality. Calls EmailAnalyzer.main and shows output in a QMessageBox &quot;&quot;&quot; # sender is QPushButton sender = self.sender() sender.setEnabled(False) self.statusBar().showMessage(&quot;E-Mail Auswertung läuft...&quot;) self.statusBar().repaint() message_box = MyMessageBox(self) message_box.setStandardButtons(QMessageBox.Ok) message_box.setDefaultButton(QMessageBox.Ok) output = StringIO() with redirect_stdout(new_target=output), redirect_stderr(new_target=output): try: EmailAnalyzer().main() message_box.setWindowTitle(&quot;E-Mail-Auswertung&quot;) message_box.setText(output.getvalue()) message_box.setIcon(QMessageBox.Information) except MessageException as e: log.exception(&quot;Erwarteter Fehler&quot;) message_box.setWindowTitle(&quot;Fehler&quot;) message_box.setText(e.message) message_box.setIcon(QMessageBox.Critical) except Exception as e: log.exception(&quot;Unerwarteter Fehler&quot;) message_box.setWindowTitle(&quot;Unerwarteter Fehler&quot;) message_box.setText(f&quot;Unerwarteter Fehler:\n&quot; f&quot;{e.__class__}\n&quot; f&quot;{e.__str__()}\n\n&quot; f&quot;Bitte die Logs an den Entwickler schicken.&quot;) message_box.setIcon(QMessageBox.Critical) self.statusBar().showMessage(&quot;Auswertung abgeschlossen&quot;) self.statusBar().repaint() message_box.exec_() self.statusBar().showMessage(&quot;Auswertung abgeschlossen&quot;, msecs=4000) sender.setEnabled(True) def closeEvent(self, event) -&gt; None: &quot;&quot;&quot; Redirects the PyQt close event to custom quit function. &quot;&quot;&quot; self.quit() def quit(self) -&gt; None: &quot;&quot;&quot; Check if password needs to be cleared, then close the GUI &quot;&quot;&quot; if config_handler.get_setting(&quot;gui&quot;, &quot;save_password&quot;, default=False) is False: config_handler.set_setting(&quot;&quot;, &quot;server_data&quot;, &quot;password&quot;) super().close() class MyMessageBox(QMessageBox): &quot;&quot;&quot; Custom MessageBox that sets its width at every event &quot;&quot;&quot; # This is a hacky workaround to be able to set the box size, which PyQt doesn't easily support # Based on: # https://stackoverflow.com/questions/2655354/how-to-allow-resizing-of-qmessagebox-in-pyqt4/2664019#2664019 # Basically, every event is caught and the width is set to self.fixedWidth # self.fixedWidth is updated every time the text changes (usually only during initialization) def __init__(self, parent): super().__init__(parent) self.fixed_width = 750 def event(self, e): result = super().event(e) self.setFixedWidth(self.fixed_width) return result def setText(self, a0: str) -&gt; None: longest_line = max(a0.split(&quot;\n&quot;), key=len) # These magic numbers are the result of manual trial and error # I found them to match the text width the most accurately, but it's far from perfect width = self.fontMetrics().boundingRect(longest_line).width() self.fixed_width = max(750, round(width * 1.4)) super().setText(a0) </code></pre>
[]
[ { "body": "<p>A random collection of things:</p>\n<ul>\n<li>As with many other syntactic contexts, <code>import (Type, Callable)</code> does not require explicit tuple notation, and such notation is only useful if the imports are so long as to span more than one line</li>\n<li>Generally want to avoid <code>import *</code>, even if it means a fairly long list of imports. Or maybe better, make a convenience alias for the module and keep everything in that namespace, like <code>import PyQt5.QtWidgets as qw</code></li>\n<li>Non-reentrant global <code>MAIN_GUI</code> is a smell, and will impede testing. <code>show</code> is at the top level and should own it, passing it down as necessary</li>\n<li><em>only import DateListGUI if it's actually needed</em> - why? Is this to avoid a known circular import, performance reasons, or other? Usually this should not be done.</li>\n<li>Under <code>setup_ui</code>, if ever you find yourself writing a <code># --------</code> partition between blocks of code, that's a big hint that you should divide the function into subroutines</li>\n<li>It's confusing that you accept multiple <code>config_keys</code> for <code>config_handler.get_setting(*config_keys</code> - maybe the documentation already explains that this is nested dictionary traversal, but if it doesn't it should. Also maybe use <code>key_path</code> for the associated argument name?</li>\n<li><code>print(e.__str__())</code> should just be equivalent to <code>print(e)</code></li>\n<li><em>These magic numbers are the result of manual trial and error</em> is, as you already know, suspicious. What are the input and output measurement units? Making this explicit would help.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T09:12:36.313", "Id": "515948", "Score": "0", "body": "Good points, I'll have to implement most of them and especially look to breaking down `setup_ui` further. For reference: `config_handler.get_setting` accepts an arbitrary number of config keys because my project config consists of nested dictionaries written to a json file. The old version of `config_handler` and an example of `config.json` can be found in [a previous question](https://codereview.stackexchange.com/questions/259380/singleton-handler-for-reading-and-writing-configuration-json). Not sure if that's even close to a best practice, that just seemed the most intuitive to me." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T21:01:45.517", "Id": "261439", "ParentId": "261430", "Score": "1" } } ]
{ "AcceptedAnswerId": "261439", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T18:11:46.173", "Id": "261430", "Score": "2", "Tags": [ "python", "python-3.x", "pyqt" ], "Title": "PyQt5 GUI for setting user configurations and calling main procedure" }
261430
<p>How can I optimize and shorten this code that I am using to display Woocommerce custom fields?</p> <pre><code>function fields() { global $product; $value1 = get_post_meta( $product-&gt;id, 'storage', true ); $value2 = get_post_meta( $product-&gt;id, 'delivery_date', true ); $value3 = get_post_meta( $product-&gt;id, 'mpn', true ); $value4 = get_post_meta( $product-&gt;id, 'color', true ); $value5 = get_post_meta( $product-&gt;id, 'sizes_available', true ); $value6 = get_post_meta( $product-&gt;id, 'country_of_origin', true ); if ( ! empty( $value1 ) ) { echo '&lt;div&gt;Storage: ' . $value1 . '&lt;/div&gt;'; } if ( ! empty( $value2 ) ) { echo '&lt;div&gt;Delivery: ' . $value2 . '&lt;/div&gt;'; } if ( ! empty( $value3 ) ) { echo '&lt;div&gt;Manufacturer's product number: ' . $value3 . '&lt;/div&gt;'; } if ( ! empty( $value4 ) ) { echo '&lt;div&gt;Color: ' . $value4 . '&lt;/div&gt;'; } if ( ! empty( $value5 ) ) { echo '&lt;div&gt;Sizes: ' . $value5 . '&lt;/div&gt;'; } if ( ! empty( $value6 ) ) { echo '&lt;div&gt;Country: ' . $value6 . '&lt;/div&gt;'; } } add_action( 'woocommerce_after_shop_loop_item', 'fields', 10 ); </code></pre> <p>There will be even more fields in the future so I would like to shorten it.</p>
[]
[ { "body": "<p>Identify that most of the code contains repeated code, then isolate the few parts of the script that change. These changing parts need to become variables in your new code.</p>\n<p>There is a direct relationship between the generated values the labels that you displaying while echoing. Create a lookup map/array containing these relationships. As you iterate the map, put the variables through the same processes as in your original script.</p>\n<pre><code>$map = [\n 'storage' =&gt; 'Storage',\n 'delivery_date' =&gt; 'Delivery',\n 'mpn' =&gt; &quot;Manufacturer's product number&quot;,\n 'color' =&gt; 'Color',\n 'sizes_available' =&gt; 'Sizes',\n 'country_of_origin' =&gt; 'Country'\n];\n\nforeach ($map as $column =&gt; $label) {\n $value = get_post_meta($product-&gt;id, $column, true);\n if ($value) {\n echo &quot;&lt;div&gt;$label: $value&lt;/div&gt;&quot;;\n }\n}\n</code></pre>\n<p>Also, <code>!empty()</code> would be an appropriate truthy check on the data if the variables might not be declared. Because you are unconditionally declaring the values, a simple/function-less truthy check will suffice.</p>\n<p>Using a map is an ideal technique, because whenever you wish to extend/manage the columns in your output, you only need to adjust the map -- there is no need to touch the processing code inside the loop.</p>\n<p>Disclaimer: I do not WordPress therefore I do not know if there is a more direct way to fetch all of the desired data without iterated calls of <code>get_post_meta()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T21:30:57.170", "Id": "261441", "ParentId": "261431", "Score": "1" } } ]
{ "AcceptedAnswerId": "261441", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T18:27:33.407", "Id": "261431", "Score": "-1", "Tags": [ "performance", "php" ], "Title": "Displaying custom fields with values" }
261431
<p>it's been two weeks since I started learning web development and am currently practicing designing a friend contact page. The problem is, I find my code very poorly optimized and can't do what I want. Do you have any suggestions on what changes I could make to my code?</p> <p>For the HTML part, I feel like I put a little too much:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Contact&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;styles.css&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;background&quot;&gt;&lt;/div&gt; &lt;div class=&quot;logo&quot;&gt; &lt;img src=&quot;img/logo.jpeg&quot;&gt; &lt;p&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;social&quot;&gt; &lt;div class=&quot;sociall&quot;&gt; &lt;ul id=&quot;ul_social&quot;&gt; &lt;a href=&quot;link&quot; target=&quot;_blank&quot;&gt;&lt;div class=&quot;sbutton&quot;&gt;&lt;li id=&quot;li_insta&quot;&gt;Instagram&lt;/li&gt;&lt;/div&gt;&lt;/a&gt; &lt;a href=&quot;link&quot; target=&quot;_blank&quot;&gt;&lt;div class=&quot;sbutton&quot;&gt;&lt;li id=&quot;li_snap&quot;&gt;Snapchat&lt;/li&gt;&lt;/div&gt;&lt;/a&gt; &lt;a href=&quot;link&quot; target=&quot;_blank&quot;&gt;&lt;div class=&quot;sbutton&quot;&gt;&lt;li id=&quot;li_tiktok&quot;&gt;Tiktok&lt;/li&gt;&lt;/div&gt;&lt;/a&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>For the CSS part, I'm not sure, I'm kinda lost. I can't seem to figure out if everything is properly organized and whether or not it's optimizing.:</p> <pre><code>/* Général */ body, html { margin: 0; padding: 0; height: 100%; width: 100%; overflow: hidden; } li{ list-style-type: none; } a{ text-decoration: none; color: white; } /* Privé */ .background{ background-image: url('img/background.png'); background-position: center; background-repeat: no-repeat; background-size: cover; height: 100%; width: 100%; filter: blur(1px); } .logo{ position: absolute; top: 5%; left:0; height: 100%; width: 100%; user-select: none; } .logo img{ display: block; height: 150px; width: 150px; margin: auto; border-radius: 300px; border-style: solid; border-color: black; } .social{ text-decoration: none; position: absolute; top: 30%; left: -1%; height: 100%; width: 100%; user-select: none; } .sociall{ display: flex; justify-content: center; } .sbutton:hover{ background-color: rgba(7, 75, 150, 0.50); } .sbutton{ width: 250px; height: 50px; background-color: rgba(255, 255, 255, 0.50); color: white; padding: 20px 20px; text-decoration: none; text-align: center; display: block; margin: 2px 4px; font-size: 30px; cursor: pointer; border-radius: 50px; border-style: solid; border-color: black; } #li_insta{ content: ''; display: block; height: 50px; width: 50px; background-size: 50px; background-image: url(&quot;img/instagram.png&quot;); background-repeat: no-repeat; padding: 10px 75px 0 75px; margin: 0 20px; } #li_snap{ content: ''; display: block; height: 50px; width: 50px; background-size: 50px; background-image: url(&quot;img/snapchat.png&quot;); background-repeat: no-repeat; padding: 10px 75px 0 75px; margin: 0 20px; } #li_tiktok{ content: ''; display: block; height: 50px; width: 50px; background-size: 50px; background-image: url(&quot;img/tiktok.png&quot;); background-repeat: no-repeat; padding: 10px 75px 0 75px; margin: 0 20px; }``` Thank you in advance for your help. </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T20:53:28.857", "Id": "515910", "Score": "1", "body": "What do you mean by poorly optimized? And what are some things you want it to do that you feel like it can't?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T07:29:34.347", "Id": "515938", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." } ]
[ { "body": "<p>First of all, you seem to arbitrarily choose between class and id selectors. It's advisable to use class selectors for everything, except when dealing with logic. Better yet, you could try following a CSS design pattern (like BEM).</p>\n<p>Moreover, you unnecessarily repeat a lot of CSS properties. For example, you could easily have created a single &quot;li_item&quot; class containing the unchanged properties then made the respective classes changing only the needed properties:</p>\n<pre class=\"lang-css prettyprint-override\"><code>.li_item {\n content: '';\n display: block;\n height: 50px;\n width: 50px;\n background-size: 50px;\n background-repeat: no-repeat;\n padding: 10px 75px 0 75px;\n margin: 0 20px;\n}\n\n.li_item--snap {\n background-image: url(&quot;img/snapchat.png&quot;);\n}\n\n.li_item--tictac {\n background-image: url(&quot;img/tictac.png&quot;);\n}\n</code></pre>\n<p>On HTML:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;li class=&quot;li_item li_item--snap&quot;&gt;Snapchat&lt;/li&gt;\n&lt;li class=&quot;li_item li_item--tictac&quot;&gt;TikTok&lt;/li&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T20:55:25.100", "Id": "261438", "ParentId": "261437", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T20:21:33.073", "Id": "261437", "Score": "-1", "Tags": [ "html", "css" ], "Title": "Some optimisations?" }
261437
<p>I've been making a brute force program for fun. This program tries to guess a password using brute force. I've tried many things to help increase the efficiency. Here it is: (Sorry for the lack of comments)</p> <pre><code>from itertools import product from time import time def findamount(find): constValues = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;, &quot;f&quot;, &quot;g&quot;, &quot;h&quot;, &quot;i&quot;, &quot;j&quot;, &quot;k&quot;, &quot;l&quot;, &quot;m&quot;, &quot;n&quot;, &quot;o&quot;, &quot;p&quot;, &quot;q&quot;, &quot;r&quot;, &quot;s&quot;, &quot;t&quot;, &quot;u&quot;, &quot;v&quot;, &quot;w&quot;, &quot;x&quot;, &quot;y&quot;, &quot;z&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot;, &quot;I&quot;, &quot;J&quot;, &quot;K&quot;, &quot;L&quot;, &quot;M&quot;, &quot;N&quot;, &quot;O&quot;, &quot;P&quot;, &quot;Q&quot;, &quot;R&quot;, &quot;S&quot;, &quot;T&quot;, &quot;U&quot;, &quot;V&quot;, &quot;W&quot;, &quot;X&quot;, &quot;Y&quot;, &quot;Z&quot;, &quot;0&quot;, &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;] dictValues = {constValues[n]:n+1 for n in range(62)} value = 0 for n in range(len(str(find))): x = len(str(find)) - (n+1) value += dictValues[find[n]] * (62**x) return value def fast(password): password = tuple(password) origtime = time() length = 1 constValues = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;, &quot;f&quot;, &quot;g&quot;, &quot;h&quot;, &quot;i&quot;, &quot;j&quot;, &quot;k&quot;, &quot;l&quot;, &quot;m&quot;, &quot;n&quot;, &quot;o&quot;, &quot;p&quot;, &quot;q&quot;, &quot;r&quot;, &quot;s&quot;, &quot;t&quot;, &quot;u&quot;, &quot;v&quot;, &quot;w&quot;, &quot;x&quot;, &quot;y&quot;, &quot;z&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot;, &quot;I&quot;, &quot;J&quot;, &quot;K&quot;, &quot;L&quot;, &quot;M&quot;, &quot;N&quot;, &quot;O&quot;, &quot;P&quot;, &quot;Q&quot;, &quot;R&quot;, &quot;S&quot;, &quot;T&quot;, &quot;U&quot;, &quot;V&quot;, &quot;W&quot;, &quot;X&quot;, &quot;Y&quot;, &quot;Z&quot;, &quot;0&quot;, &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;] for a in range(10000000): #More efficient than while True for n in product(constValues, repeat=length): if n == password: amount = findamount(''.join(list(n))) amountTime = time() - origtime if amountTime == 0: print(f&quot;Length = {length}, Amounts = {amount}\nTime elapsed = 0 secs\nAttempts per sec = ? TIME TOO SHORT&quot;) else: print(f&quot;Length = {length}, Amounts = {amount}\nTime elapsed = {amountTime} secs\n Attempts per sec (estimate) = {amount/amountTime}&quot;) print(f&quot;DONE! PASSWORD: {password}&quot;) return length += 1 if length &gt; 3: amount = findamount(''.join(n)) amountTime = time() - origtime print(f&quot;Length = {length-1}, Amounts = {amount}, Password = {''.join(n)}\nTime elapsed = {amountTime} secs\nAttempts per sec = {amount/amountTime}\nEstimated Time: {findamount(''.join(password))/(amount/amountTime)} secs&quot;) password = input(&quot;&gt;&gt;&gt; &quot;) fast(password) </code></pre> <p>My current average is 6-16M per sec. However, I want to see how to increase it on my code. I tried using <code>threading</code> and this is the attempt:</p> <pre><code>from itertools import product from time import time from threading import Thread from more_itertools import divide def findamount(find): constValues = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;, &quot;f&quot;, &quot;g&quot;, &quot;h&quot;, &quot;i&quot;, &quot;j&quot;, &quot;k&quot;, &quot;l&quot;, &quot;m&quot;, &quot;n&quot;, &quot;o&quot;, &quot;p&quot;, &quot;q&quot;, &quot;r&quot;, &quot;s&quot;, &quot;t&quot;, &quot;u&quot;, &quot;v&quot;, &quot;w&quot;, &quot;x&quot;, &quot;y&quot;, &quot;z&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot;, &quot;I&quot;, &quot;J&quot;, &quot;K&quot;, &quot;L&quot;, &quot;M&quot;, &quot;N&quot;, &quot;O&quot;, &quot;P&quot;, &quot;Q&quot;, &quot;R&quot;, &quot;S&quot;, &quot;T&quot;, &quot;U&quot;, &quot;V&quot;, &quot;W&quot;, &quot;X&quot;, &quot;Y&quot;, &quot;Z&quot;, &quot;0&quot;, &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;] dictValues = {constValues[n]:n+1 for n in range(62)} value = 0 for n in range(len(str(find))): x = len(str(find)) - (n+1) value += dictValues[find[n]] * (62**x) return value def fast(password, amountOfThreads, thread): password = tuple(password) origtime = time() length = 1 constValues = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;, &quot;f&quot;, &quot;g&quot;, &quot;h&quot;, &quot;i&quot;, &quot;j&quot;, &quot;k&quot;, &quot;l&quot;, &quot;m&quot;, &quot;n&quot;, &quot;o&quot;, &quot;p&quot;, &quot;q&quot;, &quot;r&quot;, &quot;s&quot;, &quot;t&quot;, &quot;u&quot;, &quot;v&quot;, &quot;w&quot;, &quot;x&quot;, &quot;y&quot;, &quot;z&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot;, &quot;I&quot;, &quot;J&quot;, &quot;K&quot;, &quot;L&quot;, &quot;M&quot;, &quot;N&quot;, &quot;O&quot;, &quot;P&quot;, &quot;Q&quot;, &quot;R&quot;, &quot;S&quot;, &quot;T&quot;, &quot;U&quot;, &quot;V&quot;, &quot;W&quot;, &quot;X&quot;, &quot;Y&quot;, &quot;Z&quot;, &quot;0&quot;, &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;] for a in range(10000000): #More efficient than while True (I think) for n in divide(amountOfThreads, product(constValues, repeat=length))[thread-1]: if n == password: amount = findamount(''.join(list(n))) amountTime = time() - origtime if amountTime == 0: print(f&quot;Length = {length}, Amounts = {amount}\nTime elapsed = 0 secs\nAttempts per sec = ? TIME TOO SHORT&quot;) else: print(f&quot;Length = {length}, Amounts = {amount}\nTime elapsed = {amountTime} secs\n Attempts per sec (estimate) = {amount/amountTime}&quot;) print(f&quot;DONE! PASSWORD: {password}&quot;) raise SystemExit length += 1 if length &gt; 3: amount = findamount(''.join(n)) amountTime = time() - origtime print(f&quot;Length = {length-1}, Amounts = {amount}, Password = {''.join(n)}\nTime elapsed = {amountTime} secs\nAttempts per sec = {amount/amountTime}\nEstimated Time: {findamount(''.join(password))/(amount/amountTime)} secs&quot;) password = input(&quot;&gt;&gt;&gt; &quot;) if __name__ == &quot;__main__&quot;: amountOfThreads = int(input(&quot;How much threads?&quot;)) for n in range(amountOfThreads): Thread(target=fast, args = (password, amountOfThreads, n+1)).start() </code></pre> <p>It gets much slower. If you input 1 thread it does 2-3M per sec and 2+ threads in total does about 200k per sec (totalling all threads). Is there any way to improve this code to allow <code>threading</code> to be useful, or any other efficient code I should add? Also, is <code>threading</code> the most efficient way to do this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T06:50:33.990", "Id": "516052", "Score": "1", "body": "The constraint in the program is computation, not IO. Using threads, as you discovered, won't help (search for the Python GIL). Instead see the multiprocessing library." } ]
[ { "body": "<p>I've found a few ways to improve my code:</p>\n<ol>\n<li><p>Instead of doing <code>for a in range(10000000):</code> and <code>length += 1</code>, you can just merge the two and do <code>for length in range(1, 10000000):</code>. This would help increase efficiency because in the previous case, <code>a</code> would be <code>length-1</code>, meaning if I use <code>range(1, 10000000)</code> (meaning <code>a</code> starts at 1 instead of 0), <code>a</code> would be equal to <code>length</code>.</p>\n</li>\n<li><p>The second improvement is in this code:</p>\n</li>\n</ol>\n<pre><code>if length &gt; 3: \n amount = findamount(''.join(n))\n amountTime = time() - origtime\n print(f&quot;Length = {length}, Amounts = {amount}, Password = {''.join(n)}\\nTime elapsed = {amountTime} secs\\nAttempts per sec = {amount/amountTime}\\nEstimated Time: {findamount(''.join(password))/(amount/amountTime)} secs&quot;)\n</code></pre>\n<p><code>''.join(n)</code> is calculated twice, I could just do <code>currentPassword = ''.join(n)</code> so <code>''.join(n)</code> would only be calculated once, and use <code>currentPassword</code> for the two times I used <code>''.join(n)</code>.</p>\n<ol start=\"3\">\n<li>This improvement is also on the code above. the <code>print</code> part can be improved. This isnt an efficiency improvement, but a readability improvement. Changing the <code>print</code> function to:</li>\n</ol>\n<pre><code>print(f&quot;Length = {length}, Amounts = {amount}, Password = {currentAmount}\\nTime elapsed = {amountTime} secs&quot;,\n&quot;\\nAttempts per sec = {amount/amountTime}\\nEstimated Time: {findamount(''.join(password))/(amount/amountTime)} secs&quot;)\n</code></pre>\n<p>I'll update this every time I find something new.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T08:52:25.977", "Id": "261458", "ParentId": "261440", "Score": "1" } } ]
{ "AcceptedAnswerId": "261458", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T21:28:53.773", "Id": "261440", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "multithreading" ], "Title": "Brute Force Password Program / Python 3.9" }
261440
<p>Write a program that uses an ADT Stack to evaluate arithmetic expressions in RPN format. The contents of the stack should be displayed on the screen during evaluation. The allowed arithmetic operators are +, -, x, and /.</p> <p>What I have done so far:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string.h&gt; using namespace std; struct Stack { int top; unsigned cap; int* arr; }; struct Stack* createStackFun(unsigned capacity) { struct Stack* s = (struct Stack*) malloc(sizeof(struct Stack)); if (!s) return NULL; s-&gt;top = -1; s-&gt;cap = capacity; s-&gt;arr = (int*)malloc(s-&gt;cap * sizeof(int)); if (!s-&gt;arr) return NULL; return s; } int isEmpty(struct Stack* stack) { return stack-&gt;top == -1; } char peek(struct Stack* stack) { return stack-&gt;arr[stack-&gt;top]; } char pop(struct Stack* stack) { if (!isEmpty(stack)) return stack-&gt;arr[stack-&gt;top--]; return '$'; } void push(struct Stack* stack, char op) { stack-&gt;arr[++stack-&gt;top] = op; } int postfixEvaluation(char* exp) { // Create a stack of capacity equal to expression size struct Stack* stack = createStackFun(strlen(exp)); int i; // See if stack was created successfully if (!stack) return -1; // Scan all characters one by one for (i = 0; exp[i]; ++i) { // If the scanned character is an operand (number here), push it to the stack. if (isdigit(exp[i])) push(stack, exp[i] - '0'); // If the scanned character is an operator, pop two elements from stack apply the operator else { int val1 = pop(stack); int val2 = pop(stack); switch (exp[i]) { case '+': push(stack, val2 + val1); break; case '-': push(stack, val2 - val1); break; case '*': push(stack, val2 * val1); break; case '/': push(stack, val2 / val1); break; } } } return pop(stack); } int main() { char expression[] = &quot;74*+8-&quot;; cout &lt;&lt; &quot;Postfix Evaluation: &quot; &lt;&lt; postfixEvaluation(expression); return 0; } </code></pre> <p>The problem:</p> <p>I am not sure if this is correct and I don't know if there is a way to shorten the code or make it better.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T14:35:24.320", "Id": "516145", "Score": "0", "body": "That is C code and idioms, except for the use of `cout`. Was this really meant for the C language?" } ]
[ { "body": "<blockquote>\n<pre><code>#include &lt;string.h&gt;\n</code></pre>\n</blockquote>\n<p>It's better to include <code>&lt;cstring&gt;</code>, which declares all the identifiers in the <code>std</code> namespace. .... Unless you do this:</p>\n<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n<p>which denies you all the advantages of namespaces. So don't do that.</p>\n<blockquote>\n<pre><code> struct Stack* s = (struct Stack*) malloc(sizeof(struct Stack));\n</code></pre>\n</blockquote>\n<p>This looks like C code, assuming that <code>std::malloc()</code>, from <code>&lt;cstdlib&gt;</code>, is intended. Why are you not using <code>new</code> here - or better, on of C++'s smart pointers? The subsequent initialisation looks like it really belongs in <code>Stack</code>'s constructor which would entirely remove the need for this factory function.</p>\n<p>The corresponding <code>free()</code> seems to be entirely absent, meaning that this program leaks memory. And the capacity is never checked, meaning that it is vulnerable to overflow.</p>\n<p>All in all, I see no reason not to use a <code>std::stack</code> here, rather than poorly implementing our own.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T08:02:47.463", "Id": "261453", "ParentId": "261443", "Score": "1" } }, { "body": "<p>C and C++ are two different languages. Since we're using <code>&lt;iostream&gt;</code> it's clear that this is C++ (although the <code>Stack</code> struct is created in a very C-like fashion).</p>\n<hr />\n<pre><code>#include &lt;string.h&gt; \n</code></pre>\n<p>Since this is C++, if we want the C++ version of functions from the C standard library, we should include the <code>&lt;cstring&gt;</code> header. This header puts the contents into the <code>std</code> namespace.</p>\n<p>Alternatively, we can use the C++ <code>std::string</code> class, which is in the <code>&lt;string&gt;</code> header.</p>\n<hr />\n<pre><code>using namespace std;\n</code></pre>\n<p>This is a bad habit to get into, even in small programs, as it can lead to name collisions. We should qualify names fully where we need to, e.g. <code>std::cout</code>.</p>\n<hr />\n<pre><code>struct Stack\n{\n int top;\n unsigned cap;\n int* arr;\n};\n</code></pre>\n<p>The <code>push</code>, <code>pop</code>, and <code>peek</code> functions all use <code>char</code>s, but the <code>Stack</code> contains an array of <code>int</code>s. We should probably use <code>int</code> consistently throughout.</p>\n<p>Note that the C++ standard library <a href=\"https://en.cppreference.com/w/cpp/container/stack\" rel=\"nofollow noreferrer\">already contains a stack class</a>. So we don't need to write our own.</p>\n<hr />\n<pre><code>struct Stack* createStackFun(unsigned capacity)\n{\n struct Stack* s = (struct Stack*) malloc(sizeof(struct Stack));\n if (!s) return NULL;\n s-&gt;top = -1;\n s-&gt;cap = capacity;\n s-&gt;arr = (int*)malloc(s-&gt;cap * sizeof(int));\n if (!s-&gt;arr) return NULL;\n return s;\n}\n</code></pre>\n<p>C++ doesn't have a separate namespace for <code>struct</code> types, so we can just write <code>Stack*</code> instead of <code>struct Stack*</code>.</p>\n<p>Since this is C++, we should be using <code>new</code> and <code>delete[]</code>, not <code>malloc</code> and <code>free</code>. (Well... actually we shouldn't be doing manual memory management at all).</p>\n<p>There's no need to create the Stack itself on the heap with <code>malloc</code>. We can use a simple local variable, and return it by value. Only the <code>arr</code> memory needs to be allocated on the heap.</p>\n<p>The stack pointer we return from this function is never freed, and neither are its resources! We should have an equivalent <code>destroyStack</code> function to clean up when we don't need it any more.</p>\n<p>Since this is C++, we should be using a constructor and destructor instead of free functions.</p>\n<pre><code>Stack(unsigned capacity):\n top(-1),\n cap(capacity),\n arr(new int[cap])\n{\n \n}\n\n~Stack()\n{\n delete[] arr;\n}\n</code></pre>\n<p><code>new</code> will throw an exception if allocation fails, so we don't need to manually check for a null value.</p>\n<p>Note that we would also have to think about copy and move operations on the class. The easiest thing to do is tell the compiler not to allow them:</p>\n<pre><code>Stack(Stack const&amp;) = delete; // no copy-construction\nStack&amp; operator=(Stack const&amp;) = delete; // no copy-assignment\nStack(Stack&amp;&amp;) = delete; // no move-construction\nStack&amp; operator=(Stack&amp;&amp;) = delete; // no move-assignment\n</code></pre>\n<hr />\n<pre><code>int isEmpty(struct Stack* stack)\n{\n return stack-&gt;top == -1;\n}\n\nchar peek(struct Stack* stack)\n{\n return stack-&gt;arr[stack-&gt;top];\n}\n\nchar pop(struct Stack* stack)\n{\n if (!isEmpty(stack))\n return stack-&gt;arr[stack-&gt;top--];\n return '$';\n}\n\nvoid push(struct Stack* stack, char op)\n{\n stack-&gt;arr[++stack-&gt;top] = op;\n}\n</code></pre>\n<p>In C++, these can be member functions. The class pointer is passed implicitly as the <code>this</code> pointer. So we can write them as:</p>\n<pre><code>bool isEmpty() const\n{\n return (top == -1);\n}\n\nvoid push(int op)\n{\n arr[++top] = op;\n}\n</code></pre>\n<p>Note that member functions that don't change the member variables of the class should be marked <code>const</code> to indicate this.</p>\n<hr />\n<pre><code>int postfixEvaluation(char* exp)\n</code></pre>\n<p>For C++, we should usually use a <code>std::string</code> rather than a raw <code>char*</code>. This stores the length of the string along with the data, so we don't have to use <code>strlen</code>, which iterates through the whole string to find the null character at the end:</p>\n<pre><code>int postfixEvaluation(std::string exp)\n{\n Stack stack(exp.size());\n</code></pre>\n<hr />\n<pre><code>int i;\n</code></pre>\n<p>We don't use this variable outside the <code>for</code> loop. So we should just do:</p>\n<pre><code>for (int i = 0; exp[i]; ++i)\n</code></pre>\n<hr />\n<pre><code> if (isdigit(exp[i])) ...\n</code></pre>\n<p>For C++, <a href=\"https://en.cppreference.com/w/cpp/string/byte/isdigit\" rel=\"nofollow noreferrer\"><code>isdigit</code> is in the <code>std::</code> namespace</a> and we should include the <code>&lt;cctype&gt;</code> header to use it. Unfortunately, we also have to cast the argument to <code>unsigned char</code> before using it:</p>\n<pre><code> if (std::isdigit(static_cast&lt;unsigned char&gt;(exp[i]))) ...\n</code></pre>\n<hr />\n<pre><code> // If the scanned character is an operator, pop two elements from stack apply the operator\n else\n {\n char val1 = stack.pop();\n char val2 = stack.pop();\n switch (exp[i])\n {\n case '+': \n stack.push(val2 + val1); \n break;\n case '-': \n stack.push(val2 - val1); \n break;\n case '*': \n stack.push(val2 * val1); \n break;\n case '/': \n stack.push(val2 / val1); \n break;\n }\n }\n</code></pre>\n<p>It's possible that we were given an invalid RPN string (such as the one in the question!). Currently the program silently ignores invalid input, giving the user no indication that the answer they get out is incorrect. We definitely need to warn them!</p>\n<p>So we need to do a couple of extra steps here:</p>\n<ul>\n<li><p>Check that there are actually two values in the stack to pop (we could add a <code>getSize()</code> member function to the stack class), warn the user if there aren't and stop the program.</p>\n</li>\n<li><p>Check for an invalid character in the RPN string (we can add a <code>default</code> case to the switch statement to catch such characters), warn the user and stop the program.</p>\n</li>\n</ul>\n<p>One other thing to be careful of is if the user supplies an empty string. We can't pop a value off the stack in that case! So we should probably check for this at the top of <code>postfixEvaluation</code> and return 0.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T08:08:22.583", "Id": "261454", "ParentId": "261443", "Score": "2" } }, { "body": "<p>The earlier replies have already pointed out that this is C code, top to bottom, and is not at all the way you would write in C++.</p>\n<p>Since there is already a <a href=\"https://en.cppreference.com/w/cpp/container/stack\" rel=\"nofollow noreferrer\"><code>std::stack</code></a> in the standard library, I'll just go over the one function you actually had to write to implement your parser.</p>\n<pre><code>int postfixEvaluation(char* exp)\n</code></pre>\n<p>Your input is not modified, so <strong>use const</strong>. But really, don't pass as a <code>char*</code> at all, but use <code>std::string_view</code>.</p>\n<pre><code> // Create a stack of capacity equal to expression size \n struct Stack* stack = createStackFun(strlen(exp));\n</code></pre>\n<p>That becomes: <code>std::stack&lt;int&gt; stack;</code><br />\nNote that you don't have to pre-define a capacity, and you don't use pointers; rather, the class instance is a local variable directly.</p>\n<pre><code> // See if stack was created successfully \n if (!stack) return -1;\n</code></pre>\n<p>It will be, or an exception will be thrown. With the <code>std::stack</code> constructor, if the code got here there is no error, period.</p>\n<pre><code> int i;\n ...\n // Scan all characters one by one \n for (i = 0; exp[i]; ++i)\n</code></pre>\n<p>First of all, you don't need to declare your variables at the top of the function. Even in C, that has not been necessary since C90. Don't!! Declare variables when you are ready to initialize them.</p>\n<p>Here, you don't even need <code>i</code> at all, as we'll see next.</p>\n<p>To scan the characters one by one, use a range-based <code>for</code> loop: <code>for (const auto c : exp)</code> then in the body of the loop you will get <code>c</code> set to the next char in turn, so use that instead of <code>exp[i]</code>. BTW, it is &quot;not nice&quot; that you repeated <code>exp[i]</code> all over the place instead of getting the value out of it once.</p>\n<pre><code> // If the scanned character is an operand (number here), push it to the stack. \n if (isdigit(exp[i]))\n push(stack, exp[i] - '0');\n</code></pre>\n<p>That's reasonable, given that you only allow single-digit numbers in your input.\nLikewise, the math part is reasonable, but needs to be converted to use the member function calls on <code>std::stack</code>.</p>\n<p>So, your actual &quot;real work&quot; logic is fine. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T14:49:34.973", "Id": "261548", "ParentId": "261443", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T23:28:15.200", "Id": "261443", "Score": "2", "Tags": [ "c++", "calculator", "stack" ], "Title": "C++ evaluating an arithmetic expression in RPN format using ADT stack" }
261443
<p>I'm porting <a href="https://stackoverflow.com/questions/30143082/how-to-get-color-value-from-gradient-by-percentage-with-javascript">this code</a> to Java and after a few tests all seems ok but I need to know if I'm doing this right.</p> <p>The code takes some colors and create a color ramp for maps and other stuff. You can see the original Javascript version <a href="http://jsfiddle.net/vksn3yLL/" rel="nofollow noreferrer">working here</a>.</p> <p>I removed the &quot;slider&quot; part and fixed the amplitude to 0..100 for color ramp and 0..1 for levels.</p> <pre><code>package br.com.cmabreu.color; import java.awt.Color; import java.util.ArrayList; import java.util.List; public class ColorGradientGenerator { private List&lt;ColorItem&gt; gradient; public ColorGradientGenerator() { this.gradient = new ArrayList&lt;ColorItem&gt;(); } public void addToGradient( int index, int red, int green, int blue, int alpha ) throws Exception { if( index &gt; 100 ) throw new Exception(&quot;Index must be &lt;= 100&quot;); if( index &lt; 0 ) throw new Exception(&quot;Index must be &gt;= 0&quot;); Color color = new Color(red,green,blue,alpha); gradient.add( new ColorItem( index, color ) ); } public void removeFromGradient( int index ) { gradient.remove(index); } private ColorItem getItemZero() throws Exception { for ( ColorItem colorItem : gradient ) { if( colorItem.getIndex() == 0 ) return colorItem; } throw new Exception(&quot;Cannot find lower bound color&quot;); } public Color getColorAt( double value ) throws Exception { ColorItem firstColor = null, secondColor = null; double firstColorX, secondColorX; value = value * 100; int iVal = (int)value; firstColor = getItemZero(); for ( ColorItem colorItem : gradient ) { if( iVal &lt;= colorItem.getIndex() ) { secondColor = colorItem; break; } else { firstColor = colorItem; } } if( secondColor == null ) throw new Exception(&quot;Cannot find upper bound color&quot;); firstColorX = firstColor.getIndex(); secondColorX = secondColor.getIndex() - firstColorX; double sliderX = (double)iVal - (double)firstColorX; double ratio = 0.0; if( secondColor.getIndex() &gt; 0) { ratio = sliderX / (double)secondColorX; } // System.out.println(&quot;Sx: &quot; + sliderX + &quot; Fc: &quot; + firstColor.getIndex() + &quot; Sc: &quot; + secondColor.getIndex() + &quot; Ratio: &quot; + ratio ); return pickHex( firstColor.getColor(), secondColor.getColor(), ratio); } private Color pickHex( Color firstColor, Color secondColor, double weight ) { double w = weight * 2 - 1; double w1 = ( w / 1+1 ) / 2; double w2 = 1 - w1; long red = Math.round( secondColor.getRed() * w1 + firstColor.getRed() * w2 ); long green = Math.round( secondColor.getGreen() * w1 + firstColor.getGreen() * w2 ); long blue = Math.round( secondColor.getBlue() * w1 + firstColor.getBlue() * w2 ); String hex = String. format(&quot;#%02X%02X%02X&quot;, red, green, blue); System.out.println( red + &quot;,&quot; + green + &quot;,&quot; + blue + &quot; || &quot; + hex ); return new Color( (int)red, (int)green, (int)blue ); } } </code></pre> <p>You can invoke the class this way: Prepare some colors to sample. Must have a zero index and 100 index do create a very simple gradient. By adding colors in the middle of this range you can create nice gradients.</p> <pre><code> public static void main(String[] args) { ColorGradientGenerator cg = new ColorGradientGenerator(); try { cg.addToGradient(0, 128, 64, 0, 255); cg.addToGradient(50, 58, 168, 69, 255); cg.addToGradient(100, 255, 255, 255, 255); cg.getColorAt(0.0); cg.getColorAt(0.5); cg.getColorAt(0.8); cg.getColorAt(1.0); } catch (Exception e) { e.printStackTrace(); } } </code></pre> <p>What I need to know is: Am I forgot to cover something that will lead to an error? My concern is about the things I changed/removed from the original code.</p> <p>Another thing: a value of 0.8 for example will not put you at 80% of the color ramp. I can't think a global way to do this. Instead will put you at 80% of the gradient made by the color pair near (that match) 80% of the sample colors.</p> <p>Lets see:</p> <p>In the example I've created a ramp using 3 colors:</p> <pre><code> cg.addToGradient(0, 128, 64, 0, 255); // #804000 cg.addToGradient(50, 58, 168, 69, 255); // #3aa845 cg.addToGradient(100, 255, 255, 255, 255); // #FFFFFF </code></pre> <p>So, 0.8 will take the last pair because 80 is between 100 and 50 ( lower #3aa845 and upper #FFFFFF), create a gradient and give you the color at 80% of this ( #B0DCB5 ).</p> <p><strong>EDIT : This is the ColorItem class</strong></p> <pre><code>package br.com.cmabreu.color; import java.awt.Color; public class ColorItem { private int index; private Color color; public ColorItem( int index, Color color ) { this.color = color; this.index = index; } public Color getColor() { return color; } public int getIndex() { return index; } } </code></pre>
[]
[ { "body": "<p>First, a naming nitpick. I don't think your class is a gradient <em>generator</em> so much as just being a <em>gradient</em> in and of itself. You could just call it <code>Gradient</code>. At that point <code>addToGradient</code> and <code>removeFromGradient</code> can just be <code>add</code> and <code>remove</code> as well</p>\n<p>You <code>throw Exception</code> in multiple places. That's generally not a great thing to do, because it means that while programs using your API can tell when something goes wrong, they can't tell why, which is inconvenient. It would be much more convenient if the exceptions had more specific types. <code>IllegalArgumentException</code> seems like a good fit for <code>addToGradient</code> and some uses of <code>getColorAt</code>. As for <code>getItemZero</code>... well, <code>IllegalStateException</code> isn't a terrible fit, but I don't think exceptions are necessarily the best way to go here at all</p>\n<p>The way you described it, a gradient <em>must</em> have colors that map to indices 0 and 100. If nobody would ever want to have a gradient without those, we can design the gradient class so that they won't need to worry about whether the gradient they have is in a usable state or not! If the constructor for a <code>ColorGradientGenerator</code> were to demand two <code>Color</code>s (one for 0 one for 100) and if we made sure they couldn't be removed later (by <code>removeFromGradient</code> or by other means), our library will keep all its functionality and the user won't have to worry about running into those particular errors. If the domain we're working in has rules, it's often good to have the computer keep track of those so we humans don't have to do it ourselves.</p>\n<p>It also looks like there's no limit to how many colors you can have at the same index, which is a bit weird. And users have to deal with both the gradient index when making gradients and an index into the internal <code>ArrayList</code> when removing colors, which I think could get confusing. And a gradient of [(0, red), (20, blue), (100, green)] might not be the same as one of [(0, red), (100, green), (20, blue)], which I also wouldn't expect, and making sure they always behave the same feels like it might be hard (I think the current <code>getColorAt</code> might sometimes get that wrong). I feel like those are all signs that we're not using the right data structure for the job. We want something that stays in some kind of order even as we update it, mapping sparse index values to one value (a <code>Color</code>) each, or maybe two of them. That doesn't sound very much like like an <code>ArrayList&lt;ColorItem&gt;</code> to me, but it <em>does</em> sound a lot like a <code>TreeMap&lt;Integer, Color&gt;</code>! Or, perhaps, something more like a <code>TreeMap&lt;Integer, Pair&lt;Color, Color&gt;&gt;</code>. Either way by using a <code>TreeMap</code> we better represent the domain and we even get methods like <code>floorKey</code> and <code>ceilingKey</code> that let us find whichever keys are closest to some index of our choice, which seems like it could be <em>very</em> useful for implementing <code>getColorAt</code></p>\n<h3>Edit</h3>\n<p>Wait, I'm a bit confused by the start of <code>pickHex</code>. As far as I can tell those first two expressions, for all their operators, don't <em>do</em> anything. Dividing by 1 shouldn't do anything, and all the other operations should cancel out. But maybe I'm missing something. If there is a reason why those first two lines look like that, I'd <em>really</em> suggest adding a comment to explain them, and if there isn't I'd just replace them with <code>double w1 = weight;</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T02:45:51.590", "Id": "515922", "Score": "0", "body": "WOW!! Many thanks ... it was very detailed!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T09:36:55.333", "Id": "515952", "Score": "2", "body": "\"*It also looks like you can have multiple colors at the same index. Which is a bit weird.*\" The OP's code indeed has some weirdness in it, but in general allowing up to two colors at the same index in a color gradient is a desirable feature, since it allows the color to [change discontinuously](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Images/Using_CSS_gradients#Creating_hard_lines) at that point in the gradient." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T21:29:32.093", "Id": "516014", "Score": "0", "body": "Many thanks to all of you. I'll try to do my best to improve this code as you said. But for those that want to contribute to this \"weirdness\" here is the repo: https://github.com/icemagno/rampcreator" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T21:33:08.020", "Id": "516015", "Score": "0", "body": "@Sara J for your edit: I have no time to lapidate the original JS code in search for this kind of madness ( like the w/1+1) ... just need to solve my Java problem fast. The source of original code is in the question for comparation. Although this have potential to be a good tool I may need some help to polish it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T17:13:08.483", "Id": "516095", "Score": "0", "body": "@MagnoC But the `w/1 + 1` is not from the JS code. That simply does `w1 = weight` as she suggests." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T21:12:32.333", "Id": "516109", "Score": "1", "body": "@mdfst13 look here: http://jsfiddle.net/vksn3yLL/ line ```55```. Although found this very strange I decide to do not modify to avoid inject errors in to Java transcription. I'm afraid of black magic." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T02:27:03.763", "Id": "261449", "ParentId": "261447", "Score": "6" } } ]
{ "AcceptedAnswerId": "261449", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T01:05:10.647", "Id": "261447", "Score": "4", "Tags": [ "java", "algorithm" ], "Title": "Colour ramp for maps" }
261447
<p>I have this function at the moment</p> <pre><code> def isConnected(adjacencyListMap: Map[String, Seq[String]]): Boolean = { // Simple BFS to check whether each vertex is connected val visitedMap = mutable .Map[String, Boolean]() ++= adjacencyListMap.keys.map(vertex =&gt; vertex -&gt; false).toMap val seen = mutable.Stack[String]() seen.push(adjacencyListMap.keys.head) while (seen.nonEmpty) { val v = seen.pop() visitedMap.put(v, true) val adjacentVertices = adjacencyListMap(v) adjacentVertices.foreach(adjVertex =&gt; { if (!visitedMap(adjVertex)) { visitedMap.put(adjVertex, true) seen.push(adjVertex) } }) } // If all vertices are visited then we know all vertices are connected in 1 component visitedMap.values.reduce(_ &amp;&amp; _) } </code></pre> <p>The function in essence takes in a Map where each vertex is a key and all adjacent vertices to that vertex are values. We basically do a BFS and at the end check whether all vertices were visited, if they were then we know that graph is one component and connected, if not then it is not connected.</p> <p>How would I go about making this code more immutable (i.e. the mutable <code>seen</code> Stack and mutable <code>visitedMap</code> HashMap)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T08:58:21.533", "Id": "516119", "Score": "0", "body": "Welcome to Code Review bigfocalchord. Are you only interested in improving the immutability of your code? How would you feel if someone were to post a helpful answer, but not comment on immutability?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T11:56:36.350", "Id": "516124", "Score": "0", "body": "I am happy with both! @Peilonrayz :)" } ]
[ { "body": "<p><strong>completeness</strong></p>\n<p>Code posted to <em>Code Review</em> should be complete, correct, and ready for review. You've got everything here except for the <code>import</code> statement needed to allow the mutable collections to compile. Sample input would also be nice but I was able to make do (I think).</p>\n<p><strong>layout</strong></p>\n<p>The code is organized and well presented but I do find it a bit unusual the way <code>mutable.Map[...</code> has been split. It requires a double-take to read and understand, and it doesn't really help balance the lengths of the two lines. After the <code>++=</code> would make more sense.</p>\n<p><strong>Scala idioms</strong></p>\n<p>Replace <code>map(vertex =&gt; vertex -&gt; false)</code> with <code>map(_ -&gt; false)</code>.</p>\n<p>A <code>Map[String, Boolean]</code>, i.e. <code>visitedMap</code>, almost exactly imitates the function of a <code>Set[String]</code>, where membership is either <strong>true</strong> or <strong>false</strong>. You'd have to flip its meaning to <code>notVisited</code> and then remove each element as it gets visited. With that the final result would simply be <code>notVisited.isEmpty</code>.</p>\n<p>Single-use variables can be useful to help document the data transformations, but in this case I don't think that <code>val adjacentVertices</code> serves much purpose. The more concise...</p>\n<pre><code>adjacencyListMap(v).foreach(adjVertex =&gt;\n</code></pre>\n<p>...is equally as obvious as to what's being done.</p>\n<p>You've got an excess (unneeded) pair of braces, <code>{</code> and <code>}</code>, surrounding the <code>if</code> statement.</p>\n<p>Instead of reducing all the <code>visitedMap</code> values to a single boolean, all you really want to know is if there are any <strong>false</strong> values left behind: <code>visitedMap.forall(_._2)</code></p>\n<p><strong>immutable</strong></p>\n<p>You're right, a cornerstone of Functional Programming is the use of immutable data. A common way to achieve this is via a recursive method that uses only immutable variables but passes updated data to each iteration.</p>\n<pre><code>def isConnected(adjacencyListMap: Map[String, Seq[String]]): Boolean = {\n def loop(from:Set[String], to:Set[String]): Boolean =\n if (from.isEmpty) to.isEmpty\n else (loop _).tupled(to.partition(from.flatMap(adjacencyListMap)))\n\n val keys = adjacencyListMap.keySet\n loop(Set(keys.head), keys.tail)\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T11:57:29.667", "Id": "516125", "Score": "0", "body": "Thank you for such a great answer! I am relatively new to Scala so your tips really help me nicer and functional code :D\n\nI'll leave this question up for another few days before I tick this as answered." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T22:34:41.033", "Id": "261529", "ParentId": "261448", "Score": "4" } } ]
{ "AcceptedAnswerId": "261529", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T01:34:45.183", "Id": "261448", "Score": "1", "Tags": [ "graph", "scala" ], "Title": "Checking whether a graph is connected in an immutable way" }
261448
<p>Below is the code for merge sort using multithreading. Will this code run for large number of inputs? Does any other part of the code need changing?</p> <pre><code>#include&lt;iostream&gt; #include&lt;thread&gt; #include&lt;mutex&gt; #include&lt;vector&gt; #include&lt;functional&gt; #include&lt;fstream&gt; std::mutex mut; void merge(std::vector&lt;int&gt;&amp; vec,int s,int mid,int e){ std::vector&lt;int&gt; lvec,rvec; for(int i=s;i&lt;=e;i++){ mut.lock(); if(i&lt;=mid) lvec.push_back(vec[i]); else rvec.push_back(vec[i]); mut.unlock(); } int a=0,b=0,c=s; while(a&lt;lvec.size()&amp;&amp;b&lt;rvec.size()){ if(lvec[a]&lt;rvec[b]){ vec[c++]=lvec[a++]; } else vec[c++]=rvec[b++]; } while(a&lt;lvec.size()){ vec[c++]=lvec[a++]; } while(b&lt;rvec.size()){ vec[c++]=rvec[b++]; } } void mergeSort(std::vector&lt;int&gt;&amp; vec,int s,int e){ if(s&gt;=e) return; int mid=(s+e)/2; std::thread th1(std::bind(mergeSort,std::ref(vec),s,mid)); std::thread th2(std::bind(mergeSort,std::ref(vec),mid+1,e)); th1.join(); th2.join(); merge(vec,s,mid,e); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T09:08:40.130", "Id": "515947", "Score": "0", "body": "`mu.lock()/unlock()` is probably going to be a bottleneck for large `e` - also why not use something like this for your partitioning sub-vector creation .. https://www.cplusplus.com/reference/algorithm/partition/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T09:16:34.320", "Id": "515949", "Score": "0", "body": "`mu.lock()/unlock() is probably going to be a bottleneck for large e ` so do I need to change it ? can I use a lock_guard instead ?. How do I need to change my code using subvector?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T09:29:00.370", "Id": "515950", "Score": "2", "body": "Did you test it for large inputs? If not, why not?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T09:33:21.713", "Id": "515951", "Score": "0", "body": "I did check it which seemed fine but just asking if this code can improved anywhere or will it fail for large inputs" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T10:24:21.667", "Id": "515954", "Score": "0", "body": "Also do you mean \"large sized vector\" or vector with large values in it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T10:26:23.150", "Id": "515957", "Score": "0", "body": "@MrR large sized vector say n=10000" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T10:29:41.970", "Id": "515958", "Score": "0", "body": "Okay n=10000 is not what I'd call large :-) Even if int is 8byte - that can be represented in less than 100Kbytes of RAM. WRT to the mutex - just do a significant portion for 1 grab of it, rather than grab/release for 1 element ... Infact what's the mutex protecting there (against two independant threads filling their own independant sub-vectors????)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T10:50:31.163", "Id": "515960", "Score": "0", "body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T10:55:04.547", "Id": "515961", "Score": "0", "body": "@MrR So can I use the mutex for whole function then or remove it? I used mutex here to ensure thread safety so it doesn't cause any problems in pushback" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T10:55:32.813", "Id": "515962", "Score": "0", "body": "@TobySpeight It is correct." } ]
[ { "body": "<h3>Summary</h3>\n<p>Because the number of threads that a system can create is finite, if your data set is large enough eventually the <code>thread</code> constructor will throw an exception (<code>system_error</code>) when a thread cannot be created. There is also a performance hit when creating a thread, so making threads for very small intervals is counterproductive.</p>\n<h3>merge</h3>\n<p>When copying elements into the local vectors <code>lvec</code> and <code>rvec</code>, you are copying elements sequentially. Using one loop to copy all the elements adds extra overhead and is unnecessary. You can use two loops (and reserve memory space for each), use an appropriate vector constructor (that takes a pair of iterators), or use the <code>insert</code> function to block copy elements from one vector to another. Reserving space for the vector, instead of allowing it to grow, will reduce the contention in the memory allocator (which is not concurrent, creating a bottleneck when two threads both try to allocate memory).</p>\n<p>Since you are writing to local vectors, and reading from a region of <code>vec</code> that is only being read by the current thread, the mutex is unnecessary.</p>\n<p>To avoid repeated calculation of the size, store <code>lvec.size()</code> and <code>rvec.size()</code> in local variables. Or you can use iterators for all vector accesses. The two loops that finish copying the tail elements from <code>lvec</code> or <code>rvec</code> can use vector's <code>insert</code> function.</p>\n<p>There is also some inconsistent indentation in the code, and inconsistent use of braces for single-line <code>if</code>/<code>else</code> blocks.</p>\n<p>There may be a slight performance hit if multiple threads are writing to elements in <code>vec</code> that are near each other (that share a cache line), but this should be rare and with appropriate choice of range to not create threads (see below) should be avoidable.</p>\n<h3>mergesort</h3>\n<p>Thread creation is expensive, and the number of threads available in a system is finite. Once the number of running threads exceeds the number available in hardware, there is no performance gain from creating more (and usually a slight hit).</p>\n<p>Therefore, once the interval to sort is small enough (64 or 128 elements), make recursive calls directly, rather than create threads for them. Also including an upper limit on the number of threads to create would avoid the penalty of creating threads that will not execute right away. Determination of appropriate values for these limits would require experimentation to check the effect on the performance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T16:44:58.173", "Id": "515980", "Score": "0", "body": "`if your data set is large enough eventually the thread constructor will throw an exception` is there a way to handle this" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T14:41:21.793", "Id": "261471", "ParentId": "261456", "Score": "4" } }, { "body": "<h1>Limiting the number of threads spawned</h1>\n<p>As already mentioned, there is a limit to how many threads can be spawned, but it also doesn't make sense for CPU-bound workloads to spawn much more threads than the number of hardware threads that your system has. You can query the number of hardware threads using <a href=\"https://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency\" rel=\"nofollow noreferrer\"><code>std::thread::hardware_concurrency()</code></a>.</p>\n<p>There are many ways you could ensure the number of threads spawned is limited, but in this case I think the appropriate thing to do is to limit thread spawning to a certain recursion depth of <code>mergeSort()</code>. Every level of recursion doubles the number of running threads, so if you pass the number of currently running threads as a parameter to <code>mergeSort()</code>, it will be able to track this. For example:</p>\n<pre><code>void mergeSort(std::vector&lt;int&gt;&amp; vec, int s, int e, unsigned int cur_threads = 1) {\n if(s &gt;= e)\n return;\n int mid = (s + e) / 2;\n\n static const unsigned int max_threads = std::thread::hardware_concurrency();\n\n if (cur_threads &lt; max_threads) {\n std::thread thr(mergeSort, std::ref(vec), s, mid, cur_threads * 2);\n // No need to create a second thread if we are going to block anyway\n mergeSort(std::ref(vec), mid + 1, e, cur_threads * 2);\n thr.join();\n } else {\n mergeSort(std::ref(vec), s, mid, cur_threads);\n mergeSort(std::ref(vec), mid + 1, e, cur_thread);\n }\n\n merge(vec, s, mid, e);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T04:32:55.910", "Id": "516048", "Score": "0", "body": "why is that you are not creating a second thread, could you explain it a little more. If I don't have a lock ,then can I create another thread too?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T06:52:26.293", "Id": "516053", "Score": "0", "body": "@Zebra You can create a second thread, but if you are going to wait for two threads to join, the original thread is not doing anything useful. So why not have it do some of the work as well?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T19:25:31.567", "Id": "261479", "ParentId": "261456", "Score": "4" } }, { "body": "<p>There are a few things to do:</p>\n<ol>\n<li><p>Perform all the standard optimizations also common for single-threaded merge-sort:</p>\n<ol>\n<li><p>Switch to intro-sort below a threshold.</p>\n</li>\n<li><p>Ensure only a single scratch-buffer is ever allocated per thread, all those allocate/deallocate operations are a monumental waste of time.</p>\n</li>\n</ol>\n</li>\n<li><p>Limit threads. When all the cores are hard at work, adding more threads slows everything down.</p>\n</li>\n<li><p>Get rid of the locking. Currently, you don't need any. All the global lock does is removing the concurrency you so enthusiastically introduced. I would be astounded if it doesn't lower the throughput below that of single-threading the code (remove lock, call synchronously instead of starting threads).</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:37:16.363", "Id": "261508", "ParentId": "261456", "Score": "3" } }, { "body": "<pre><code> std::vector&lt;int&gt; lvec,rvec;\n for(int i=s;i&lt;=e;i++){\n mut.lock();\n if(i&lt;=mid)\n lvec.push_back(vec[i]);\n else\n rvec.push_back(vec[i]);\n mut.unlock();\n }\n</code></pre>\n<p>You are locking each <code>push_back</code> to the vectors defined as local variables. How can other threads be manipulating the same vectors?</p>\n<p>It's also using a global mutex for all threads, which will pretty much destroy any threading benefit.</p>\n<p>Use a scoped lock rather than direct <code>lock</code> and <code>unlock</code> calls.</p>\n<p>Don't repeat the whole thing when only a variable changes: Break out the choice of <code>lvec</code> or <code>rvec</code> in the condition, and then have one copy of the expression that uses it. E.g.</p>\n<pre><code>auto&amp; side= i&lt;=mid ? lvec : rvec;\nside.push_back(vec[i]);\n</code></pre>\n<p>But looking at that when I typed it, I realized that you are choosing based on <code>i</code> not the value (<code>vec[i]</code>). <code>i</code> is just counting up. So you should just copy the first half of <code>vec</code> to <code>left</code> as one statement and copy the other half to <code>right</code> as one statement. That can be further improved: if you copy off <code>right</code> to another vector, then just call <code>vec.resize</code> to turn it into what you wanted in <code>left</code>, with no copying needed.</p>\n<p>Your leftover is doing the same thing: just copy the entire rest of <code>lvec</code> or <code>rvec</code> with a single call each. Don't write a loop.</p>\n<p>Your create two new threads and then immediately join them. That means that the original thread is doing nothing, and is just wasted overhead of having created it. You have two parallel things to do; put half in a new thread and do the other half in <em>this</em> thread. This will have the identical effect, but without the overhead of more thread creation/joining.</p>\n<p>Finally, nobody ever sorts a simple vector of <code>int</code>. Make your code useable for real work by making it a template argument. You can use <code>int</code> in your testing, but the code is ready to use with other types.</p>\n<p>Also, if you look at the standard algorithms, <code>sort</code>, <code>stable_sort</code>, etc. are defined to take <em>iterators</em>, and are not limited to <code>std::vector</code>. You are passing in index positions (as <code>int</code>, not as the type that <code>vector</code> actually uses for indexing) to allow sorting part of a <code>vector</code>, as this is needed by your recursive approach. But it works more naturally if you just used begin/end iterators, and don't need to pass the collection at all.</p>\n<p>That is, make the signature look like <code>std::sort</code>.<br />\nI suggest you review what's in the <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\">algorithm header</a> so you're familiar with what's in there, and can reach for those instead of writing loops from scratch for simple operations.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T14:03:06.023", "Id": "261513", "ParentId": "261456", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T08:47:52.987", "Id": "261456", "Score": "3", "Tags": [ "c++", "multithreading", "thread-safety", "mergesort" ], "Title": "Multi-threaded merge sort" }
261456
<p>Project Euler 7: What is the 10 001st prime number?</p> <p>I currently have this code:</p> <pre><code>let primesfound = 0; for(i=0;i&lt;Number.MAX_SAFE_INTEGER;i++){ if(isPrime(i)){ primesfound++ } if(primesfound==10001){ console.log(i) break; } else{ console.log(i + `and ${primesfound} found`) //testing line } } </code></pre> <p>but it's taking ages! There has to be a way to do it faster.</p> <p>The <code>isPrime()</code> function:</p> <pre><code> function isPrime(num){ if(num&lt;2){ return false; } for(a=2;a&lt;=num/2;a++){ if(!(num%a)){ return false; } } return true; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T13:02:44.530", "Id": "515967", "Score": "1", "body": "https://www.github.com/strikersps/Competitive-Programming/tree/master/Project-Euler%2F10001st-Prime-Number" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T20:08:28.743", "Id": "520511", "Score": "0", "body": "The fastest method for getting the 10001st prime number is to store that prime number and just reply it. Practical applications which use prime numbers use pre calculated prime numbers from tables." } ]
[ { "body": "<p>Testing every integer using trial division is probably the slowest way to find primes.</p>\n<p>Change the algorithm to use one of the standard <em>prime number sieves</em> (e.g. Sieve of Eratosthenes).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T10:54:40.467", "Id": "261461", "ParentId": "261459", "Score": "1" } }, { "body": "<p>I am not a javascript developer so most of this answer will focus on the algorithm rather than specific language usage.</p>\n<p>There are some simple algorithmic improvements you can make without changing your entire algorithm. Firstly, there is a simple one - do you need to check every single number under n/2? Once you've checked if <code>2</code> is a divisor, there is no need to check if every following even number is a divisor. If <code>2</code> was a divisor, then you've already found out that <code>n</code> is not prime, and if <code>2</code> was not a divisor, then none of the even numbers will be divisors. To do this, I would add a simple edge case for <code>n % 2 == 0</code> and <code>n == 2</code>, which would half the time taken.</p>\n<p>Another improvement is that you don't need to check up to <code>n / 2</code> - the highest number you need to check is <code>sqrt(n)</code>, as <code>sqrt(n)^2 == n</code>. This will be a significant speedup for larger primes.</p>\n<p>Another slightly more complicated speedup could be achieved by using the fact that all primes past 2 &amp; 3 are of the form <code>6n ± 1</code> - so they're all either one above or one below a multiple of 6. To check primes this way, you can simply increase <code>a</code> by 6 each time, and then check if the numbers one below or one above a are factors of <code>n</code>. In terms of programming, it'd be easiest to start at 5, then check if <code>a</code> was a factor, or if <code>a + 2</code> was. In pseudocode, the algorithm with all the above improvements might look something like:</p>\n<pre><code># check edge cases first\nif number is less than 2:\n return false\nif number is 2 or 3:\n return true\nif number is divisible by 2 or 3:\n return false\n\nlet upper_limit = integer_sqrt(num) + 1\nfor i from 5 to upper_limit in steps of 6:\n if (num is divisible by i) or (num is divisible by i + 2):\n return false\n \nreturn true\n</code></pre>\n<p>This might not be enough to make it fast enough though, in which case using another algorithm would be the way to go.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T11:29:25.880", "Id": "261463", "ParentId": "261459", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T09:13:24.680", "Id": "261459", "Score": "1", "Tags": [ "javascript", "performance", "programming-challenge", "primes" ], "Title": "Find the 10001st prime number" }
261459
<pre class="lang-py prettyprint-override"><code>from itertools import cycle # Integers represent Chinese characters main_text = &quot;234458674935346547521456767378878473562561423&quot; text_with_commentary = &quot;2344586749215432678652353465475214561655413164653413216576737887847356152352561423&quot; iter_main = iter(main_text) iter_comm = iter(text_with_commentary) marked_up = [] x = next(iter_main) y = next(iter_comm) i = 0 j = 0 def commentary_start(): global x, y, i, j, marked_up while x == y and j &lt; len(text_with_commentary): try: marked_up.append(y) x = next(iter_main) y = next(iter_comm) i += 1 j += 1 except: return marked_up.append(&quot;{{&quot;) return marked_up def commentary_end(): global x, y, i, j, marked_up while x != y: marked_up.append(y) y = next(iter_comm) j += 1 if main_text[i+1] == text_with_commentary[j+1] and \ main_text[i+2] == text_with_commentary[j+2]: marked_up.append(&quot;}}&quot;) else: marked_up.append(y) y = next(iter_comm) j += 1 commentary_end() return marked_up def mark_up_commentary(): global marked_up while j &lt; len(text_with_commentary): try: commentary_start() commentary_end() except: break marked_up = &quot;&quot;.join(marked_up) return marked_up mark_up_commentary() # Expected result: &quot;2344586749{{215432678652}}35346547521456{{16554131646534132165}}76737887847356{{15235}}2561423&quot; </code></pre> <p>The above code compares two sets of strings, character by character, to markup commentary text that is interspersed between the main text.</p> <p>The code makes use of the iterators <code>iter_main</code> and <code>inter_comm</code> to check if the next character in the commented text is the same as the next character of the main text, adding double braces to mark up commentary text that deviates from the main text at the relevant positions.</p> <p>I would like to seek help to improve the code in these respects:</p> <ol> <li>See if the code can be made more concise and efficient.</li> <li>The current method is actually quite hard-coded and mechanical, which makes little room for minor deviations in the texts, which is actually unavoidable in the real world. I would hence like to know whether fuzzy text-comparison tools that make use of concepts such as Levenshtein distance can be implemented to make the code more robust and flexible.</li> <li>Are there good libraries to recommend for the task?</li> </ol>
[]
[ { "body": "<blockquote>\n<p>Are there good libraries to recommend for the task?</p>\n</blockquote>\n<p>Yes, and it's built-in: read about <code>difflib</code>.</p>\n<blockquote>\n<p>I would hence like to know whether fuzzy text-comparison tools [...] can be implemented</p>\n</blockquote>\n<p>Off-topic for CodeReview.</p>\n<p>Avoid globals, use <code>difflib</code>, and this becomes</p>\n<pre><code>from difflib import SequenceMatcher\nfrom typing import Iterable\n\n\ndef diff(main_text: str, text_with_commentary: str) -&gt; Iterable[str]:\n matcher = SequenceMatcher(a=main_text, b=text_with_commentary, autojunk=False)\n for op, a0, a1, b0, b1 in matcher.get_opcodes():\n right = text_with_commentary[b0: b1]\n if op == 'equal':\n yield right\n elif op == 'insert':\n yield '{' + right + '}'\n else:\n raise ValueError(f&quot;{op} indicates malformed text&quot;)\n\n\ndef test():\n actual = ''.join(\n diff(\n main_text=(\n &quot;2344586749&quot;\n &quot;35346547521456&quot;\n &quot;76737887847356&quot;\n &quot;2561423&quot;\n ),\n text_with_commentary=(\n &quot;2344586749&quot;\n &quot;215432678652&quot;\n &quot;35346547521456&quot;\n &quot;16554131646534132165&quot;\n &quot;76737887847356&quot;\n &quot;15235&quot;\n &quot;2561423&quot;\n ),\n )\n )\n\n expected = (\n &quot;2344586749&quot;\n &quot;{215432678652}&quot;\n &quot;35346547521456&quot;\n &quot;{16554131646534132165}&quot;\n &quot;76737887847356&quot;\n &quot;{15235}&quot;\n &quot;2561423&quot;\n )\n assert actual == expected\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T14:17:31.720", "Id": "515972", "Score": "0", "body": "Could you explain the logic of the code to me? This is the first time I've come across a generator function. Seems like I am supposed to use it with `''.join([i for i in diff(main_text, text_with_commentary)])`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T14:24:44.337", "Id": "515973", "Score": "1", "body": "Close, but it would just be `''.join(diff(....))`. It's just yielding strings that the user can choose to do with it what they like - join, or otherwise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T14:51:17.463", "Id": "515976", "Score": "0", "body": "What does `Iterable[str]` at the function annotation do? Is it there just to indicate that this function returns an iterable string?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T14:55:54.720", "Id": "515978", "Score": "0", "body": "An iterable of strings - in other words, if you `for x in diff()`, `x` will be a string on each iteration." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T02:40:25.110", "Id": "516039", "Score": "0", "body": "The variables `op, a0, a1, b0, b1` seem to map to my globals `marked_up, x, y, i, j`, but not exactly. What are the differences between these two sets of variables other than globality?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T03:02:02.170", "Id": "516041", "Score": "0", "body": "They have totally different purposes. Read about `get_opcodes` here: https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher.get_opcodes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T04:05:12.030", "Id": "516044", "Score": "1", "body": "`SequenceMatcher(None, a, b)` would return a tuple that describes how string `a` transcribes to string `b`. `op` is the tag, while `a0, a1` and `b0, b1` are the position indicators of the stretch of matching or mismatching strings between `a` and `b`. Is this understanding correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T13:10:13.370", "Id": "516081", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/124949/discussion-between-reinderien-and-sati)." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T13:27:15.477", "Id": "261468", "ParentId": "261462", "Score": "3" } } ]
{ "AcceptedAnswerId": "261468", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T11:14:01.563", "Id": "261462", "Score": "2", "Tags": [ "python", "strings", "iterator" ], "Title": "Compare strings to markup commentary in main text" }
261462
<p>Take the <code>words</code> dataset from <code>stringr</code>. <a href="https://r4ds.had.co.nz/strings.html#exercises-38" rel="nofollow noreferrer">An R4DS exercise</a> challenges the reader to check if there are any words in that dataset that contain every vowel. My presumably correct solution, using five calls to <code>str_detect</code>, was as follows:</p> <pre><code>library(stringr) words[apply(sapply(c(&quot;a&quot;, &quot;e&quot;, &quot;i&quot;, &quot;o&quot;, &quot;u&quot;), function(x) str_detect(words, x)), 1, all)] </code></pre> <p>Under the restriction that we must call <code>str_detect</code> exactly five times, once for each vowel, is there a better way to do this? The <code>sapply</code> seems like the right idea - it produces a 980*5 logical matrix with each row being a logical vector showing if the corresponding vowel was in the corresponding word. Collapsing it with <code>all</code> also seems like the right idea, but any time that I have to call <code>apply</code> rather than any other member of the apply family or something like <code>Filter</code>, I become concerned about my approach. R's higher-order functions typically work best by column rather than by row and <code>apply</code> is a sign that I've failed to work like that.</p> <p>Suggestions from either base R or the Tidyverse will be accepted. My primary reason for asking this question is that I have a strong feeling that the <code>apply</code> could have been avoided, perhaps by construction the logical matrix differently.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T07:24:12.413", "Id": "516182", "Score": "0", "body": "Hello, you wrote that the code you presented is a presumably correct solution for your problem, have you tested it ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T16:51:40.330", "Id": "516225", "Score": "0", "body": "@dariosicily Yes. It gives the output that I expect. However, one can never be certain when working with this many data points." } ]
[ { "body": "<p><strong>Sample data</strong></p>\n<pre class=\"lang-r prettyprint-override\"><code>vowels &lt;- c(&quot;a&quot;, &quot;e&quot;, &quot;i&quot;, &quot;o&quot;, &quot;u&quot;)\ninput &lt;- c(&quot;aeiou&quot;, &quot;uoiea&quot;, &quot;aeiouc&quot;, &quot;aeioo&quot;, &quot;coeiauc1&quot;, &quot;eu&quot;)\n</code></pre>\n<hr />\n<p><strong>Solution 1. Use <code>reduce</code> and <code>&amp;</code></strong></p>\n<p>These create 5 vectors, but only have 2 loaded at a time.</p>\n<pre class=\"lang-r prettyprint-override\"><code># 1A: with str_detect\ninput[Reduce(function(x, y) x &amp; str_detect(input, y), vowels, init = TRUE)]\n\n# 1B: with grepl\ninput[Reduce(function(x, y) x &amp; grepl(y, input), vowels, init = TRUE)]\n</code></pre>\n<p><strong>Solution 2. Use positive lookaheads</strong></p>\n<p>You can find a complete explanation <a href=\"https://regex101.com/r/XgRgxz/1\" rel=\"nofollow noreferrer\">here</a>. We are essentially checking for the presence of all the vowels.</p>\n<pre class=\"lang-r prettyprint-override\"><code># 2A: with str_detect\ninput[str_detect(input, &quot;(?=.*?a)(?=.*?e)(?=.*?i)(?=.*?o)(?=.*?u)&quot;)]\n\n# 2B: with grep\ngrep(&quot;(?=.*?a)(?=.*?e)(?=.*?i)(?=.*?o)(?=.*?u)&quot;, input, perl = TRUE, value = TRUE)\n</code></pre>\n<p><strong>Solution 3. Use <code>strsplit</code> and <code>match</code></strong></p>\n<p>We can split all the words into individual characters, and then compare <code>vowels</code> to the letters of each word. All letters that aren't matched become <code>0</code>. Since <code>0</code> converts to <code>FALSE</code> as a logical, we can use <code>all</code> to see if all vowels are present.</p>\n<pre class=\"lang-r prettyprint-override\"><code>input[sapply(strsplit(input, &quot;&quot;), function(x) all(match(vowels, x, nomatch = 0L)))]\n</code></pre>\n<p><strong>Solution 4. <code>lapply</code> and <code>grep</code></strong></p>\n<p>We can also choose to generate a vector for each vowel, but just a short one, as <code>grep</code> will only return the indices for which the conditions apply. We then use <code>Reduce</code> and <code>intersect</code> to get our answer. Alternatively, we can use skip <code>lapply</code> (solution 4B), but this is slower.</p>\n<pre class=\"lang-r prettyprint-override\"><code># 4A: with lapply\nReduce(intersect, lapply(vowels, grep, input, value = TRUE))\n\n# 4B: without lapply\nReduce(function(x, y) intersect(x, grep(y, input, value = TRUE)), vowels, init = input)\n</code></pre>\n<hr />\n<p><strong>Benchmark of all solutions</strong></p>\n<pre class=\"lang-r prettyprint-override\"><code>Unit: microseconds\n expr min lq mean median uq max neval cld\n original(words) 1766.7 1936.75 2238.6696 2082.7 2237.00 60182.5 10000 f\n solution_1a(words) 706.7 746.10 839.5126 802.6 868.70 4362.7 10000 c \n solution_1b(words) 492.5 515.40 586.4063 555.5 605.15 30031.6 10000 a \n solution_2a(words) 779.4 817.20 906.0936 875.8 940.55 29357.0 10000 d \n solution_2b(words) 707.4 737.70 819.2046 790.7 854.10 3072.7 10000 c \n solution_3(words) 1226.4 1376.55 1667.8316 1470.9 1600.95 76907.0 10000 e \n solution_4a(words) 592.2 641.00 736.0374 689.4 755.20 29589.7 10000 b \n solution_4b(words) 649.5 704.20 805.9942 757.8 828.80 31104.2 10000 c \n</code></pre>\n<p>Memory allocation with <code>bench::mark</code>:</p>\n<pre class=\"lang-r prettyprint-override\"><code> Code Memory allocation (KB)\n1 original(words) 100.15\n2 solution_1a(words) 42.63\n3 solution_1b(words) 42.63\n4 solution_2a(words) 7.76\n5 solution_2b(words) 3.88\n6 solution_3(words) 38.96\n7 solution_4a(words) 75.67\n8 solution_4b(words) 106.70\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T20:55:17.207", "Id": "518497", "Score": "0", "body": "I suspect that in many places, `grepl` would serve you better than `grep`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T21:00:35.643", "Id": "518499", "Score": "0", "body": "A quick benchmark shows that `input[grepl(...)]` is slightly slower than `grep(..., values = TRUE)`, although only by a fraction. Either way, it doesn't lead to any gains." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T12:03:17.753", "Id": "518610", "Score": "1", "body": "Are you sure that we cannot `Reduce`+`intersect` the logical vectors? If the corresponding word contains all five vowels, then all five of the logical vector entries should be `TRUE`. In order to avoid the five `FALSE`s case, we could intersect with a literal `TRUE` via `Reduce`'s `init` argument." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T12:53:20.803", "Id": "518618", "Score": "0", "body": "You're absolutely right, thanks :) I revamped the whole post. It now contains 4 solutions (some with sub-solutions). I also benchmarked on `words` now instead of on `input`. I also added a memory allocation benchmark, just out of curiosity." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T20:24:43.673", "Id": "262696", "ParentId": "261464", "Score": "2" } } ]
{ "AcceptedAnswerId": "262696", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T11:50:11.730", "Id": "261464", "Score": "2", "Tags": [ "strings", "functional-programming", "regex", "r" ], "Title": "Find if a dataset of words contains any words containing all vowels by using exactly 5 calls to str_detect" }
261464
<h2>Background</h2> <p>I am doing an exercise in clojure to make a function that can determine if a number is an <a href="https://web.archive.org/web/20171228054132/https://everything2.net/index.pl?node_id=1407017&amp;displaytype=printable&amp;lastnode_id=1407017" rel="nofollow noreferrer">Armstrong Number</a> or not.</p> <p>The solution I came up with us a bit more complicated than it would be if there was not a requirement to take 17 digit numbers which start to cause calculation errors with Math/pow etc...</p> <h2>Tests</h2> <pre><code>(ns armstrong-numbers-test (:require [clojure.test :refer [deftest is testing]] [armstrong-numbers :refer [armstrong?]])) (deftest armstrong-number-9926315 (testing &quot;Seven digit number that is an Armstrong number&quot; (is (armstrong? 9926315)))) (deftest not-armstrong-number-9926314 (testing &quot;Seven digit number that is not an Armstrong number&quot; (is (not (armstrong? 9926314))))) (deftest armstrong-number-21897142587612075 (testing &quot;Seventeen digit number that is an Armstrong number&quot; (is (armstrong? 21897142587612075)))) </code></pre> <h2>My Solution</h2> <pre><code>(ns armstrong-numbers) (defn less-than-one? [input] (&lt; input 1)) (defn one-tenth [input] (/ (- input (mod input 10)) 10)) (defn for-every-digit [input accumulator accumulator-function] (if (less-than-one? input) accumulator (for-every-digit (one-tenth input) (accumulator-function input accumulator) accumulator-function))) (defn pow-by-reduction [x n] (reduce * (repeat n x))) (defn armstrong? [num] (let [num-digits (for-every-digit num 0 (fn [input accumulator] (+ accumulator 1)))] (== num (for-every-digit num 0 (fn [input accumulator] (+ accumulator (pow-by-reduction (mod input 10) num-digits))))))) </code></pre> <h2>Update</h2> <p>I worked on it some more, and got it down to this which I am pretty happy with...</p> <pre><code>(ns armstrong-numbers) (defn one-tenth [input] (/ (- input (mod input 10)) 10)) (defn pow-by-reduction [x n] (reduce * (repeat n x))) (defn armstrong? [num] (== num (let [seq (map (fn [x] (mod x 10)) (take-while (fn [x] (&gt;= x 1)) (iterate one-tenth num)))] (apply + (map (fn [x] (pow-by-reduction x (count seq))) seq))))) </code></pre>
[]
[ { "body": "<p>Here is how I would code it. It takes a lot of care to properly account for BigInteger values. We will use the <a href=\"https://guava.dev/releases/23.0/api/docs/com/google/common/math/BigIntegerMath.html\" rel=\"nofollow noreferrer\">Google Guava BigInteger lib</a> to augment what we get from Java:</p>\n<pre><code>(ns tst.demo.core\n (:use tupelo.core tupelo.test)\n (:import\n [java.math RoundingMode]\n [com.google.common.math BigIntegerMath]\n ))\n\n(defn num-digits\n [n]\n (let [n (biginteger n)]\n (inc (BigIntegerMath/log10 n RoundingMode/DOWN))))\n\n(dotest\n (is= 1 (num-digits 1))\n (is= 1 (num-digits 9))\n (is= 2 (num-digits 10))\n (is= 2 (num-digits 99))\n (is= 3 (num-digits 100))\n (is= 3 (num-digits 999))\n (is= 4 (num-digits 1000))\n (is= 4 (num-digits 5555)))\n</code></pre>\n<p>I like to write the tests inline at first. We need a custom remainder function since Guava doesn't have one</p>\n<pre><code>(defn bigint-quot-rem\n [n d]\n (let [n (biginteger n)\n d (biginteger d)\n quot (BigIntegerMath/divide n d RoundingMode/DOWN)\n rem (- n (* quot d))]\n [quot rem]))\n\n(dotest\n (is= [1 2] (bigint-quot-rem 5 3))\n (is= [2 0] (bigint-quot-rem 6 3)))\n</code></pre>\n<p>Then a function to extract the digits of the number</p>\n<pre><code>(defn digits\n [n]\n (assert (pos? n))\n (loop\n [accum []\n value (biginteger n)]\n (if (zero? value)\n (mapv biginteger (reverse accum))\n (let [[value-next last-digit] (bigint-quot-rem value 10)\n accum-next (append accum last-digit)]\n (recur accum-next value-next)))))\n\n(dotest\n (is= [3 1 4] (digits 314))\n (is= [1] (digits 1))\n (is= [1 3] (digits 13)))\n</code></pre>\n<p>and finally we can test for the armstrong property</p>\n<pre><code>(defn armstrong?\n [n]\n (let [n (bigint n)\n ndigits (num-digits n)\n digits (digits n)\n digits-exp (mapv #(.pow % ndigits)\n digits)\n powsum (apply + digits-exp)\n result (= n powsum)]\n result))\n\n(dotest\n\n (is= 3 (num-digits 151))\n (isnt (armstrong? 151))\n (is (armstrong? 153))\n (isnt (armstrong? 154))\n\n (is (armstrong? 9926315))\n (isnt (armstrong? 9926314))\n\n (is (armstrong? 4679307774N))\n (is (armstrong? 28116440335967N))\n (is (armstrong? 63105425988599693916N))\n (is (armstrong? 188451485447897896036875N))\n (is (armstrong? 115132219018763992565095597973971522401N))\n\n (is (armstrong? 21897142587612075N))\n )\n</code></pre>\n<p>with result</p>\n<pre><code>-----------------------------------\n Clojure 1.10.3 Java 15.0.2\n-----------------------------------\n\nTesting tst.demo.core\n\nRan 5 tests containing 25 assertions.\n0 failures, 0 errors.\n</code></pre>\n<p>The above is using <a href=\"https://github.com/io-tupelo/clj-template\" rel=\"nofollow noreferrer\">my favorite template project</a>. Extra test values are from</p>\n<p><a href=\"https://codegolf.stackexchange.com/questions/83272/all-armstrong-numbers\">https://codegolf.stackexchange.com/questions/83272/all-armstrong-numbers</a></p>\n<p>Note also that, in Clojure, <code>bigint</code> is different than <code>biginteger</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T13:19:03.087", "Id": "261467", "ParentId": "261466", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T12:40:05.327", "Id": "261466", "Score": "1", "Tags": [ "clojure" ], "Title": "Verify Armstrong Number in Clojure" }
261466
<p>I made a maze generator in python that outputs in CLI. With mazes that are extremely big, it can take a while to output. I want to know if there is any way to increase the efficiency of this code. Here it is:</p> <pre><code>import random def mgen(size=3, disallowedcoords = [[]]): try: def canmove(coords, size, coordslist, disallowedcoords, coordsarray): actuallist = [] for n in range(len(coordsarray)): actuallist.append(coordsarray[n][0:2]) actuallist.extend(coordslist) actuallist.extend(disallowedcoords) canmoveto = [] if len(coords) == 3: coords = coords[0:2] #--------------------NORTH CHECK-------------------- if [coords[0], coords[1]+1] not in actuallist and coords[1]+1 != size: canmoveto.append(0) #--------------------EAST CHECK -------------------- if [coords[0]+1, coords[1]] not in actuallist and coords[0]+1 != size: canmoveto.append(3) #--------------------SOUTH CHECK-------------------- if [coords[0], coords[1]-1] not in actuallist and coords[1]-1 == abs(coords[1]-1): canmoveto.append(2) #--------------------WEST CHECK -------------------- if [coords[0]-1, coords[1]] not in actuallist and coords[0]-1 == abs(coords[0]-1): canmoveto.append(1) #RETURN: return canmoveto def move(coords, direction): if direction == 0: return [coords[0], coords[1]+1] if direction == 1: return [coords[0]-1, coords[1]] if direction == 2: return [coords[0], coords[1]-1] if direction == 3: return [coords[0]+1, coords[1]] else: raise Exception(&quot;ERROR CODE: 0001. DIRECTION NOT IN 0-3.&quot;) previouscoords = [-1, -1, -1] coords = [random.randint(0, size-1), random.randint(0, size-1), -1] while coords[0:2] in disallowedcoords: coords = [random.randint(0, size-1), random.randint(0, size-1), -1] coordsarray = [] coordslist = [] coordsarray.append(coords) coordslist.append([coords[0], coords[1]]) success = 0 iterations = 0 backtrack = 0 while len(coordsarray)-1 != size**2: movement = canmove(coords, size, coordslist, disallowedcoords, coordsarray) if len(movement) != 0: previouscoords = coords startback = False iterations += 1 direction = movement[random.randint(0, len(movement)-1) if len(movement) &gt; 1 else 0] coords = move([coords[0], coords[1]], direction) coords.append(direction) coordslist.append(coords[0:2]) coordsarray.append(coords[:]) success += 1 if len(movement) == 0: backtrack += 1 coords = coordslist[(len(coordslist)-1)] del coordslist[len(coordslist)-1] except Exception as e: return coordsarray def displaymaze(coords, size, grasschance=0, brokenwallchance=0, questionchance=0): linkcoords = [] for n in range(len(coords)): linkcoords.append([(coords[n][0]*2)+1, (coords[n][1]*2)+1]) for n in range(len(coords)): if coords[n][2] == -1: pass elif coords[n][2] == 2: linkcoords.append([coords[n][0]*2+1, coords[n][1]*2+2]) elif coords[n][2] == 3: linkcoords.append([coords[n][0]*2, coords[n][1]*2+1]) elif coords[n][2] == 1: linkcoords.append([coords[n][0]*2+2, coords[n][1]*2+1]) elif coords[n][2] == 0: linkcoords.append([coords[n][0]*2+1, coords[n][1]*2]) &quot;&quot;&quot; for n in range(len(coords)): if coords[n][2] == -1: links.append([coords[n][0:2], coords[n+1][0:2]]) links.append([coords[n+1][0:2], coords[n][0:2]]) elif coords[n][2] == 0: links.append([coords[n][0:2], [coords[n][0], coords[n][1]-1]]) links.append([[coords[n][0], coords[n][1]-1], coords[n][0:2]]) elif coords[n][2] == 1: links.append([coords[n][0:2], [coords[n][0]-1, coords[n][1]]]) links.append([[coords[n][0]-1, coords[n][1]], coords[n][0:2]]) elif coords[n][2] == 2: links.append([coords[n][0:2], [coords[n][0], coords[n][1]+1]]) links.append([[coords[n][0], coords[n][1]+1], coords[n][0:2]]) elif coords[n][2] == 3: links.append([coords[n][0:2], [coords[n][0]+1, coords[n][1]]]) links.append([[coords[n][0]+1, coords[n][1]], coords[n][0:2]]) #FINISH---------------------------------------------THIS NEEDS TO BE FINISHED LINKS SYSTEM!!!!!!!!!!!!!!!!!!-------------------------------------- else: raise Exception(&quot;ERROR CODE: 0002. DIRECTiON NOT IN 0-3 WHILE LINKING MAZE PATHS.&quot;) &quot;&quot;&quot; lines = [] for n in range(size): currentline = &quot;&quot; if n == 0 or n == size-1: lines.append(&quot;██&quot;*(size)) else: for i in range(size): if i == 0 or i == size-1: currentline += &quot;██&quot; else: if [n, i] in linkcoords: chance = random.randint(1, 100) if chance &lt;= int(grasschance): currentline += &quot;░░&quot; elif chance &gt; 100-int(questionchance): currentline += &quot;??&quot; else: currentline += &quot; &quot; else: if random.randint(1, 100) &lt;= int(brokenwallchance): currentline += &quot;▓▓&quot; else: currentline += &quot;██&quot; lines.append(currentline) return lines def maze(length=3, disallowedcoords = [], gc = 0, bwc = 0, qc = 0): &quot;&quot;&quot;GC -&gt; GRASS CHANCE. BWC - &gt; BROKEN WALL CHANCE. QC - &gt; QUESTION CHANCE IN PERCENTAGE&quot;&quot;&quot; return displaymaze(mgen(size=length, disallowedcoords = disallowedcoords), length*2+1, grasschance = gc, brokenwallchance = bwc, questionchance = qc) while True: try: length = int(input(&quot;How long + wide do you want the maze to be?&quot;)) gc = int(input(&quot;What do you want the chance of grass to be in the maze?&quot;)) qc = int(input(&quot;What do you want the chance of question marks to be in the maze?&quot;)) bwc = int(input(&quot;What do you want the chance of broken walls to be in the maze?&quot;)) input(&quot;&gt;&gt;&gt;&quot;) display = maze(length = length, gc = gc, bwc = bwc, qc = qc) for n in range(length*2+1): print(display[n]) except: print(&quot;Invalid values.&quot;) </code></pre> <p>Is there any way to increase the efficiency of this code?</p> <p><strong>Important Side Note: With very big mazes it might seem like it doesn't work but this is because Python automatically cuts the maze to the next line, this is something that is unfixable and it's a problem with the Command Line Interface. Copying and Pasting it to notepad will fix this.</strong></p>
[]
[ { "body": "<p>First, a random list:</p>\n<ul>\n<li>There's no strict benefit to having <code>canmove</code> and <code>move</code> as being nested functions. They're not closures over any variable so far as I can tell; so just move them to the global scope.</li>\n<li>Consider adding PEP484 type hints</li>\n<li>Make an <code>Enum</code> for your four cardinal directions instead of relying on integer magic</li>\n<li><code>displaymaze</code> does not display anything, since it does not <code>print</code>; perhaps call it <code>format_maze</code>.</li>\n<li>Expand your <code>gc = 0, bwc = 0, qc = 0</code> variables to spell out English words</li>\n</ul>\n<p>This block:</p>\n<pre><code>except Exception as e:\n return coordsarray\n</code></pre>\n<p>is a deeply bad idea. You're saying that if <em>anything</em> goes wrong, including running out of memory, a <code>None</code> where there shouldn't be one, index errors etc., give up and return what you have so far. Even stranger, if <em>nothing</em> goes wrong, this function is guaranteed to throw away all of its work and return <code>None</code>. The fix to this, I think, is:</p>\n<pre><code> if len(movement) == 0:\n backtrack += 1\n if len(coordslist) == 0:\n return coordsarray\n</code></pre>\n<p>and delete your <code>try/except</code>.</p>\n<p>When I tried running this, it was extremely slow for a 50x50 maze. Did you implement an <a href=\"https://en.wikipedia.org/wiki/Maze_generation_algorithm\" rel=\"nofollow noreferrer\">off-the-shelf algorithm</a> or is this your own? If it's your own, I encourage you to do some reading and compare to more efficient, well-established algorithms. 50x50 should execute &quot;instantly&quot; by human perception.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T14:22:38.873", "Id": "261470", "ParentId": "261469", "Score": "4" } }, { "body": "<p>Took me a while to understand it all because I had no prior experience with maze generation. Your approach looks like a pretty good implementation of the &quot;Randomized depth-first search&quot; algorithm. I think it's not the most efficient algorithm but one of the easiest to implement.</p>\n<p>Apart from the good comments by @Reinderien, I have one tip. When checking whether a coordinate is in a list of coordinates, it can be faster if you use a set of coordinates instead of a list; you'll have to represent coordinates as tuples instead of lists. I didn't measure it, but I guess I gained most time in canmove(). My laptop runs a 50x50 maze in 1.4 second and a 100x100 maze in 30 seconds.</p>\n<p>With this in mind, I did some refactoring. I renamed some of the variables that were not obvious to me. I should have changed <code>coordsarray</code> and <code>coordslist</code> as well (if you don't know the algorithm, these variables look as if they do the same) but instead I put some comments to explain them. Comments in general help me in the sense of being an extension of my working memory. You can see my code here: <a href=\"https://hastebin.com/kareyugozu.py\" rel=\"nofollow noreferrer\">https://hastebin.com/kareyugozu.py</a></p>\n<p>Maybe another improvement is to make <code>coordslist</code> an instance of <code>collections.deque</code> and then maybe you could make <code>coordsarray</code> a set as well. But I haven't looked into it that deeply yet.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T11:23:42.107", "Id": "261574", "ParentId": "261469", "Score": "1" } } ]
{ "AcceptedAnswerId": "261574", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T13:30:00.393", "Id": "261469", "Score": "3", "Tags": [ "python", "performance", "python-3.x" ], "Title": "CLI ASCII Maze Generator / Python 3.9" }
261469
<p><strong>Goal</strong></p> <p>This code combines two matrices, diagonalizes that matrix, and finds the right and left eigenvectors, right and left eigenvectors are normalized with respect to each other, then it is multiplied by an exponential function that is a function of the Eigen values and plots the output spectrum with respect to omega(w: frequency)</p> <p><strong>Code</strong></p> <pre><code> %%Main V2 %has an input electric field and outputs the transmitted %define some global variables n = 100; %step count a = linspace(1,100,n); %our dummy parameter p = 1; %p is the index value used of a N = 10^8; %N is the density of particles needs to be changed c = 3*10^8; %m/s k = (2*pi)/c; %tau = linspace(0,1,n); tau = 0; % time delay %the Frequency grid w = linspace(0,1,n); wp = linspace(0,1,n); %%define a diagonal X0 s.t it is zero on the bounds chi_0 = (1+1i)*(sin(5*pi*w).^2); %chi_0 get diagonalized in EigVect function %%define a 3D function same as above %X_nd non diagonal for i=1:n for j=1:n X_nd(i,j) = (1+1i)*sin(5*pi.*w(i).*wp(j)).^2; end end %%Diagonalize Xij and Normalize EigVectors [U_r, L, U_L] = EigVect(chi_0,X_nd,a(p),w,n); %get the right/left eigent vectors and eigen values L [U_rbar,U_Lbar] = Norm(U_r,U_L); %normalize the right/left eigen vectors %%Define the incoming electric field E_0 = 1; %amplitude w_0 = 0.5; %choose value from 0.3-0.7 doesn't matter for now sigma = 0.1; %This for loop creates a vector of E for i = 1:n E(i) = E_0.*sin(pi*w(i))*exp(-((w(i)-w_0)/(sigma*sqrt(2))).^2); end %%Compute the transmitted spectrum E(omega,tau;a,N) at the exit of the sample %exponential function of lambda Exp_lambda = exp(N*1i*k*diag(L)); %time delay tau_phase = exp(1i*tau.*w); UXU = U_rbar*diag(Exp_lambda)*(U_Lbar'); %Output Electric field E_out = UXU*(tau_phase.*E).'; hold on plot(w,E, 'b'); plot(w,abs(E_out), 'r'); %for output plot absolute value legend('Input','Output') title(['a = ',num2str(a(p)),', N = ',num2str(N),', tau = ',num2str(tau)]) %%Functions %Normalization of the eigenvectors w.r.t one another function [A_bar,B_bar] = Norm(A,B) f = sum(B'*A,1); sqrt_f = sqrt(f); A_bar = A./sqrt_f; B_bar = B./sqrt_f; end %input a chi_0 and a non diagonal portion return right and left eigvectors %and the diagonal eigen values function [A_bar, L, B_bar] = EigVect(x,y,a,w,n) X_0 = diag(x); dw = 1/(n-1); for i = 1:n for j = 1:n X_ij(i,j) = (a*dw*y(i,j)+X_0(i,j))*sqrt(w(i)*w(j)); end end %y is X_nd [A_bar, L, B_bar] = eig(X_ij); %returns the non-normalized right and left eigenvectors of X_ij %and the diagonal eigenvalue matrix end </code></pre> <p><a href="https://i.stack.imgur.com/1z0UZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1z0UZ.jpg" alt="Output" /></a></p> <p>I am looking for a general code review as well as any suggestions to bring the computation time down. Thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T15:23:42.827", "Id": "515979", "Score": "0", "body": "Do you have any specific concerns, or are you looking for a generic review?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T17:26:28.030", "Id": "515983", "Score": "1", "body": "Are you in the same class as this person? https://codereview.stackexchange.com/questions/261316/simulate-transmission-spectrum-of-extreme-ultraviolet-laser-pulse-through-laser — You could learn a lot from reviewing that code!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T18:08:02.543", "Id": "515987", "Score": "0", "body": "I am looking for a generic code review as well as some shortcuts to speed up the computation time." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T14:49:29.640", "Id": "261472", "Score": "3", "Tags": [ "simulation", "matlab", "physics" ], "Title": "MatLab: Plotting Output Electric Field Spectrum" }
261472
<p>The below code filters my <code>contacts</code> according to a search term the user typed.</p> <p>Is there a way I can avoid explicitly writing all the object keys but keep the readability?</p> <pre><code> contacts = contacts.filter( contact =&gt; contact.firstName.toLowerCase().includes(search) || contact.lastName.toLowerCase().includes(search) || contact.title.toLowerCase().includes(search) || contact.type.toLowerCase().includes(search) || contact.notes.toLowerCase().includes(search) || contact.phones.filter(val =&gt; val.value.toLowerCase().includes(search) ).length || contact.emails.filter(val =&gt; val.value.toLowerCase().includes(search) ).length ) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T03:50:18.210", "Id": "516042", "Score": "0", "body": "When you say \"dynamic\", are you looking for a way to make this code more flexible (i.e. usable in other contexts)? If so, could you expound a bit on what you're looking for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T04:30:23.803", "Id": "516047", "Score": "0", "body": "@ScottyJamison I meant to avoid explicitly writing all the object keys" } ]
[ { "body": "<p>You can use <code>Object.entries(obj)</code> and <code>Array.isArray(obj)</code> to make it generic:</p>\n<pre class=\"lang-js prettyprint-override\"><code>let testObj = obj =&gt; obj.toLowerCase().includes(search);\ncontacts = contacts.filter(\n contact =&gt; Object.entries(contact).some(entry =&gt; {\n let [key, value] = entry;\n if (Array.isArray(value)) {\n return value.some(val =&gt; testObj(val.value));\n } else {\n return testObj(value);\n }\n });\n);\n</code></pre>\n<p>If you run the code above with the following sample data:</p>\n<pre class=\"lang-js prettyprint-override\"><code>let contacts = [\n {\n phones: [\n {value: &quot;8765&quot;}, \n {value: &quot;4356&quot;}\n ],\n foo: &quot;hey&quot;,\n bar: &quot;adggg&quot;\n },\n {\n phones: [\n {value: &quot;1234&quot;}, \n {value: &quot;3456&quot;}\n ],\n foo: &quot;oh&quot;,\n bar: &quot;sdff&quot;\n },\n {\n phones: [\n {value: &quot;8765&quot;}, \n {value: &quot;4356&quot;}\n ],\n foo: &quot;ah&quot;,\n bar: &quot;hhh&quot;\n } \n];\nlet search = &quot;ah&quot;;\n</code></pre>\n<p>you get:</p>\n<pre class=\"lang-js prettyprint-override\"><code>{\n phones: [\n {value: &quot;8765&quot;}, \n {value: &quot;4356&quot;}\n ],\n foo: &quot;ah&quot;,\n bar: &quot;hhh&quot;\n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T02:43:34.490", "Id": "516040", "Score": "3", "body": "Your code will not run if used in modules or strict mode. Always declare variable." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T19:36:21.420", "Id": "261480", "ParentId": "261473", "Score": "0" } }, { "body": "<p>I can think of a few ways:</p>\n<ol>\n<li><p>Serialize the whole object. A simple version: <code>JSON.stringify(contact).toLowerCase().includes(search)</code>\nThis will absolutely get the wrong answer if the user searches for quotes, colons or braces, but if this is not a concern, it will be easy.</p>\n</li>\n<li><p>To be a little more precise, you're going to have to do a little &quot;meta-programming&quot; to get the names of the fields of your object. <code>Object.keys(contract)</code> will give you an array of all the keys, which you can then iterate through. You'll need to partition these into two groups: those that are simple strings, and those that are nested arrays. You can then re-work the code you have to use these more generic lists.</p>\n</li>\n<li><p>As your code grows, this will probably be your best path: Create a list of the valid field names; this &quot;data dictionary&quot; can be shared in such a way that they can be used here in a generic way. It could be something as simple as <code>SEARCHABLE_CONTACT_FIELDS = ['firstName','lastName','title'...</code> or a more complex <code>SEARCHABLE_CONTACT_FIELDS = { firstName: 'String', lastName: 'String', phone: 'Array', ...</code> This gives you more control and this &quot;meta&quot; information will be useful for other functions as well.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-12T22:27:44.470", "Id": "262984", "ParentId": "261473", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T15:29:44.883", "Id": "261473", "Score": "1", "Tags": [ "javascript" ], "Title": "Filter results by a search term" }
261473
<p>A function that asks for user input according to some criteria and again on the same line if the criteria is not met. It requires that escape character sequences be enable.</p> <pre><code>&quot;&quot;&quot; Ask for user input according to some criteria and again on the same line if the criteria is not met &quot;&quot;&quot; __all__ = ['input_wrong_up_line'] def input_wrong_up_line(input_msg, criteria): a = '\033[A' input_wrong_msg = a + len(input_msg) * ' ' while True: input_user = input(input_msg) if criteria(input_user): return input_user print(input_wrong_msg + len(input_user) * ' ' + a) if __name__ == '__main__': from colorama import deinit, init init() try: input_wrong_up_line('Exit? [y/ ] ', lambda input_user: input_user == 'y') finally: deinit() </code></pre>
[]
[ { "body": "<p>Nice, but you’re doing too much work.</p>\n<p><code>\\033[J</code> will erase from the cursor position until the end of the screen, which eliminates the need to count characters and print spaces.</p>\n<p>(See <a href=\"https://en.wikipedia.org/wiki/ANSI_escape_code#CSIsection\" rel=\"nofollow noreferrer\">ANSI escape codes: CSI sequences</a> for additional codes &amp; information.)</p>\n<p>So, you just need to move the cursor up one line, clear to end of screen, and not print a newline, leaving the cursor at the “up one line“ position.</p>\n<pre><code>print(&quot;\\033[A\\033[J&quot;, end='')\n</code></pre>\n<p><strong>Note</strong>: if the user input is more than one line of text, moving the cursor up only one line will only result in clearing the last line. Fixing that would require more effort.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T18:59:11.687", "Id": "261478", "ParentId": "261474", "Score": "2" } } ]
{ "AcceptedAnswerId": "261478", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T16:59:22.260", "Id": "261474", "Score": "3", "Tags": [ "python-3.x", "console", "escaping" ], "Title": "Ask for user input and again on the same line" }
261474
<p>The <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/range" rel="nofollow noreferrer">standard HTML range input element</a> suffers from a number of limitations that caused me to implement the web component presented here.</p> <p>First, it is unnecessarily complicated to style the standard HTML range input element to make it look the same in all web browsers (see <a href="https://css-tricks.com/sliding-nightmare-understanding-range-input/" rel="nofollow noreferrer">here</a> and <a href="https://css-tricks.com/styling-cross-browser-compatible-range-inputs-css/" rel="nofollow noreferrer">here</a>).</p> <p>Second, the standard HTML range input element is designed to be used in a horizontal manner from left to right. Turning it into a vertical slider can be done but is again web browser-specific (see <a href="https://stackoverflow.com/q/15935837">here</a>). In order to invert its minimum and maximum the element needs to be transformed accordingly (see <a href="http://twiggle-web-design.com/tutorials/Custom-Vertical-Input-Range-CSS3.html" rel="nofollow noreferrer">here</a>).</p> <p>Lastly, the standard HTML range input element does not support visual indications of the values that it can be set to. Such indications are an important aspect of this web component and it is where it derives its name from.</p> <p>The result of that effort is a dependency-free web component stored in a single file. Its content is shown below:</p> <pre class="lang-javascript prettyprint-override"><code>export const OrientationEnum = Object.freeze({ LeftToRight: &quot;left-to-right&quot;, RightToLeft: &quot;right-to-left&quot;, TopToBottom: &quot;top-to-bottom&quot;, BottomToTop: &quot;bottom-to-top&quot; }); const webComponentName = &quot;summbit-discrete-slider&quot;; const nameTrack = &quot;track&quot;; const nameMinimum = &quot;min&quot;; const nameMaximum = &quot;max&quot;; const nameValue = &quot;value&quot;; const nameOrientation = &quot;orientation&quot;; const nameThumb = &quot;thumb&quot;; const nameDot = &quot;dot&quot;; const nameDotContainer = &quot;dot-container&quot;; const keysToIncrement = [&quot;ArrowUp&quot;, &quot;ArrowRight&quot;]; const keysToDecrement = [&quot;ArrowDown&quot;, &quot;ArrowLeft&quot;]; const propertyTrackColor = `--${webComponentName}-private-track-color`; const propertyProgressColor = `--${webComponentName}-private-progress-color`; const propertyThumbDiameter = `--${webComponentName}-private-thumb-diameter`; const propertyThumbPosition = `--${webComponentName}-private-thumb-position`; const initialMinimum = 0; const initialMaximum = 5; const template = document.createElement(&quot;template&quot;); template.innerHTML = ` &lt;div id=&quot;${nameTrack}&quot; class=&quot;${nameTrack}-${OrientationEnum.LeftToRight}&quot; tabindex=&quot;0&quot;&gt; &lt;span id=&quot;${nameMinimum}&quot; class=&quot;${nameMinimum}-${OrientationEnum.LeftToRight}&quot; tabindex=&quot;-1&quot;&gt;&lt;/span&gt; &lt;span id=&quot;${nameMaximum}&quot; class=&quot;${nameMaximum}-${OrientationEnum.LeftToRight}&quot; tabindex=&quot;-1&quot;&gt;&lt;/span&gt; &lt;span id=&quot;${nameDotContainer}&quot; class=&quot;${nameDotContainer}-${OrientationEnum.LeftToRight}&quot; tabindex=&quot;-1&quot;&gt;&lt;/span&gt; &lt;span id=&quot;${nameThumb}&quot; class=&quot;${nameThumb}-${OrientationEnum.LeftToRight}&quot; tabindex=&quot;-1&quot;&gt; &lt;span class=&quot;thumb-center-dot&quot; tabindex=&quot;-1&quot;&gt;&lt;/span&gt; &lt;/span&gt; &lt;/div&gt; &lt;style&gt; :host { ${propertyTrackColor}: var(--${webComponentName}-track-color, #a8bec9); ${propertyProgressColor}: var(--${webComponentName}-progress-color, #0079c9); ${propertyThumbDiameter}: var(--${webComponentName}-thumb-diameter, 20px); --${webComponentName}-private-thumb-color: var(--${webComponentName}-thumb-color, #ffffff); --${webComponentName}-private-track-width: var(--${webComponentName}-track-width, 4px); --${webComponentName}-private-track-offset: calc(calc(100% - var(--${webComponentName}-private-track-width)) / 2); --${webComponentName}-private-thumb-stroke: calc(var(--${webComponentName}-private-track-width) / 2); --${webComponentName}-private-thumb-radius: calc(var(${propertyThumbDiameter}) / 2); --${webComponentName}-private-thumb-offset: calc(calc(100% - var(${propertyThumbDiameter})) / 2); --${webComponentName}-private-dot-diameter: calc(var(--${webComponentName}-private-track-width) * 2); --${webComponentName}-private-dot-container-offset-front-side: calc(calc(var(${propertyThumbDiameter}) - var(--${webComponentName}-private-dot-diameter)) / 2); --${webComponentName}-private-dot-container-offset-long-side: calc(calc(100% - var(--${webComponentName}-private-dot-diameter)) / 2); all: initial; touch-action: none; display: inline-block; padding: 0; margin: 0; } .${nameTrack}-${OrientationEnum.LeftToRight}, .${nameTrack}-${OrientationEnum.RightToLeft}, .${nameTrack}-${OrientationEnum.TopToBottom}, .${nameTrack}-${OrientationEnum.BottomToTop} { touch-action: none; position: relative; width: 100%; height: 100%; } .${nameTrack}-${OrientationEnum.LeftToRight}, .${nameTrack}-${OrientationEnum.RightToLeft} { min-width: 150px; min-height: var(${propertyThumbDiameter}); } .${nameTrack}-${OrientationEnum.TopToBottom}, .${nameTrack}-${OrientationEnum.BottomToTop} { min-height: 150px; min-width: var(${propertyThumbDiameter}); } .${nameMinimum}-${OrientationEnum.LeftToRight}, .${nameMinimum}-${OrientationEnum.RightToLeft}, .${nameMinimum}-${OrientationEnum.TopToBottom}, .${nameMinimum}-${OrientationEnum.BottomToTop} { touch-action: none; position: absolute; background-color: var(${propertyProgressColor}); } .${nameMaximum}-${OrientationEnum.LeftToRight}, .${nameMaximum}-${OrientationEnum.RightToLeft}, .${nameMaximum}-${OrientationEnum.TopToBottom}, .${nameMaximum}-${OrientationEnum.BottomToTop} { touch-action: none; position: absolute; background-color: var(${propertyTrackColor}); } .${nameMinimum}-${OrientationEnum.LeftToRight}, .${nameMaximum}-${OrientationEnum.RightToLeft} { top: var(--${webComponentName}-private-track-offset); left: var(--${webComponentName}-private-thumb-radius); width: var(${propertyThumbPosition}); height: var(--${webComponentName}-private-track-width); } .${nameMinimum}-${OrientationEnum.RightToLeft}, .${nameMaximum}-${OrientationEnum.LeftToRight} { top: var(--${webComponentName}-private-track-offset); left: calc(var(${propertyThumbPosition}) + var(--${webComponentName}-private-thumb-radius)); right: var(--${webComponentName}-private-thumb-radius); height: var(--${webComponentName}-private-track-width); } .${nameMinimum}-${OrientationEnum.TopToBottom}, .${nameMaximum}-${OrientationEnum.BottomToTop} { top: var(--${webComponentName}-private-thumb-radius); left: var(--${webComponentName}-private-track-offset); width: var(--${webComponentName}-private-track-width); height: var(${propertyThumbPosition}); } .${nameMinimum}-${OrientationEnum.BottomToTop}, .${nameMaximum}-${OrientationEnum.TopToBottom} { top: calc(var(${propertyThumbPosition}) + var(--${webComponentName}-private-thumb-radius)); left: var(--${webComponentName}-private-track-offset); width: var(--${webComponentName}-private-track-width); bottom: var(--${webComponentName}-private-thumb-radius); } .${nameDotContainer}-${OrientationEnum.LeftToRight}, .${nameDotContainer}-${OrientationEnum.RightToLeft}, .${nameDotContainer}-${OrientationEnum.TopToBottom}, .${nameDotContainer}-${OrientationEnum.BottomToTop} { touch-action: none; position: absolute; display: flex; align-items: center; justify-content: space-between; } .${nameDotContainer}-${OrientationEnum.LeftToRight}, .${nameDotContainer}-${OrientationEnum.RightToLeft} { top: var(--${webComponentName}-private-dot-container-offset-long-side); left: var(--${webComponentName}-private-dot-container-offset-front-side); right: var(--${webComponentName}-private-dot-container-offset-front-side); bottom: var(--${webComponentName}-private-dot-container-offset-long-side); } .${nameDotContainer}-${OrientationEnum.TopToBottom}, .${nameDotContainer}-${OrientationEnum.BottomToTop} { top: var(--${webComponentName}-private-dot-container-offset-front-side); left: var(--${webComponentName}-private-dot-container-offset-long-side); right: var(--${webComponentName}-private-dot-container-offset-long-side); bottom: var(--${webComponentName}-private-dot-container-offset-front-side); } .${nameDotContainer}-${OrientationEnum.LeftToRight} { flex-direction: row; } .${nameDotContainer}-${OrientationEnum.RightToLeft} { flex-direction: row-reverse; } .${nameDotContainer}-${OrientationEnum.TopToBottom} { flex-direction: column; } .${nameDotContainer}-${OrientationEnum.BottomToTop} { flex-direction: column-reverse; } .${nameDot} { touch-action: none; width: var(--${webComponentName}-private-dot-diameter); height: var(--${webComponentName}-private-dot-diameter); border-radius: 50%; } .${nameThumb}-${OrientationEnum.LeftToRight}, .${nameThumb}-${OrientationEnum.RightToLeft}, .${nameThumb}-${OrientationEnum.TopToBottom}, .${nameThumb}-${OrientationEnum.BottomToTop} { touch-action: none; position: absolute; width: var(${propertyThumbDiameter}); height: var(${propertyThumbDiameter}); border-radius: 50%; border: var(--${webComponentName}-private-thumb-stroke) solid var(${propertyProgressColor}); box-sizing: border-box; background-color: var(--${webComponentName}-private-thumb-color); display: flex; align-items: center; justify-content: center; } .${nameThumb}-${OrientationEnum.LeftToRight}, .${nameThumb}-${OrientationEnum.RightToLeft} { top: var(--${webComponentName}-private-thumb-offset); left: var(${propertyThumbPosition}); } .${nameThumb}-${OrientationEnum.TopToBottom}, .${nameThumb}-${OrientationEnum.BottomToTop} { top: var(${propertyThumbPosition}); left: var(--${webComponentName}-private-thumb-offset); } .thumb-center-dot { touch-action: none; width: var(--${webComponentName}-private-dot-diameter); height: var(--${webComponentName}-private-dot-diameter); border-radius: 50%; background-color: var(${propertyProgressColor}); } .${nameTrack}-${OrientationEnum.LeftToRight}:focus, .${nameTrack}-${OrientationEnum.RightToLeft}:focus, .${nameTrack}-${OrientationEnum.TopToBottom}:focus, .${nameTrack}-${OrientationEnum.BottomToTop}:focus, .${nameMinimum}-${OrientationEnum.LeftToRight}:focus, .${nameMinimum}-${OrientationEnum.RightToLeft}:focus, .${nameMinimum}-${OrientationEnum.TopToBottom}:focus, .${nameMinimum}-${OrientationEnum.BottomToTop}:focus, .${nameMaximum}-${OrientationEnum.LeftToRight}:focus, .${nameMaximum}-${OrientationEnum.RightToLeft}:focus, .${nameMaximum}-${OrientationEnum.TopToBottom}:focus, .${nameMaximum}-${OrientationEnum.BottomToTop}:focus, .${nameDotContainer}-${OrientationEnum.LeftToRight}:focus, .${nameDotContainer}-${OrientationEnum.RightToLeft}:focus, .${nameDotContainer}-${OrientationEnum.TopToBottom}:focus, .${nameDotContainer}-${OrientationEnum.BottomToTop}:focus, .${nameDot}:focus, .${nameThumb}-${OrientationEnum.LeftToRight}:focus, .${nameThumb}-${OrientationEnum.RightToLeft}:focus, .${nameThumb}-${OrientationEnum.TopToBottom}:focus, .${nameThumb}-${OrientationEnum.BottomToTop}:focus, .thumb-center-dot:focus { outline: none; } .${nameTrack}-${OrientationEnum.LeftToRight}:focus-visible, .${nameTrack}-${OrientationEnum.RightToLeft}:focus-visible, .${nameTrack}-${OrientationEnum.TopToBottom}:focus-visible, .${nameTrack}-${OrientationEnum.BottomToTop}:focus-visible { outline: 5px auto Highlight; outline: 5px auto -webkit-focus-ring-color; } &lt;/style&gt; `; export default class SummbitDiscreteSlider extends HTMLElement { constructor() { super(); this.attachShadow({ mode: &quot;open&quot; }); this.shadowRoot.appendChild(template.content.cloneNode(true)); this._minimum = Number.NaN; this._maximum = Number.NaN; this._value = 0; this._startValue = 0; this._orientation = OrientationEnum.LeftToRight; this._trackElement = this.shadowRoot.getElementById(nameTrack); this._minimumElement = this.shadowRoot.getElementById(nameMinimum); this._maximumElement = this.shadowRoot.getElementById(nameMaximum); this._dotContainerElement = this.shadowRoot.getElementById(nameDotContainer); this._thumbElement = this.shadowRoot.getElementById(nameThumb); this._resizeObserver = new ResizeObserver(this._resizeHandler.bind(this)); this.ondragstart = () =&gt; false; this.addEventListener(&quot;pointerdown&quot;, this._pointerDownHandler.bind(this)); this.addEventListener(&quot;keydown&quot;, this._keyDownHandler.bind(this)); } static get observedAttributes() { return [nameMinimum, nameMaximum, nameValue, nameOrientation]; } attributeChangedCallback(attributeName, oldValue, newValue) { if(newValue !== null) { switch(attributeName) { case nameMinimum: this._minimum = parseInt(newValue); this._createAllDots(); this._updateThumbPosition(); this._restrictValueToMinimum(); break; case nameMaximum: this._maximum = parseInt(newValue); this._createAllDots(); this._updateThumbPosition(); this._restrictValueToMaximum(); break; case nameValue: this._value = this._clampValue(parseInt(newValue)); this._createAllDots(); this._updateThumbPosition(); this._updateDotColorsAndValues(); break; case nameOrientation: this._orientation = newValue; this._updateElementStyle(); this._createAllDots(); this._updateThumbPosition(); this._updateDotColorsAndValues(); break; } } } connectedCallback() { this._createAllDots(); this._resizeObserver.observe(this, { box: &quot;content-box&quot; }); } set min(value) { this.setAttribute(nameMinimum, value); } get min() { return this._minimum; } set max(value) { this.setAttribute(nameMaximum, value); } get max() { return this._maximum; } set value(value) { this.setAttribute(nameValue, this._clampValue(value)); } get value() { return this._value; } set orientation(value) { this.setAttribute(nameOrientation, value); } get orientation() { return this._orientation; } _resizeHandler(entries) { this._updateThumbPosition(); } _pointerDownHandler(event) { this.setPointerCapture(event.pointerId); this.onpointermove = this._pointerMoveHandler.bind(this); this.onpointerup = this._pointerUpHandler.bind(this); this._startValue = this._value; this._updateValue(event); } _pointerMoveHandler(event) { this._updateValue(event); } _pointerUpHandler(event) { this.onpointermove = null; this.onpointerup = null; if(this._startValue != this._value) { this._dispatchChangeEvent(); } } _keyDownHandler(event) { if(keysToIncrement.includes(event.code)) { this._incrementValue(); } else if(keysToDecrement.includes(event.code)) { this._decrementValue(); } } _createAllDots() { this._initializeLimits(); let currentDotCount = this._dotContainerElement.childElementCount; let requiredDotCount = this._maximum - this._minimum + 1; this._createAdditionalDots(requiredDotCount - currentDotCount); this._deleteObsoleteDots(currentDotCount - requiredDotCount); } _initializeLimits() { if(isNaN(this._minimum)) { this._minimum = initialMinimum; } if(isNaN(this._maximum)) { this._maximum = initialMaximum; } } _createAdditionalDots(dotCount) { if(dotCount &gt; 0) { for(let i = 0; i &lt; dotCount; i++) { this._dotContainerElement.appendChild(this._createDot()); } this._updateDotColorsAndValues(); } } _deleteObsoleteDots(dotCount) { if(dotCount &gt; 0) { for(let i = 0; i &lt; dotCount; i++) { this._dotContainerElement.removeChild(this._dotContainerElement.lastChild); } this._updateDotColorsAndValues(); } } _createDot() { let dot = document.createElement(&quot;span&quot;); dot.className = nameDot; dot.tabIndex = -1; return dot; } _updateDotColorsAndValues() { let computedStyle = window.getComputedStyle(this); let progressColor = computedStyle.getPropertyValue(propertyProgressColor); let trackColor = computedStyle.getPropertyValue(propertyTrackColor); let dot, value; for(let i = 0; i &lt; this._dotContainerElement.children.length; i++) { value = i + this._minimum; dot = this._dotContainerElement.children[i]; dot.dataset.value = value; dot.style.backgroundColor = value &gt; this._value ? trackColor : progressColor; } } _updateThumbPosition() { for(let i = 0; i &lt; this._dotContainerElement.children.length; i++) { if(this._dotContainerElement.children[i].dataset.value == this._value) { switch(this._orientation) { case OrientationEnum.LeftToRight: case OrientationEnum.RightToLeft: this._trackElement.style.setProperty(propertyThumbPosition, this._dotContainerElement.children[i].offsetLeft + &quot;px&quot;, &quot;&quot;); return; case OrientationEnum.TopToBottom: case OrientationEnum.BottomToTop: this._trackElement.style.setProperty(propertyThumbPosition, this._dotContainerElement.children[i].offsetTop + &quot;px&quot;, &quot;&quot;); return; } } } } _clampValue(value) { if(!isNaN(this._minimum) &amp;&amp; value &lt; this._minimum) { return this._minimum; } else if(!isNaN(this._maximum) &amp;&amp; value &gt; this._maximum) { return this._maximum; } return value; } _restrictValueToMinimum() { if(this._value &lt; this._minimum) { this.value = this._minimum; } } _restrictValueToMaximum() { if(this._value &gt; this._maximum) { this.value = this._maximum; } } _incrementValue() { if(this._value &lt; this._maximum) { this.value += 1; this._dispatchInputEvent(); this._dispatchChangeEvent(); } } _decrementValue() { if(this._value &gt; this._minimum) { this.value -= 1; this._dispatchInputEvent(); this._dispatchChangeEvent(); } } _updateValue(event) { let index = Math.round(this._calculateProgress(event) * (this._maximum - this._minimum)); let value = parseInt(this._dotContainerElement.children[index].dataset.value); if(this._value != value) { this.value = value; this._dispatchInputEvent(); } } _calculateProgress(event) { let thumbDiameter = parseFloat(window.getComputedStyle(this).getPropertyValue(propertyThumbDiameter)); let thumbRadius = thumbDiameter / 2; let trackLength, position; switch(this._orientation) { case OrientationEnum.LeftToRight: trackLength = this._trackElement.offsetWidth - thumbDiameter; position = event.clientX - thumbRadius - this._trackElement.getBoundingClientRect().left; break; case OrientationEnum.RightToLeft: trackLength = this._trackElement.offsetWidth - thumbDiameter; position = this._trackElement.getBoundingClientRect().right - event.clientX - thumbRadius; break; case OrientationEnum.TopToBottom: trackLength = this._trackElement.offsetHeight - thumbDiameter; position = event.clientY - thumbRadius - this._trackElement.getBoundingClientRect().top; break; case OrientationEnum.BottomToTop: trackLength = this._trackElement.offsetHeight - thumbDiameter; position = this._trackElement.getBoundingClientRect().bottom - event.clientY - thumbRadius; break; } return Math.min(Math.max(position, 0), trackLength) / trackLength; } _updateElementStyle() { this._trackElement .className = `${nameTrack}-${this._orientation}`; this._minimumElement .className = `${nameMinimum}-${this._orientation}`; this._maximumElement .className = `${nameMaximum}-${this._orientation}`; this._dotContainerElement.className = `${nameDotContainer}-${this._orientation}`; this._thumbElement .className = `${nameThumb}-${this._orientation}`; } _dispatchInputEvent() { this.shadowRoot.dispatchEvent(new CustomEvent(&quot;input&quot;, { bubbles: true, composed: true, detail: { value: this._value }})); } _dispatchChangeEvent() { this.shadowRoot.dispatchEvent(new CustomEvent(&quot;change&quot;, { bubbles: true, composed: true, detail: { value: this._value }})); } } if(!customElements.get(webComponentName)) { customElements.define(webComponentName, SummbitDiscreteSlider); } </code></pre> <p>This <a href="https://github.com/summbit/summbit-web-components/blob/master/js/summbit-discrete-slider.js" rel="nofollow noreferrer">code</a> has been released to the public on GitHub under <a href="https://github.com/summbit/summbit-web-components/blob/master/LICENSE.txt" rel="nofollow noreferrer">this license</a>.</p> <p>The instructions on how to use it are available <a href="https://github.com/summbit/summbit-web-components/blob/master/docs/summbit-discrete-slider.md" rel="nofollow noreferrer">here</a>. An HTML test page is available <a href="https://summbit.github.io/summbit-web-components/test/summbit-discrete-slider.html" rel="nofollow noreferrer">here</a>.</p> <p>Please note that symbol names are long and descriptive on purpose. The goal of this file is to be as understandable for humans as possible. Those symbol names are later minified.</p> <p>Note also that private symbol names start with an underscore (<code>_</code>) in order to mark them accordingly. At the time of writing this, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields" rel="nofollow noreferrer">private class fields</a> are not available yet in Firefox according to <a href="https://caniuse.com/?search=Private%20class%20fields" rel="nofollow noreferrer">caniuse.com</a>. Once available, the underscores will be replaced with the <code>#</code> character.</p> <p><strong>I'm looking for hints/comments/advice in general i.e. HTML, CSS and JavaScript best practices, style tips, etc. are all welcome.</strong></p> <hr /> <p>Known issues:</p> <ul> <li>Safari on iOS 14 seems to have a bug in regards to the <code>setPointerCapture</code> API. Moving the thumb only works if the pointer is located within the slider. This possible bug is corroborated by <a href="https://stackoverflow.com/q/64017560">this</a> StackOverflow post.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T18:13:08.593", "Id": "515989", "Score": "1", "body": "First thing I checked was keyboard support :) and +1 for that: However I do find the flipped sliders anti-intuitive. As in keyboard `left` makes slider go right, and `up` makes slider go down etc. I would also have added Home / End. Second is focus. There is no indication on which element has focus unless one use TAB to move between them. I like the overall layout (esp the stop marks). I am also wondering if it should replace HTML sliders, as in: if user has JS disabled, display HTML variant, else replace it with the custom. If in a Web-App OK, then one need JS, else it should work regardless." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T20:04:36.967", "Id": "516011", "Score": "0", "body": "Thanks for your comment, @user3342816. Depending on how you look at it, which keys do what for each configuration of the slider can be confusing. On a test page, like the one linked, it can make sense the way it is because how you increment or decrement is consistent across all sliders. For just one slider configuration, which is likely the more probable case, it might really be just confusing. So, I consider changing it on the right-to-left and top-to-bottom configuration. Regarding the focus indication: From what I see on the default slider it only appears if tabs is pressed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T20:12:24.133", "Id": "516012", "Score": "0", "body": "I'm pretty new to the whole web development / web front-end design thing so I might just be ignorant to the fact that JavaScript might be disabled in a web browser. From what I see in today's web, judging from my personal perspective, it is just utterly impractical to browse the web without JavaScript enabled. So, I really wonder whether I need to consider that case at all. I mean, it *might* be an actual thing but I abandoned the idea of disabling JavaScript in any of my web browsers years ago." } ]
[ { "body": "<p>It looks like you've put a lot of work into this and it appears to function well. There are only a few suggestions - see below.</p>\n<p>I agree with the comment by user3342816 that the flipped sliders seem counter-intuitive.</p>\n<h2>Suggestions</h2>\n<h3>Reflows</h3>\n<p>The <a href=\"/questions/tagged/performance\" class=\"post-tag\" title=\"show questions tagged &#39;performance&#39;\" rel=\"tag\">performance</a> tag was not originally added to the post but that should definitely be a consideration for UI elements. Perhaps it is becoming less of a concern as browsers are being optimized, but it is wise to <a href=\"https://developers.google.com/speed/docs/insights/browser-reflow\" rel=\"nofollow noreferrer\">Minimize browser reflows</a>. That means instead of adding elements to the DOM in a loop - e.g. in <code>_createAdditionalDots()</code>, add elements to a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment\" rel=\"nofollow noreferrer\">documentFragment</a> or temporary element and then add the contents of that element in a single step. And for removing elements - e.g. as <code>_deleteObsoleteDots()</code> uses a loop, a different approach might be better.</p>\n<h3>Loops</h3>\n<p>The method <code>updateThumbPosition()</code> could use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code> loop</a> since variable <code>i</code> is only used to dereference the collection <code>this._dotContainerElement.children</code>, though performance might be impacted because it would use in internal iterator method to iterate over the elements.</p>\n<h3><code>const</code> vs <code>let</code></h3>\n<p>Using <code>const</code> when re-assignment isn't needed is a good habit because it can help avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>. For example, the method <code>_createDot()</code> has one such variable:</p>\n<blockquote>\n<pre><code>_createDot() {\n let dot = document.createElement(&quot;span&quot;);\n dot.className = nameDot;\n dot.tabIndex = -1;\n return dot;\n}\n</code></pre>\n</blockquote>\n<p>The variable <code>dot</code> is never re-assigned so it can be declared with <code>const</code> instead of <code>let</code>.</p>\n<h3>Constant naming convention</h3>\n<p>A lot of idiomatic Javascript follows conventions from other C-based languages, including true constants in <code>ALL_CAPS</code>. This isn't a requirement but does help anyone reading the code spot values that are symbolic constants. More on this topic can be found <a href=\"https://www.freecodecamp.org/news/when-to-capitalize-your-javascript-constants-4fabc0a4a4c4/\" rel=\"nofollow noreferrer\">here</a>.</p>\n<h3>Increment and Decrement operators</h3>\n<p>In method <code>_incrementValue()</code> this line exists:</p>\n<blockquote>\n<pre><code>this.value += 1;\n</code></pre>\n</blockquote>\n<p>It could be simplified using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment\" rel=\"nofollow noreferrer\">increment operator</a>:</p>\n<pre><code>this.value++;\n</code></pre>\n<p>And similarly, in <code>_decrementValue()</code> the second line:</p>\n<blockquote>\n<pre><code>this.value -= 1;\n</code></pre>\n</blockquote>\n<p>can be simplified using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Decrement\" rel=\"nofollow noreferrer\">decrement operator</a>:</p>\n<pre><code>this.value--;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T06:17:56.023", "Id": "518979", "Score": "0", "body": "Thanks a lot for your review. What you brought up are all good points and I will address them accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-26T16:37:14.367", "Id": "522201", "Score": "0", "body": "For reference, the points you brought up (except \"constant naming convention\") are addressed in the version I put up [GitHub](https://github.com/summbit/summbit-web-components/blob/master/js/summbit-discrete-slider.js)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T23:51:19.090", "Id": "262781", "ParentId": "261475", "Score": "3" } } ]
{ "AcceptedAnswerId": "262781", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T17:05:36.137", "Id": "261475", "Score": "5", "Tags": [ "javascript", "html", "css", "ecmascript-6", "user-interface" ], "Title": "JavaScript discrete slider web component" }
261475
<p>I'm in the early stages of learning Racket, and decided to have a go at the tower of Hanoi. I did this without any reference whatsoever, so everything is up for review, including the algorithm as well as my code.</p> <p>In order to move <em>n</em> disks from a <em>from</em> peg to a <em>to</em> peg, we need to...</p> <ol> <li>move the top n-1 disks from <em>from</em> to <em>free</em></li> <li>move the remaining single disk from <em>from</em> to <em>to</em></li> <li>move n-1 disks from <em>free</em> to <em>to</em></li> </ol> <p>You then do exactly the same for the next <em>n-1</em> pegs, and keep repeating until you've finished. This is clearly a recursive algorithm.</p> <p>In order to work out which is the free peg, I realised that if you number the pegs 1, 2 and 3, then the sum of all three is always 6, so the number of the free peg is going to be <em>6 - (from + to)</em>. This led to my first utility function...</p> <pre class="lang-lisp prettyprint-override"><code> (define (free-peg from to) (- 6 (+ from to))) </code></pre> <p>Then I needed a function to move a tower of <em>n</em> disks to one peg to another. Following the three steps shown above, I came up with this...</p> <pre class="lang-lisp prettyprint-override"><code> (define (move-tower n from to) (if (= n 0) empty (append (move-tower (- n 1) from (free-peg from to)) ; step 1 (list (list from to)) ; step 2 (move-tower (- n 1) (free-peg from to) to))) ; step 3 ) </code></pre> <p>I then needed to call this function, passing in the number of disks, and the start and end peg numbers. This gave me the following...</p> <pre class="lang-lisp prettyprint-override"><code>(define (hanoi n) (define (free-peg from to) (- 6 (+ from to))) (define (move-tower n from to) (if (= n 0) empty (append (move-tower (- n 1) from (free-peg from to)) (list (list from to)) (move-tower (- n 1) (free-peg from to) to))) ) (move-tower n 1 3)) </code></pre> <p>This seems to work correctly, and gives a list of 2-tuples, each of which tells you the <em>from</em> and <em>to</em> peg for that step. For example, a 3 disk solution is...</p> <pre><code>'((1 3) (1 2) (3 2) (1 3) (2 1) (2 3) (1 3)) </code></pre> <p>Anyone able to comment on my code? Specifically, I run out of memory when I give it a large number of disks. I've been reading about tail recursion, but don't understand it well enough to know if it would help me here. Would that enable me to run this with bigger numbers?</p> <p>Thanks for any advice you can give. Remember, I'm very new at Racket (and Lisp in general), so please explain in words of one syllable!</p>
[]
[ { "body": "<p>The code looks fine, though I'd suggest to follow the usual Lisp style\nand not having dangling parentheses around:</p>\n<pre class=\"lang-lisp prettyprint-override\"><code>(define (hanoi n)\n (define (free-peg from to)\n (- 6 (+ from to)))\n (define (move-tower n from to)\n (if (= n 0)\n empty\n (append (move-tower (- n 1) from (free-peg from to))\n (list (list from to))\n (move-tower (- n 1) (free-peg from to) to))))\n (move-tower n 1 3))\n</code></pre>\n<p>The nested functions are fine, even elegant.</p>\n<p>With regards to optimisation, Tail Call Optimisation won't help you\nhere, since you're still calling <code>append</code> and there's simply no tail\ncalls to optimise. However, look into\n<a href=\"https://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow noreferrer\">memoisation</a>, e.g. the\n<a href=\"https://docs.racket-lang.org/memoize/index.html\" rel=\"nofollow noreferrer\"><code>memoize</code></a> library:</p>\n<pre class=\"lang-lisp prettyprint-override\"><code>(require memoize)\n\n(define (hanoi n)\n (define (free-peg from to)\n (- 6 from to))\n (define/memo (move-tower n from to)\n (if (= n 0)\n empty\n (append (move-tower (- n 1) from (free-peg from to))\n (list (list from to))\n (move-tower (- n 1) (free-peg from to) to))))\n (move-tower n 1 3))\n</code></pre>\n<p>With that, <code>(hanoi 20)</code> doesn't crash, it just takes a very long time to\nprint the result, as expected.</p>\n<p>Note that I didn't memoise the overall\nresult, but the actual recursive calls, memoising <code>free-peg</code> isn't\nuseful here either, since it's such a small function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T14:43:15.070", "Id": "516086", "Score": "1", "body": "Thanks for that. The reason for the dangling bracket was that whilst timing the function, I added a \"0\" as the last expression, to save DrRacket printing the full list out (which often took longer than the execution!). I removed the zero when I posted here, but forgot to shift the closing bracket back up :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T14:44:33.073", "Id": "516087", "Score": "1", "body": "Thanks also for directing me to memoize. I had just read about memoisation last night, but the book I was reading showed how to write your own code. Good to know there's a library for it (although writing your own code is a great way to understand what's going on). Thanks again." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T13:56:52.003", "Id": "261512", "ParentId": "261476", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T17:36:33.443", "Id": "261476", "Score": "1", "Tags": [ "lisp", "racket", "tower-of-hanoi" ], "Title": "Tower of Hanoi in Racket" }
261476
<p>I have about 977 obs in <code>top500Stocks</code> which contains name of 977 stocks.</p> <pre><code>head(top500Stocks,10) ï..Symbol 1 RELIANCE 2 TCS 3 HDFCBANK 4 INFY 5 HINDUNILVR 6 HDFC 7 ICICIBANK 8 KOTAKBANK 9 SBIN 10 BAJFINANCE </code></pre> <p>and I have Date, OHLC and Adj.Close, Vol and Ret of each stocks from the top500Stocks in stocksRetData</p> <pre><code> head(stocksRetData[[1]],3) Date Open High Low Close Adj.Close Volume Ret 1 20000103 28.18423 29.86935 28.18423 38.94457 29.86935 28802010 0.000 2 20000104 30.66445 32.26056 29.82188 42.06230 32.26056 61320457 0.080 3 20000105 30.45677 34.16522 30.45677 43.71014 33.52440 173426953 0.039 </code></pre> <p>Now for a given lookbackPeriod and holdPeriod I am trying to run the below function but it takes about 1 minute. How can I make it faster? Because I have to run for multiple lookbackPeriod and holdPeriod it will take forever to complete.</p> <pre><code>CalC.MOD_MScore.Ret.High &lt;- function(lookbackPeriod, holdPeriod, fnoStocks, stocksRetData, totalTestPeriod) { #We go through each stock and calculate Modified mscores where we give more importance to recent data WeeklyData &lt;- list() wmean &lt;- function(x, k) mean(seq(k)/k * x) for (i in 1:nrow(fnoStocks)){ out &lt;- stocksRetData[[i]] out &lt;- tail(out,totalTestPeriod) if (nrow(out)==totalTestPeriod){ tempDF &lt;- transform(out, wtMean = rollapply(Ret, lookbackPeriod, wmean, k = lookbackPeriod, align = &quot;right&quot;, fill = NA)) tempDF &lt;- transform(tempDF, ExitVal = rollapply(lead(High, holdPeriod), holdPeriod, max, align = &quot;right&quot;, fill = NA)) tempDF$NWeekRet &lt;- (tempDF$ExitVal - tempDF$Adj.Close ) / tempDF$Adj.Close tempDF &lt;- tempDF[!is.na(tempDF$wtMean),] tempDF &lt;- tempDF[!is.na(tempDF$ExitVal),] tempDF$StockName = fnoStocks[i,1] tempDF$WeekNum = c((lookbackPeriod):(nrow(tempDF)+lookbackPeriod-1)) WeeklyData[[i]] &lt;- data.frame( StockName = tempDF$StockName, WeekNum = tempDF$WeekNum, M_Score = tempDF$wtMean, NWeekRet = tempDF$NWeekRet, stringsAsFactors = FALSE ) } }# i ends here return(bind_rows(WeeklyData)) } </code></pre> <p>This takes more than a minute to complete.</p> <pre><code> a &lt;- CalC.MOD_MScore.Ret.High(4,14,fnoStocks = top500Stocks, stocksRetData = stocksRetData, 2000) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T08:18:20.027", "Id": "516055", "Score": "0", "body": "can you supply the data so the code can be tested?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T08:20:06.637", "Id": "516056", "Score": "0", "body": "@minem sure but where do I upload it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T08:31:07.627", "Id": "516057", "Score": "0", "body": "@minem top500Stocks contains 977 unique strings in column 1. And stocksRetData contains list of 977 dataframes with data in above format. Other than that no other data is used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T12:35:18.220", "Id": "516079", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T10:00:50.030", "Id": "516120", "Score": "0", "body": "@Stupid_Intern updated my answer" } ]
[ { "body": "<p>Fake data:</p>\n<pre><code>set.seed(1)\nn1 &lt;- 977\ntop500Stocks &lt;- data.frame(a = sample(letters, n1, replace = T))\nn &lt;- 2000\ndf &lt;- data.frame(High = rnorm(n),\n Adj.Close = rnorm(n),\n Ret = rnorm(n))\nstocksRetData &lt;- lapply(1:n1, function(x) df)\n</code></pre>\n<p>new function:</p>\n<pre><code>require(data.table)\nminem &lt;- function(lookbackPeriod, holdPeriod, fnoStocks, stocksRetData, totalTestPeriod) {\n \n WeeklyData &lt;- list()\n k &lt;- lookbackPeriod\n y &lt;- seq(k)/k/k\n wmean2 &lt;- function(x) sum(y * x)\n \n for (i in 1:nrow(fnoStocks)) {\n \n out &lt;- tail(stocksRetData[[i]], totalTestPeriod)\n \n if (nrow(out) == totalTestPeriod) {\n \n wtMean &lt;- frollapply(out$Ret, k, wmean2, align = &quot;right&quot;, fill = NA)\n ExitVal &lt;- frollapply(lead(out$High, holdPeriod), \n holdPeriod, max, align = &quot;right&quot;, fill = NA)\n tempDF &lt;- out\n tempDF$wtMean &lt;- wtMean\n tempDF$ExitVal &lt;- ExitVal\n tempDF$NWeekRet &lt;- (ExitVal / tempDF$Adj.Close - 1)\n \n tempDF &lt;- tempDF[!is.na(wtMean),]\n tempDF &lt;- tempDF[!is.na(tempDF$ExitVal),]\n tempDF$StockName = fnoStocks[i, 1]\n tempDF$WeekNum = c(k:(nrow(tempDF) + k - 1))\n \n WeeklyData[[i]] &lt;- tempDF[, c('StockName', 'WeekNum', 'wtMean', 'NWeekRet')]\n colnames(WeeklyData[[i]])[3] &lt;- 'M_Score'\n }\n }# i ends here\n return(bind_rows(WeeklyData))\n}\n</code></pre>\n<p>speed:</p>\n<pre><code>system.time(a2 &lt;- minem(4, 14, top500Stocks, stocksRetData, 2000))\n# user system elapsed \n# 2.36 0.00 2.36\n</code></pre>\n<p>(versus 31.75 seconds for original on my machine)</p>\n<p>some comments:</p>\n<ol>\n<li><p>from code profiling we see that <code>wmean</code> was the slowest part(called thousands of times). As we know <code>k</code>(lookbackPeriod) beforehand we can simplify/speedup this function.</p>\n</li>\n<li><p><code>rollapply</code> was quite slow. replacing it with <code>data.table</code>s <code>frollapply</code> we gain performance</p>\n</li>\n<li><p>creating new <code>data.frame</code> in loop isn't efficient, we can reuse <code>tempDF</code> (but this isn't as significant as first two points)</p>\n</li>\n<li><p>other minor changes</p>\n</li>\n</ol>\n<h2>update</h2>\n<p>we can go faster:</p>\n<pre><code>minem2 &lt;- function(lookbackPeriod, holdPeriod, fnoStocks, \n stocksRetData, totalTestPeriod) {\n \n k &lt;- lookbackPeriod\n y &lt;- seq(k)/k/k\n \n # create stock name data.table\n sn &lt;- data.table(sname = fnoStocks[[1]], id = 1:nrow(fnoStocks), key = 'id')\n dt &lt;- rbindlist(stocksRetData[1:nrow(fnoStocks)], idcol = 'id') # bind together data\n setkey(dt, id)\n dt &lt;- dt[, tail(.SD, totalTestPeriod), by = id] # select last n rows by group\n dt[sn, StockName := sname] # merge stock names\n \n # calculate wtMean using tcrossprod:\n v &lt;- shift(dt$Ret, (k:1) - 1L) # create list of lagged values\n v &lt;- do.call(cbind, v) # bind together\n dt[, wtMean := tcrossprod(y, v)[1, ]]\n dt[1:(k - 1), wtMean := NA, by = id] # delete first (k-1) as they aren't correct\n # maybe not needed\n \n # the same approach for ExitVal as it was sufficiently fast\n dt[, ExitVal := frollapply(lead(High, holdPeriod), holdPeriod, max,\n align = &quot;right&quot;, fill = NA), by = id]\n \n dt[, NWeekRet := (ExitVal / Adj.Close - 1)]\n dt &lt;- dt[!is.na(wtMean) &amp; !is.na(ExitVal)]\n dt[, WeekNum := c(k:(.N + k - 1)), by = id]\n res &lt;- dt[, .(StockName, WeekNum, M_Score = wtMean, NWeekRet)]\n return(res[])\n}\n\nsystem.time(a3 &lt;- minem2(4, 14, top500Stocks, stocksRetData, 2000))\n# user system elapsed \n# 0.91 0.01 0.78 \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T13:31:34.077", "Id": "516132", "Score": "0", "body": "Thank you for your help. It works wonderfully. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T12:30:17.747", "Id": "261509", "ParentId": "261477", "Score": "1" } } ]
{ "AcceptedAnswerId": "261509", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T17:43:52.200", "Id": "261477", "Score": "0", "Tags": [ "performance", "r", "memory-optimization" ], "Title": "R code optimization" }
261477
<p>I wrote this module to find the <a href="https://en.wikipedia.org/wiki/Hamming_distance" rel="nofollow noreferrer">Hamming distance</a> between two strings. (It's a problem from <code>exercism.io</code>'s Haskell track.)</p> <p>As I saw it, the problem has two distinct parts: check if the length of the two strings are equal (if not return <code>Nothing</code>), and recursive pattern matching on equal-length strings.</p> <p>Since my score is a monad (Maybe), I didn't know how to implement the recursive adding without dealing with the <code>Nothing</code> case, so I broke it off into a separate function using a simple Int type.</p> <p>GHC raises <code>warning: [-Wincomplete-patterns]</code> since my pattern matching in the helper function is incomplete. So:</p> <ol> <li>Is it bad practice to ignore this warning?</li> <li>Would it be better to implement the recursive part on the Maybe?</li> <li>Is there a better way to solve this problem?</li> </ol> <p>I'm very new to Haskell, all help appreciated.</p> <pre><code>module Hamming (distance) where distance :: String -&gt; String -&gt; Maybe Int distance a b | length a /= length b = Nothing | otherwise = Just $ getDistance a b getDistance :: String -&gt; String -&gt; Int getDistance [] [] = 0 getDistance [x] [y] = if x == y then 0 else 1 getDistance (x : xs) (y : ys) = getDistance [x] [y] + getDistance xs ys </code></pre>
[]
[ { "body": "<p>To address your title question (&quot;Is it wrong...&quot;), no, I wouldn't say that it's wrong. Using more top-level functions is nearly always a great way to decompose your problem into smaller, easier to digest bits that are simpler to solve. That said the split that you chose to make doesn't meet that goal. Your functions are tightly coupled in that <code>distance</code> relies on <code>getDistance</code> to provide an answer, and <code>getDistance</code> relies on <code>distance</code> to prepare its arguments correctly. A slightly better version might be to move <code>getDistance</code> into a <code>where</code>-clause underneath <code>distance</code>.</p>\n<p>Regarding your numbered questions—</p>\n<ol>\n<li><p>I consider it a tenet of good practice to not ignore any warnings emitted by the compiler. The moment you do so you begin training your brain to ignore all warnings emitted by the compiler, and you'll eventually miss something meaningful because it's buried in the noise of compiler barf.</p>\n</li>\n<li><p>&quot;the recursive part on the Maybe?&quot; I don't think this maps well grammatically to how you should be conceptualizing return values. The fact that <code>Maybe</code> is an instance of <code>Monad</code> doesn't actually come up in your code, you just use it as a pure value. See below for other ways to solve problems when your intermediary values are a mismatch for your return values.</p>\n</li>\n<li><p>There are many ways I could imagine solving this problem, better is going to be a function of how robust you want your code to be, what dependencies you are comfortable adding, how clever (read: tricky) you feel comfortable leaving your code, and more.</p>\n</li>\n</ol>\n<p>What follows are a bunch of lightly commented solutions, demonstrating different ways of approaching the problem.</p>\n<pre><code>hamming :: Eq a =&gt; [a] -&gt; [a] -&gt; Int\nhamming [] [] = 0\nhamming (x:xs) (y:ys) = (if x == y then 0 else 1) + hamming xs ys\nhamming _ _ = error &quot;hamming: Can't compute Hamming distance of lists of different length&quot;\n</code></pre>\n<p>This version just makes the strings being of equal length a precondition. We make the type of the function less specific because it helps us not write the wrong implementation (e.g., all you know about two <code>a</code> values is whether or not they're <code>Eq</code> here, but if you know you have <code>String</code>s you could compare on letter case or anything else).</p>\n<pre><code>hamming :: Eq a =&gt; [(a, a)] -&gt; Int\nhamming [] = 0\nhamming ((x, y) : xys) = (if x == y then 0 else 1) + hamming xys\n</code></pre>\n<p>This version makes it incumbent on the caller to provide a list of pairs, instead of a pair of lists. Now it's not possible to have mismatched lengths.</p>\n<pre><code>safeHamming :: Eq a =&gt; [a] -&gt; [a] -&gt; Maybe Int\nsafeHamming [] [] = Just 0\nsafeHamming (x:xs) (y:ys) = (+ if x == y then 0 else 1) &lt;$&gt; safeHamming xs ys\nsafeHamming _ _ = Nothing\n</code></pre>\n<p>This version uses <code>fmap</code> (<code>&lt;$&gt;</code> is <code>fmap</code> infix) to increment the returned value of the sub-problem (i.e. the shorter rest of the string). It uses the <code>Functor</code>ness of <code>Maybe</code>, but still not the <code>Monad</code> instance.</p>\n<pre><code>safeHamming :: Eq a =&gt; [a] -&gt; [a] -&gt; Maybe Int\nsafeHamming = go 0\n where\n go d [] [] = Just d\n go d (x:xs) (y:ys) = go (d + if x == y then 0 else 1) xs ys\n go _ _ _ = Nothing\n</code></pre>\n<p>Sometimes an accumulator value is easier to work on than a return value.</p>\n<hr />\n<p>What would be really great is if we could eliminate the explicit recursion in our solution altogether, leveraging existing functions to both avoid having to write as much code and to make our function easier for future readers to understand. Something like—</p>\n<pre><code>hamming :: Eq a =&gt; [a] -&gt; [a] -&gt; Int\nhamming = length . filter id . zipWith (==)\n</code></pre>\n<p>But as clever as that function is, Haskell's standard <code>zip</code>s all silently ignore when the lengths of the lists are mismatched by discarding the tail of the longer list. For a coding exercise (i.e. throwaway code) I'd probably just use that version though.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T22:04:34.173", "Id": "261486", "ParentId": "261482", "Score": "5" } }, { "body": "<p>When you have a function where not every possible input value can be mapped to one of the possible output values, you have three options: Allow fewer inputs, allow more outputs, or declare that your function is partial rather than total and just isn't well-behaved sometimes.</p>\n<ul>\n<li>The first is arguably the most flexible, but often involves some awkward re-shaping of your data. In this case that would mean a function that takes two strings that are <em>guaranteed</em> to be the same length somehow and definitely returns an <code>Int</code>. Can we do that? Well, we may be able to do something similar, but we'll get to that later. I'll call that function <code>hamming</code> just to give it a name</li>\n<li>The second is a good middle ground, and it's our current mission. <code>distance :: String -&gt; String -&gt; Maybe Int</code>. This is slightly weaker than the first option, because you can use <code>hamming</code> to define <code>distance</code>, but not necessarily the other way around. Still, this is often easier to write, and a bit less awkward to use.</li>\n<li>The third is by far the easiest to do, but it also means your function becomes harder to reason about in some ways. If I ever use a partial function like this <code>getDistance :: String -&gt; String -&gt; Int</code>, the computer doesn't know whether my use of it is well-behaved or not until it actually tries it because, well, all the computer knows is that sometimes that function doesn't play nice. Proving that some combination of non-total functions is itself total is <em>hard</em>, so if we can start from total functions it becomes easy (or at least easier) to convince both ourselves and the computer that the code does what we want it to do.</li>\n</ul>\n<p>Type safety is like a wall, and partial functions are holes in that. There's definitely a place for making holes in walls, I appreciate <code>fromJust</code>, <code>undefined</code>, and infinite recursion, just like how I appreciate doorways. But if you have too many holes it doesn't really keep the wind out anymore, even though you'll probably still find it blocking your view.</p>\n<p>So, can we write this code so that a computer can trust that it's total and type-safe? Well, the type of <code>distance</code> doesn't seem to be making any promises we can't keep, so it should be possible. Let's start with something like <code>getDistance</code> and see where we can end up</p>\n<pre><code>distance :: (Eq a) =&gt; [a] -&gt; [a] -&gt; Maybe Int\n</code></pre>\n<p>Notice the switch from <code>String</code> to <code>Eq a =&gt; [a]</code> - we can afford to be less specific here because we don't actually <em>do</em> anything with that specificity. There's no reason we need to work with <code>[Char]</code> in particular after all</p>\n<pre><code>distance [] [] = Just 0\ndistance [] _ = Nothing\ndistance _ [] = Nothing\n</code></pre>\n<p>Those are some simple cases with obvious outcomes, so let's make those our base cases. Now let's try some recursion. But how?</p>\n<p>Well, pattern matching is easy to read and write, and effective, so we could just do a <code>case</code> split</p>\n<pre><code>distance (x : xs) (y : ys) =\n case (distance xs ys) of\n Nothing -&gt; Nothing\n Just d -&gt; Just ((if x == y then 0 else 1) + d)\n</code></pre>\n<p>Or we can take advantage of how <code>Maybe</code> is a <code>Functor</code> and do something fancier like</p>\n<pre><code>distance (x : xs) (y : ys) = fmap f (distance xs ys)\n where f = if x == y then (+ 0) else (+ 1)\n</code></pre>\n<p>Either way, we have a perfectly fine <code>distance</code> function. And this time it's total, which makes the computer slightly happier.</p>\n<p>But what was that other thing I said earlier? Can we really have a function which takes two lists that are guaranteed to be the same size? Because that sounds useful!</p>\n<p>Well, kind of. It just looks a bit different than you might expect</p>\n<pre><code>hamming :: (Eq a) =&gt; [(a, a)] -&gt; Int\nhamming [] = 0\nhamming ((a, b) : rest) = (if a == b then 0 else 1) + (hamming rest)\n</code></pre>\n<p>Is that cheating? Maybe a bit, but it's still useful. A list of pairs is exactly the same as a pair of equal-length lists in terms of the stuff they're made of anyway, they're just in a slightly different shapes. And if we have two zipped list we can get their hamming distance without having to worry about <code>Maybe</code> at all and still be completely type-safe. Neat!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T23:31:24.277", "Id": "261489", "ParentId": "261482", "Score": "10" } } ]
{ "AcceptedAnswerId": "261489", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T20:18:41.217", "Id": "261482", "Score": "6", "Tags": [ "beginner", "programming-challenge", "haskell", "edit-distance", "monads" ], "Title": "Hamming distance between two strings" }
261482
<p>I decided I wanted to make a console-like system. So, I started planning &amp; creating it in <a href="/questions/tagged/c%23" class="post-tag" title="show questions tagged &#39;c#&#39;" rel="tag">c#</a>. Currently, all that it is is a processor of sorts. It reads all bytes from a file (<code>R:\disk00</code>), and then executes them, somewhat like a CPU. <code>display.pyw</code> is a simple <a href="/questions/tagged/pygame" class="post-tag" title="show questions tagged &#39;pygame&#39;" rel="tag">pygame</a> application which reads <code>R:\disk01</code> and displays the characters therein.<br /> <em>(To run this, you need to have an <code>R:</code> drive mounted and at least <code>disk00</code> and <code>disk01</code> files. <code>disk01</code> should be 512 bytes long.)</em></p> <p>I've never actually done anything like this, so I'm proud of this project. Currently, though, I want it to be faster. Since eventually, I'll be creating full games in this, I need it to be fast. I've made it fairly fast, but I'm sure that it can be improved. Also, my code is normally overengineered, so I'm sure there's a bit I can improve.</p> <p>This is my first post here so I'm hoping I didn't mess it up. Thanks!</p> <pre class="lang-cs prettyprint-override"><code>// Program.cs using System; using System.Text; namespace BarkleySRC { class Program { public static long CMS() { return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); } static void Main(string[] args) { Processor Proc = new Processor(); long time1 = CMS(); Proc.begin(&quot;R:\\disk00&quot;); long time2 = CMS(); double difference = time2 - time1; Console.WriteLine($&quot;Finished in {difference/1000} seconds @ ~{Proc.registers[10] / (difference/1000)} ops/second\n&quot;); string[] registernames = new string[] { &quot;EAX &quot;, &quot;EBX &quot;, &quot;ECX &quot;, &quot;EDX &quot;, &quot;ESP &quot;, &quot;EIP &quot;, &quot;IAX &quot;, &quot;IBX &quot;, &quot;EIX &quot;, &quot;CPUFLG&quot;, &quot;ETCX &quot; }; for (int i = 0; i &lt; Proc.registers.Length; i++) Console.WriteLine($&quot;{registernames[i]} &quot; + $&quot;{Proc.registers[i].ToString(&quot;X&quot;).PadLeft(8, '0')} &quot; + $&quot;{Convert.ToString(Proc.registers[i], 2).PadLeft(32, '0')}&quot;); } } } </code></pre> <pre class="lang-cs prettyprint-override"><code>// Processor.cs using System; using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; using System.Threading; public class Processor { Dictionary&lt;int, uint&gt; registerSegments = new Dictionary&lt;int, uint&gt; { { 0, 0xFFFFFF00 }, { 1, 0xFFFF00FF }, { 2, 0xFFFF0000 }, { 3, 0x00000000 }, }; Dictionary&lt;int, int&gt; sizint_lengths = new Dictionary&lt;int, int&gt; { { 0, 1 }, { 1, 2 }, { 2, 2 }, { 3, 4 }, }; Dictionary&lt;int, int&gt; sizint_bitshift = new Dictionary&lt;int, int&gt; { { 0, 0 }, { 1, 8 }, { 2, 0 }, { 3, 0 }, }; public uint[] registers = new uint[] { // GENERAL PURPOSE REGISTERS 0x00000000, // EAX 0 0x00000000, // EBX 1 0x00000000, // ECX 2 0x00000000, // EDX 3 // POINTER REGISTERS 0x00000000, // ESP 4 0x00000000, // EIP 5 // INTERRUPT REGISTERS 0x00000000, // IAX 6 0x00000000, // IBX 7 0x00000000, // EIX 8 // CPU RELATED 0x00000000, // CPUFLG 9 0x00000000, // ETCX 10 }; public uint[] cmp = new uint[2] { 0, 0 }; public int interrupt = -1; /* Disknum : bytes */ private Dictionary&lt;int, byte[]&gt; CachedDisks = new Dictionary&lt;int, byte[]&gt;(); /* [segmentmin : segmentmax] : [Segments, disk] */ private Dictionary&lt;int[], int[]&gt; DiskRanges = new Dictionary&lt;int[], int[]&gt;(); bool quit = false; public async void begin(string path) { byte[] bytes = File.ReadAllBytes(path); while (!quit) { uint addr = registers[5]; if (addr &gt;= bytes.Length) { Console.WriteLine($&quot;Access fault&quot;); Environment.Exit(1); } switch (bytes[addr]) { case 0: registers[5]++; break; // NOP case 0xFF: quit = true; break; // QUIT case 0x20: // CMPR { byte rbyte1 = bytes[addr + 1]; byte rbyte2 = bytes[addr + 2]; uint rval1 = registers[rbyte1 &amp; 0b00111111] // Get the unsegmented value of the register &amp; ~registerSegments[(rbyte1 &amp; 0b11000000) &gt;&gt; 6]; // Segment register uint rval2 = registers[rbyte2 &amp; 0b00111111] // Get the unsegmented value of the register &amp; ~registerSegments[(rbyte2 &amp; 0b11000000) &gt;&gt; 6]; // Segment register cmp[0] = rval1; cmp[1] = rval2; registers[5] += 3; break; } case 0x21: // CMPI { byte rbyte = bytes[addr + 1]; uint rval = registers[rbyte &amp; 0b00111111] // Get the unsegmented value of the register &amp; ~registerSegments[(rbyte &amp; 0b11000000) &gt;&gt; 6]; // Segment register uint immn = Unsafe.As&lt;byte, uint&gt;(ref bytes[addr + 2]); cmp[0] = rval; cmp[1] = immn; registers[5] += 6; break; } case 0x22: // JMP { uint address = Unsafe.As&lt;byte, uint&gt;(ref bytes[addr + 1]); registers[5] = address; break; } case 0x23: // JE { if (cmp[0] == cmp[1]) { registers[5] = Unsafe.As&lt;byte, uint&gt;(ref bytes[addr + 1]); } else { registers[5] += 5; } break; } case 0x24: // JNE { if (cmp[0] != cmp[1]) { registers[5] = Unsafe.As&lt;byte, uint&gt;(ref bytes[addr + 1]); } else { registers[5] += 5; } break; } case 0x25: // JG { if (cmp[0] &gt; cmp[1]) { registers[5] = Unsafe.As&lt;byte, uint&gt;(ref bytes[addr + 1]); } else { registers[5] += 5; } break; } case 0x26: // JGE { if (cmp[0] &gt;= cmp[1]) { registers[5] = Unsafe.As&lt;byte, uint&gt;(ref bytes[addr + 1]); } else { registers[5] += 5; } break; } case 0x27: // JL { if (cmp[0] &lt; cmp[1]) { registers[5] = Unsafe.As&lt;byte, uint&gt;(ref bytes[addr + 1]); } else { registers[5] += 5; } break; } case 0x28: // JLE { if (cmp[0] &lt;= cmp[1]) { registers[5] = Unsafe.As&lt;byte, uint&gt;(ref bytes[addr + 1]); } else { registers[5] += 5; } break; } case 0x30: // SET { uint immn = Unsafe.As&lt;byte, uint&gt;(ref bytes[addr + 2]); int sizint = (bytes[addr + 1] &amp; 0b11000000) &gt;&gt; 6; int regint = bytes[addr + 1] &amp; 0b00111111; registers[regint] &amp;= registerSegments[sizint]; registers[regint] |= immn &amp; ~registerSegments[sizint]; registers[5] += (uint)(2 + sizint_lengths[sizint]); break; } case 0x31: // CLN { byte rbyte1 = bytes[addr + 1]; byte rbyte2 = bytes[addr + 2]; uint rval = registers[rbyte2 &amp; 0b00111111] // Get the unsegmented value of the register &amp; ~registerSegments[(rbyte2 &amp; 0b11000000) &gt;&gt; 6]; // Segment register registers[rbyte1 &amp; 0b00111111] = registers[rbyte1 &amp; 0b00111111] // Get/set ungegmented value of the register &amp; registerSegments[(rbyte1 &amp; 0b11000000) &gt;&gt; 6] // Filter unwanted bits | rval &amp; ~registerSegments[(rbyte1 &amp; 0b11000000) &gt;&gt; 6]; // OR in wanted bits registers[5] += 3; break; } case 0x32: // FTC { byte rbyte1 = bytes[addr + 1]; byte rbyte2 = bytes[addr + 2]; uint address = registers[rbyte2 &amp; 0b00111111] // Get the unsegmented value of the register &amp; ~registerSegments[(rbyte2 &amp; 0b11000000) &gt;&gt; 6]; // Segment register byte fetched = 0x00; foreach (int[] _range in DiskRanges.Keys) { long num = (address / 512 - _range[0]) * (address / 512 - _range[1]); if (num &gt;= 0 &amp;&amp; num &lt;= 1) { address -= (uint)(512 * _range[0]); if (address &gt;= CachedDisks[DiskRanges[_range][1]].Length) { Console.WriteLine($&quot;Access fault @ {addr:X}&quot;); Environment.Exit(1); } fetched = CachedDisks[DiskRanges[_range][1]][address]; } else { if (address &gt;= bytes.Length) { Console.WriteLine($&quot;Access fault @ {addr:X}&quot;); Environment.Exit(1); } fetched = bytes[address]; } } registers[rbyte1 &amp; 0b00111111] = fetched &amp; ~registerSegments[(rbyte1 &amp; 0b11000000) &gt;&gt; 6]; // OR in wanted bits registers[5] += 3; break; } case 0x33: // INC { byte rbyte = bytes[addr+1]; uint rval = registers[rbyte &amp; 0b00111111]; // Get the unsegmented value of the register uint targetval = rval &amp; ~registerSegments[(rbyte &amp; 0b11000000) &gt;&gt; 6]; rval &amp;= registerSegments[(rbyte &amp; 0b11000000) &gt;&gt; 6]; targetval &gt;&gt;= sizint_bitshift[(rbyte &amp; 0b11000000) &gt;&gt; 6]; targetval++; targetval &lt;&lt;= sizint_bitshift[(rbyte &amp; 0b11000000) &gt;&gt; 6]; registers[rbyte &amp; 0b00111111] = rval | targetval; registers[5] += 2; break; } case 0x34: // DEC { byte rbyte = bytes[addr + 1]; uint rval = registers[rbyte &amp; 0b00111111]; // Get the unsegmented value of the register uint targetval = rval &amp; ~registerSegments[(rbyte &amp; 0b11000000) &gt;&gt; 6]; rval &amp;= registerSegments[(rbyte &amp; 0b11000000) &gt;&gt; 6]; targetval &gt;&gt;= sizint_bitshift[(rbyte &amp; 0b11000000) &gt;&gt; 6]; targetval--; targetval &lt;&lt;= sizint_bitshift[(rbyte &amp; 0b11000000) &gt;&gt; 6]; registers[rbyte &amp; 0b00111111] = rval | targetval; registers[5] += 2; break; } case 0x35: // ADD { byte rbyte = bytes[addr + 1]; uint immn = Unsafe.As&lt;byte, uint&gt;(ref bytes[addr + 2]); int sizint = (rbyte &amp; 0b11000000) &gt;&gt; 6; int regint = rbyte &amp; 0b00111111; uint rval = registers[regint]; immn &lt;&lt;= sizint_bitshift[sizint]; immn &amp;= ~registerSegments[sizint]; rval += immn; registers[regint] = rval; registers[5] += 2 + (uint)sizint_lengths[sizint]; break; } case 0x36: // ADR { byte rbyte = bytes[addr + 1]; uint immn = registers[bytes[addr + 2] &amp; 0b00111111]; int sizint = (rbyte &amp; 0b11000000) &gt;&gt; 6; int regint = rbyte &amp; 0b00111111; uint rval = registers[regint]; immn &lt;&lt;= sizint_bitshift[sizint]; immn &amp;= ~registerSegments[sizint]; rval += immn; registers[regint] = rval; registers[5] += 3; break; } case 0x37: // SUB { byte rbyte = bytes[addr + 1]; uint immn = Unsafe.As&lt;byte, uint&gt;(ref bytes[addr + 2]); int sizint = (rbyte &amp; 0b11000000) &gt;&gt; 6; int regint = rbyte &amp; 0b00111111; uint rval = registers[regint]; immn &lt;&lt;= sizint_bitshift[sizint]; immn &amp;= ~registerSegments[sizint]; rval -= immn; registers[regint] = rval; registers[5] += 2 + (uint)sizint_lengths[sizint]; break; } case 0x38: // SUBR { byte rbyte = bytes[addr + 1]; uint immn = registers[bytes[addr + 2] &amp; 0b00111111]; int sizint = (rbyte &amp; 0b11000000) &gt;&gt; 6; int regint = rbyte &amp; 0b00111111; uint rval = registers[regint]; immn &lt;&lt;= sizint_bitshift[sizint]; immn &amp;= ~registerSegments[sizint]; rval -= immn; registers[regint] = rval; registers[5] += 3; break; } case 0x39: // NOT { byte rbyte = bytes[addr + 1]; uint rval = registers[rbyte &amp; 0b00111111]; uint wval = rval &amp; ~registerSegments[(rbyte &amp; 0b11000000) &gt;&gt; 6]; rval &amp;= registerSegments[(rbyte &amp; 0b11000000) &gt;&gt; 6]; wval = ~wval; rval |= wval &amp; ~registerSegments[(rbyte &amp; 0b11000000) &gt;&gt; 6]; registers[rbyte &amp; 0b00111111] = rval; registers[5] += 2; break; } case 0x3A: // OR [r8 immn32] { byte rbyte = bytes[addr + 1]; uint immn = Unsafe.As&lt;byte, uint&gt;(ref bytes[addr + 2]); int sizint = (rbyte &amp; 0b11000000) &gt;&gt; 6; int regint = rbyte &amp; 0b00111111; uint rval = registers[regint]; immn &lt;&lt;= sizint_bitshift[sizint]; immn &amp;= ~registerSegments[sizint]; rval |= immn; registers[regint] = rval; registers[5] += 2 + (uint)sizint_lengths[sizint]; break; } case 0x3B: // OR [r8 r8] { byte rbyte = bytes[addr + 1]; uint immn = registers[bytes[addr + 2] &amp; 0b00111111]; int sizint = (rbyte &amp; 0b11000000) &gt;&gt; 6; int regint = rbyte &amp; 0b00111111; uint rval = registers[regint]; immn &lt;&lt;= sizint_bitshift[sizint]; immn &amp;= ~registerSegments[sizint]; rval |= immn; registers[regint] = rval; registers[5] += 3; break; } case 0x3C: // AND [r8 immn32] { byte rbyte = bytes[addr + 1]; uint immn = Unsafe.As&lt;byte, uint&gt;(ref bytes[addr + 2]); int sizint = (rbyte &amp; 0b11000000) &gt;&gt; 6; int regint = rbyte &amp; 0b00111111; uint rval = registers[regint]; immn &lt;&lt;= sizint_bitshift[sizint]; immn &amp;= ~registerSegments[sizint]; rval &amp;= immn; registers[regint] = rval; registers[5] += 2 + (uint)sizint_lengths[sizint]; break; } case 0x3D: // AND [r8 r8] { byte rbyte = bytes[addr + 1]; uint immn = registers[bytes[addr + 2] &amp; 0b00111111]; int sizint = (rbyte &amp; 0b11000000) &gt;&gt; 6; int regint = rbyte &amp; 0b00111111; uint rval = registers[regint]; immn &lt;&lt;= sizint_bitshift[sizint]; immn &amp;= ~registerSegments[sizint]; rval &amp;= immn; registers[regint] = rval; registers[5] += 3; break; } case 0x3E: // XOR [r8 immn32] { byte rbyte = bytes[addr + 1]; uint immn = Unsafe.As&lt;byte, uint&gt;(ref bytes[addr + 2]); int sizint = (rbyte &amp; 0b11000000) &gt;&gt; 6; int regint = rbyte &amp; 0b00111111; uint rval = registers[regint]; immn &lt;&lt;= sizint_bitshift[sizint]; immn &amp;= ~registerSegments[sizint]; rval ^= immn; registers[regint] = rval; registers[5] += 2 + (uint)sizint_lengths[sizint]; break; } case 0x3F: // XOR [r8 r8] { byte rbyte = bytes[addr + 1]; uint immn = registers[bytes[addr + 2] &amp; 0b00111111]; int sizint = (rbyte &amp; 0b11000000) &gt;&gt; 6; int regint = rbyte &amp; 0b00111111; uint rval = registers[regint]; immn &lt;&lt;= sizint_bitshift[sizint]; immn &amp;= ~registerSegments[sizint]; rval ^= immn; registers[regint] = rval; registers[5] += 3; break; } case 0x40: // INT { short immn = Unsafe.As&lt;byte, short&gt;(ref bytes[addr + 1]); interrupt = immn &amp; 0xFFFF; checkInterrupt(); registers[5] += 3; break; } case 0x41: // I/O branch { registers[5]++; break; } case 0x42: // LDSK { int disk = bytes[addr + 1]; if (!File.Exists(&quot;r:\\disk&quot; + disk.ToString(&quot;X&quot;).PadLeft(2, '0'))) { Console.WriteLine($&quot;Disk fault @ {addr:X}&quot;); Environment.Exit(1); } byte[] buffer = File.ReadAllBytes(&quot;r:\\disk&quot; + disk.ToString(&quot;X&quot;).PadLeft(2, '0')); CachedDisks[disk] = buffer; registers[5] += 2; break; } case 0x43: // MEMRANGE { int disknum = bytes[addr + 1]; int segment0 = Unsafe.As&lt;byte, int&gt;(ref bytes[addr + 2]); int segment1 = Unsafe.As&lt;byte, int&gt;(ref bytes[addr + 6]); if (CachedDisks.ContainsKey(disknum)) { DiskRanges[new int[] { segment0, segment1 }] = new int[] { segment1 - segment0, disknum }; } registers[5] += 10; break; } case 0x44: // STM { uint address = Unsafe.As&lt;byte, uint&gt;(ref bytes[addr + 2]); if (DiskRanges.Keys.Count &gt; 0) { foreach (int[] _range in DiskRanges.Keys) { long num = (address / 512 - _range[0]) * (address / 512 - _range[1]); if (num &gt;= 0 &amp;&amp; num &lt;= 1) { int disk = DiskRanges[_range][1]; address -= (uint)(512 * _range[0]); if (address &gt;= CachedDisks[disk].Length) { Console.WriteLine($&quot;Disk Access fault @ {addr:X}&quot;); Environment.Exit(1); } CachedDisks[disk][address] = bytes[addr + 1]; try { await File.WriteAllBytesAsync(&quot;r:\\disk&quot; + disk.ToString(&quot;X&quot;).PadLeft(2, '0'), CachedDisks[disk]); } finally { } } else { bytes[address] = bytes[addr + 1]; } } } else { if (address &gt;= bytes.Length) { Console.WriteLine($&quot;Access fault @ {addr:X}&quot;); Environment.Exit(1); } bytes[address] = bytes[addr + 1]; } registers[5] += 6; break; } case 0x45: // STM { byte rbyte = bytes[addr + 2]; uint address = registers[rbyte &amp; 0b00111111] &amp; ~registerSegments[(rbyte &amp; 0b11000000) &gt;&gt; 6]; if (DiskRanges.Keys.Count &gt; 0) { foreach (int[] _range in DiskRanges.Keys) { long num = (address / 512 - _range[0]) * (address / 512 - _range[1]); if (num &gt;= 0 &amp;&amp; num &lt;= 1) { int disk = DiskRanges[_range][1]; address -= (uint)(512 * _range[0]); if (address &gt;= CachedDisks[disk].Length) { Console.WriteLine($&quot;Disk Access fault @ {addr:X}&quot;); Environment.Exit(1); } CachedDisks[disk][address] = bytes[addr + 1]; try { await File.WriteAllBytesAsync(&quot;r:\\disk&quot; + disk.ToString(&quot;X&quot;).PadLeft(2, '0'), CachedDisks[disk]); } finally { Console.WriteLine(&quot;Diskwrite error&quot;); } } else { bytes[address] = bytes[addr + 1]; } } } else { if (address &gt;= bytes.Length) { Console.WriteLine($&quot;Access fault @ {addr:X}&quot;); Environment.Exit(1); } bytes[address] = bytes[addr + 1]; } registers[5] += 3; break; } default: // INVALID Console.WriteLine($&quot;Invalid opcode 0x{bytes[addr]:X}&quot;); registers[5]++; break; } registers[10]++; } } private void checkInterrupt() { switch (interrupt) { case 0x10: { char print = (char)(registers[6] &amp; 0x000000FF); Console.Write(print.ToString()); break; } } interrupt = -1; } } </code></pre> <pre class="lang-py prettyprint-override"><code># display.pyw import pygame, sys pygame.init() display = pygame.display.set_mode((480, 360)) displayfont = pygame.font.Font('consola.ttf', 18) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() display.fill((0, 0, 0)) with open(&quot;R:\\disk01&quot;, &quot;rb&quot;) as videomem: try: contents = videomem.read() except: contents = bytes(b'') lines = [&quot;&quot;] cl = 0 for b in contents: if len(lines[cl]) &gt;= 48: cl += 1 lines.append(&quot;&quot;) if b &gt;= 0x20 and b &lt; 0x7F: lines[cl] += chr(b) elif b == 0x0A: cl += 1 lines.append(&quot;&quot;) # # 48 x 20 # i = 0 for line in lines: display.blit(displayfont.render(line, True, (255, 255, 255)), (0, i*18)) i += 1 pygame.display.flip() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T16:43:44.707", "Id": "516093", "Score": "0", "body": "Looks nice. Fast && short view: 1) Split logic into more methods especially the repetitive code. 2) avoid `async void`, use `async Task`+`await`. 3) hardcoded paths to files in code, move it to constants 4) registers has names only in comments, you can add some properties like `public uint EAX { get => registers[0]; set => registers[0] = value }`, then use like `EAX++` in code to make it more friendly to read. 4) also you can create `enum` with opcodes. Make as less magic numbers in code as possible." } ]
[ { "body": "<p>Disclaimer: there is a plenty of code. This review is very much incomplete.</p>\n<hr />\n<p>Some design choices are seriously dubious.</p>\n<ul>\n<li><p>The <code>EIP</code> register is not a general purpose register, and you'd be in a better shape using it as <code>EIP</code> rather than <code>registers[5]</code>.</p>\n</li>\n<li><p>Many instructions modify the register value blindly: <code>registers[regint] = regval;</code>. It means that, say, <code>ADD</code> may affect a sensitive register, e.g. <code>ETCX</code> (which apparently is supposed to count execution cycles), or <code>EIP</code>. I doubt it is an intention. Yet again, some registers are not general purpose.</p>\n</li>\n<li><p>Comparison instructions fill up two hidden registers (<code>cmp[0]</code> and <code>cmp[1]</code>), and leave it to jumps to examine them. This is quite unorthodox. Normally, they set certain flags in <code>CPUFLAGS</code> registers (which is BTW unused in this code). Notice that your design prevents other instruction to affect the control flow. Again, a standard approach is to let, say, arithmetical, or logical, instructions to also set flags. Much more flexible.</p>\n</li>\n<li><p>Invalid opcode is usually not ignored, but raises an exception (not in <a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged &#39;c#&#39;\" rel=\"tag\">c#</a> sense, of course). Give a processor a chance to recover. BTW, planting an illegal instruction is a very common technique to implement breakpoints.</p>\n</li>\n<li><p>Calls and returns are sorely missing.</p>\n</li>\n<li><p>Integrating the disk cache into a processor simulator doesn't look comfortable. It is not the processor job to deal with cache.</p>\n</li>\n</ul>\n<hr />\n<ul>\n<li><p><code>case 0x44: // STM</code> and <code>case 0x45: // STM</code> have <em>huge</em> amount of duplication. Ditto <code>case 0x3e</code> and <code>case 0x3f</code>, etc. Factor out the common functionality.</p>\n</li>\n<li><p>I strongly recommend to have an <code>Instruction</code> type, at least to bind the instruction length to an opcode. It is very unclear why such and such instruction takes advances <code>EIP</code> by such and such amount. As a side note, it is very beneficial to advance <code>EIP</code> <em>as soon as you can</em>. You will see it when it comes to calls and returns.</p>\n</li>\n<li><p>As mentioned in the comments, avoid magic numbers.</p>\n</li>\n</ul>\n<hr />\n<p>I don't really understand the segmentation business, so no comments here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T00:03:43.380", "Id": "516269", "Score": "0", "body": "Thank you! I will take these into consideration. And yeah, not checking the register before setting is a bit of a dumb move but hey, who can you trust more than the user? Right..?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T02:08:21.757", "Id": "261530", "ParentId": "261488", "Score": "2" } } ]
{ "AcceptedAnswerId": "261530", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T23:23:11.450", "Id": "261488", "Score": "3", "Tags": [ "python", "c#" ], "Title": "WIP \"Console\" processor, written in C#" }
261488
<p>I am currently participating in research on transient absorption spectroscopy and four wave mixing. In the experimental design, an extreme ultraviolet (XUV) laser pulse and infrared (IR) laser pulse are sent through a finite gas sample with a certain time delay between them. My current task was to develop a function that, given data on the system and input pulses, provides the transmission spectrum of the XUV pulse electric field after exiting the sample.</p> <p>I had originally completed said task in MATLAB, and my post on that version of the program can be found here: <a href="https://codereview.stackexchange.com/questions/261316/simulate-transmission-spectrum-of-extreme-ultraviolet-laser-pulse-through-laser">Simulate transmission spectrum of extreme ultraviolet laser pulse through laser-dressed finite sample</a>. However, I figured it would be a useful exercise to translate the code into python, so as to get a better grasp of python and start the ball rolling on learning more. This python version is thus almost identical to the first MATLAB version in its structure.</p> <p><strong>The Procedure</strong></p> <p>The gist of the procedure is to take two matrices describing the sample susceptibility, combine them into a single matrix, diagonalize said matrix, normalize the left and right eigenvector matrices according to each other, apply an exponential function to the eigenvalue matrix, and finally compute the exiting spectrum given an input spectrum.</p> <p><strong>The Code</strong></p> <pre><code>import numpy as np import matplotlib.pyplot as plt import scipy.linalg as linalg def FiniteSampleTransmissionXUV(w, chi_0, chi_nd, E_in, a, N, tau): # Function takes as input: # &gt; w - A vector that describes the frequency spectrum range # &gt; X_0 - A vector that describes the susceptibility # without the IR pulse # &gt; X_nd - A matrix that describes the susceptibility with the # IR pulse # &gt; E_in - A vector that describes the frequency spectrum of the # incoming XUV pulse electric field # &gt; a - A constant that describes the intensity of the IR pulse # &gt; N - A constant that describes the optical depth of the # sample # &gt; tau - A constant that describes the time delay between the # IR pulse and the XUV pulse # Function provides output: # &gt; A vector that describes the frequency spectrum of the # XUV pulse electric field at the end of the sample #determines number of frequency steps from input frequency range n = len(w) # constant # determines frequency step size delta_w = 1 / (n - 1) # constant # create matrix sqrt(w_i*w_j) sqrt_w = np.outer( np.sqrt(w) , np.sqrt(w).T ) # nxn matrix # combine X_0 and X_nd into total suscptibility matrix chi_ij = (a * delta_w * sqrt_w * chi_nd) + \ np.diag( np.diag(sqrt_w) * (chi_0) ) # nxn matrix # diagonalize X_ij where sum(U_R_i^2) = 1 (Lambda, u_l, u_r) = linalg.eig(chi_ij, left = True, right = True) # vector and nxn matrices # attain the function that scales U_L'*U_R sqrt_F = np.sqrt( np.sum( u_l.T @ u_r , axis = 0 ) ) # row vector # scale U_R and U_L so that U_L'*U_R = 1 u_r_bar = u_r / sqrt_F # nxn matrix u_l_bar = u_l / sqrt_F # nxn matrix # apply exponential transform to eigenvalues # diagonal nxn matrix exp_lambda = np.diag( np.exp(1j * (2*np.pi*N / (3e8)) * Lambda) ) # create phase shift due to the time delay tau_phase = np.exp(1j * w * tau) # vector # recombine transformed susceptibility matrix ulambdau = u_r_bar @ exp_lambda @ u_l_bar.T # nxn matrix # apply effects of finite propagation and pulse # time delay to input electric field spectrum E_out = ulambdau @ (tau_phase * E_in).T # vector return E_out def GaussianSpectrum(w, E0, w_0, sigma): # creates a quasi-gaussian spectrum defined by the input # frequency range w, amplitude E_0, center frequency w_0, # and spectral width sigma E_in = E0 * np.sin(np.pi*w) * \ (np.exp( - ((w - w_0) / (np.sqrt(2) * sigma))**2)) return E_in # Testing the FiniteSampleTransmissionXUV function n = 100 w = np.linspace(0, 1, n) chi_0 = (1 + 1j) * ( np.sin(5*np.pi*w) )**2 chi_sin = np.sin(1*np.pi*w) chi_nd = (1 + 1j) * np.outer( (chi_sin**2), (chi_sin**2).T ) E_in = GaussianSpectrum(w, 1, 0.5, 0.1) a = 1 N = 1e8 tau = 0 E_out = FiniteSampleTransmissionXUV(w, chi_0, chi_nd, E_in, a, N, tau) plt.plot(w, E_in, w, abs(E_out)) plt.show() </code></pre> <p>In plotting the output electric field spectrum, we see the frequency spectrum of the XUV pulse before entering the sample in blue with the exiting spectrum in orange. One sees that frequencies of the XUV pulse have been absorbed, while new frequencies have been generated.</p> <p><a href="https://i.stack.imgur.com/1ez6E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1ez6E.png" alt="enter image description here" /></a></p> <p>As I imagine this is a very MATLAB looking python program, please let me know how to make it more python-ey. Any comments on violations of best practices and ways to refactor for improved functionality and cleanliness would be greatly appreciated. Thank you!</p>
[]
[ { "body": "<p>Overall it's not bad.</p>\n<ul>\n<li>Where possible, move code into functions, among other reasons to increase testability and maintainability and keep the global namespace clean</li>\n<li>Prefer <code>from x import y</code> if you don't need to alias a submodule</li>\n<li>Prefer <code>lower_snake_case</code> for method and variable names. Exceptions apply, particularly here where <code>E_x</code> has scientific meaning.</li>\n<li>Avoid line continuation <code>\\</code>; favour parentheses for multi-line expressions</li>\n<li>Can drop some redundant parens due to order of operations</li>\n<li>Consider adding a parametric transfer loop plot, since you have an input and an output. This is a Lissajous-like figure that depicts a different way of interpreting the relationship of your input and output spectra</li>\n<li>Consider plotting your introduced phase shift</li>\n<li>Add axis and figure titles</li>\n<li>Example code for Seaborn and Pandas added for the first subplot</li>\n<li>Particularly for function scalar value parameters, prefer named argument notation</li>\n<li>Add some PEP484 type hinting</li>\n<li>For <code>u_r</code> and <code>u_l</code>, in-place division is simpler and the <code>bar</code> variables are not needed</li>\n<li>Use standard triple-quoted docstring syntax</li>\n<li>Rather than <code>3e8</code> use the scipy-provided <code>c</code></li>\n</ul>\n<h2>Example code</h2>\n<p>I'm pretty sure (?) that this is numerically equivalent, and looks identical to your results.</p>\n<pre><code>from typing import Tuple\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib.collections import LineCollection\nfrom scipy import constants, linalg\n\n\ndef finite_sample_transmission_xuv(\n w: np.ndarray,\n chi_0: np.ndarray,\n chi_nd: np.ndarray,\n E_in: np.ndarray,\n a: float,\n N: float,\n tau: float,\n) -&gt; np.ndarray:\n &quot;&quot;&quot;\n Function takes as input:\n &gt; w - A vector that describes the frequency spectrum range\n &gt; X_0 - A vector that describes the susceptibility\n without the IR pulse\n &gt; X_nd - A matrix that describes the susceptibility with the\n IR pulse\n &gt; E_in - A vector that describes the frequency spectrum of the\n incoming XUV pulse electric field\n &gt; a - A constant that describes the intensity of the IR pulse\n &gt; N - A constant that describes the optical depth of the\n sample\n &gt; tau - A constant that describes the time delay between the\n IR pulse and the XUV pulse\n Function provides output:\n &gt; A vector that describes the frequency spectrum of the\n XUV pulse electric field at the end of the sample\n &quot;&quot;&quot;\n\n # determines number of frequency steps from input frequency range\n n = len(w) # constant\n\n # determines frequency step size\n delta_w = 1 / (n - 1) # constant\n\n # create matrix sqrt(w_i*w_j)\n sqrt_w = np.outer(np.sqrt(w), np.sqrt(w).T) # nxn matrix\n\n # combine X_0 and X_nd into total susceptibility matrix\n chi_ij = ( # nxn matrix\n a * delta_w * sqrt_w * chi_nd\n + np.diag(np.diag(sqrt_w) * chi_0)\n )\n\n # diagonalize X_ij where sum(U_R_i^2) = 1\n Lambda, u_l, u_r = linalg.eig(chi_ij, left=True, right=True) # vector and nxn matrices\n\n # attain the function that scales U_L'*U_R\n sqrt_F = np.sqrt(np.sum(u_l.T @ u_r, axis=0)) # row vector\n\n # scale U_R and U_L so that U_L'*U_R = 1\n u_r /= sqrt_F # nxn matrix\n u_l /= sqrt_F # nxn matrix\n\n # apply exponential transform to eigenvalues\n exp_lambda = np.diag( # diagonal nxn matrix\n np.exp(2j * np.pi * N / constants.c * Lambda)\n )\n\n # create phase shift due to the time delay\n tau_phase = np.exp(1j * w * tau) # vector\n\n # recombine transformed susceptibility matrix\n u_lambda_u = u_r @ exp_lambda @ u_l.T # nxn matrix\n\n # apply effects of finite propagation and pulse\n # time delay to input electric field spectrum\n E_out = u_lambda_u @ (tau_phase * E_in).T # vector\n\n return E_out\n\n\ndef gaussian_spectrum(\n w: np.ndarray,\n E0: float,\n w_0: float,\n sigma: float,\n) -&gt; np.ndarray:\n &quot;&quot;&quot;\n creates a quasi-gaussian spectrum defined by the input\n frequency range w, amplitude E_0, center frequency w_0,\n and spectral width sigma\n &quot;&quot;&quot;\n return (\n E0\n * np.sin(np.pi * w)\n * np.exp(\n -(\n (w - w_0) / np.sqrt(2) / sigma\n )**2\n )\n )\n\n\ndef generate_test_spectrum() -&gt; Tuple[\n np.ndarray, # w\n np.ndarray, # E_in\n np.ndarray, # E_out\n]:\n &quot;&quot;&quot;\n Testing the finite_sample_transmission_xuv function\n &quot;&quot;&quot;\n\n w = np.linspace(start=0, stop=1, num=300)\n\n chi_0 = (1 + 1j) * np.sin(5 * np.pi * w)**2\n chi_sin = np.sin(1 * np.pi * w)\n chi_sin2 = chi_sin**2\n chi_nd = (1 + 1j) * np.outer(chi_sin2, chi_sin2.T)\n\n E_in = gaussian_spectrum(w=w, E0=1, w_0=0.5, sigma=0.1)\n E_out = finite_sample_transmission_xuv(\n w=w, chi_0=chi_0, chi_nd=chi_nd, E_in=E_in,\n a=1, N=1e8, tau=0,\n )\n return w, E_in, E_out\n\n\ndef test_plot() -&gt; None:\n w, E_in, E_out = generate_test_spectrum()\n\n fig = plt.figure()\n fig.suptitle('Finite Sample Transmission XUV (Gaussian test)')\n grid = fig.add_gridspec(nrows=2, ncols=2)\n\n top = fig.add_subplot(grid[0, :])\n top.set_title('Input and output spectra')\n top.set_xlabel('ω normalized')\n top.set_ylabel('|E| normalized')\n top.grid()\n E_df = pd.DataFrame(index=w, data={'Entering': E_in, 'Exiting': np.abs(E_out)})\n sns.lineplot(ax=top, data=E_df, dashes=False)\n\n phi = np.fmod(np.angle(E_out) + 2*np.pi, 2*np.pi)\n left = fig.add_subplot(grid[1, 0])\n left.set_title('Output phase for real input')\n left.set_xlabel('ω normalized')\n left.set_ylabel('φ rad')\n left.set_yticks(np.linspace(0, 2*np.pi, 9))\n left.grid()\n left.plot(w, phi)\n\n # Adapted from https://stackoverflow.com/a/17241345/313768\n xy = E_df.to_numpy().reshape(-1, 1, 2)\n segments = np.hstack([xy[:-1], xy[1:]])\n # There's an argument to be made that a cyclic cmap like 'hsv' from\n # https://matplotlib.org/stable/tutorials/colors/colormaps.html#cyclic\n # should be used since this is a loop, but that's up to you\n lines = LineCollection(segments, cmap='viridis')\n lines.set_array(w)\n\n right = fig.add_subplot(grid[1, 1])\n right.set_title('Parametric transfer loop')\n right.set_xlabel('|E| in')\n right.set_ylabel('|E| out')\n right.add_collection(lines)\n right.grid()\n right.autoscale_view()\n plt.colorbar(lines, ax=right, label='ω normalized')\n\n plt.show()\n\n\nif __name__ == '__main__':\n test_plot()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/cdLLx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cdLLx.png\" alt=\"spectra, phase shift, and transfer\" /></a></p>\n<p>Yet another way of visualising your output spectrum is on the polar-complex plane:</p>\n<pre><code> xy = np.vstack((np.angle(E_out), np.abs(E_out))).T.reshape(-1, 1, 2)\n segments = np.hstack([xy[:-1], xy[1:]])\n lines = LineCollection(segments, cmap='viridis')\n lines.set_array(w)\n\n fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})\n ax.set_title('Polar output spectrum')\n ax.add_collection(lines)\n ax.set_rmax(0.6)\n ax.set_rticks(np.linspace(0.1, 0.6, 6))\n ax.set_rlabel_position(-90)\n ax.grid(True)\n plt.colorbar(lines, ax=ax, label='ω normalized')\n plt.show()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/E19aa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/E19aa.png\" alt=\"polar\" /></a></p>\n<h2>Jupyter</h2>\n<p>This category of script is the ideal use-case for a Jupyter notebook. Think of it as a hybrid of a Mathematica-like interpreter and a paper-writing environment. You'll want either <code>jupyterlab</code> or <code>notebook</code>, and <code>ipympl</code>, all from <code>pip</code>. This will allow for a mix of &quot;cells&quot; (basically paragraphs), either</p>\n<ul>\n<li>Markdown, supporting <code>$$ $$</code> formula notation, or</li>\n<li>Python, supporting <code>matplotlib</code> figures even with interactive cursor pan-and-zoom</li>\n</ul>\n<p>I have not written a full notebook for you, but have covered examples of all of the above. If you import this JSON into <code>xuv.ipynb</code>:</p>\n<pre class=\"lang-json prettyprint-override\"><code>{\n &quot;cells&quot;: [\n {\n &quot;cell_type&quot;: &quot;markdown&quot;,\n &quot;id&quot;: &quot;bef2a1f5&quot;,\n &quot;metadata&quot;: {},\n &quot;source&quot;: [\n &quot;Simulate transmission spectrum of extreme ultraviolet laser pulse through laser-dressed finite sample\\n&quot;,\n &quot;===&quot;\n ]\n },\n {\n &quot;cell_type&quot;: &quot;code&quot;,\n &quot;execution_count&quot;: 1,\n &quot;id&quot;: &quot;0d3cd8f0&quot;,\n &quot;metadata&quot;: {},\n &quot;outputs&quot;: [],\n &quot;source&quot;: [\n &quot;# %matplotlib widget for interactive mode, or\\n&quot;,\n &quot;# %matplotlib inline for print mode\\n&quot;,\n &quot;%matplotlib widget\\n&quot;,\n &quot;\\n&quot;,\n &quot;import numpy as np\\n&quot;,\n &quot;import matplotlib\\n&quot;,\n &quot;import matplotlib.pyplot as plt\\n&quot;,\n &quot;import pandas as pd\\n&quot;,\n &quot;import seaborn as sns\\n&quot;,\n &quot;from matplotlib.collections import LineCollection\\n&quot;,\n &quot;from scipy import constants, linalg\\n&quot;,\n &quot;from typing import Tuple\\n&quot;,\n &quot;\\n&quot;,\n &quot;ASPECT = 1.4\\n&quot;,\n &quot;figsize_inches = (8, 8/ASPECT)\\n&quot;,\n &quot;matplotlib.rc('figure', figsize=figsize_inches, dpi=100)&quot;\n ]\n },\n {\n &quot;cell_type&quot;: &quot;markdown&quot;,\n &quot;id&quot;: &quot;5d9262f3&quot;,\n &quot;metadata&quot;: {},\n &quot;source&quot;: [\n &quot;Introduction\\n&quot;,\n &quot;---------\\n&quot;,\n &quot;\\n&quot;,\n &quot;Based on [this CodeReview question](https://codereview.stackexchange.com/questions/261494/simulate-transmission-spectrum-of-extreme-ultraviolet-laser-pulse-through-laser/261517).\\n&quot;,\n &quot;\\n&quot;,\n &quot;I am currently participating in research on transient absorption spectroscopy and four wave mixing. In the experimental design, an extreme ultraviolet (XUV) laser pulse and infrared (IR) laser pulse are sent through a finite gas sample with a certain time delay between them. My current task was to develop a function that, given data on the system and input pulses, provides the transmission spectrum of the XUV pulse electric field after exiting the sample.\\n&quot;,\n &quot;\\n&quot;,\n &quot;The gist of the procedure is to take two matrices describing the sample susceptibility, combine them into a single matrix, diagonalize said matrix, normalize the left and right eigenvector matrices according to each other, apply an exponential function to the eigenvalue matrix, and finally compute the exiting spectrum given an input spectrum.&quot;\n ]\n },\n {\n &quot;cell_type&quot;: &quot;markdown&quot;,\n &quot;id&quot;: &quot;89c73f62&quot;,\n &quot;metadata&quot;: {},\n &quot;source&quot;: [\n &quot;Given an input frequency range\\n&quot;,\n &quot;\\n&quot;,\n &quot;$$\\n&quot;,\n &quot;0 \\\\le \\\\omega_i \\\\le 1, 0 \\\\le i \\\\lt n\\n&quot;,\n &quot;$$\\n&quot;,\n &quot;\\n&quot;,\n &quot;blah blah... prepared by&quot;\n ]\n },\n {\n &quot;cell_type&quot;: &quot;code&quot;,\n &quot;execution_count&quot;: 2,\n &quot;id&quot;: &quot;3e887232&quot;,\n &quot;metadata&quot;: {},\n &quot;outputs&quot;: [],\n &quot;source&quot;: [\n &quot;def gaussian_spectrum(\\n&quot;,\n &quot; w: np.ndarray,\\n&quot;,\n &quot; E0: float,\\n&quot;,\n &quot; w_0: float,\\n&quot;,\n &quot; sigma: float,\\n&quot;,\n &quot;) -&gt; np.ndarray:\\n&quot;,\n &quot; \\&quot;\\&quot;\\&quot;\\n&quot;,\n &quot; creates a quasi-gaussian spectrum defined by the input\\n&quot;,\n &quot; frequency range w, amplitude E_0, center frequency w_0,\\n&quot;,\n &quot; and spectral width sigma\\n&quot;,\n &quot; \\&quot;\\&quot;\\&quot;\\n&quot;,\n &quot; return (\\n&quot;,\n &quot; E0\\n&quot;,\n &quot; * np.sin(np.pi * w)\\n&quot;,\n &quot; * np.exp(\\n&quot;,\n &quot; -(\\n&quot;,\n &quot; (w - w_0) / np.sqrt(2) / sigma\\n&quot;,\n &quot; )**2\\n&quot;,\n &quot; )\\n&quot;,\n &quot; )&quot;\n ]\n },\n {\n &quot;cell_type&quot;: &quot;markdown&quot;,\n &quot;id&quot;: &quot;e96b5104&quot;,\n &quot;metadata&quot;: {},\n &quot;source&quot;: [\n &quot;The transmission transform is defined by\\n&quot;,\n &quot;\\n&quot;,\n &quot;... lots of formulas ...\\n&quot;,\n &quot;\\n&quot;,\n &quot;In Python:&quot;\n ]\n },\n {\n &quot;cell_type&quot;: &quot;code&quot;,\n &quot;execution_count&quot;: 3,\n &quot;id&quot;: &quot;9caf8046&quot;,\n &quot;metadata&quot;: {},\n &quot;outputs&quot;: [],\n &quot;source&quot;: [\n &quot;def finite_sample_transmission_xuv(\\n&quot;,\n &quot; w: np.ndarray,\\n&quot;,\n &quot; chi_0: np.ndarray,\\n&quot;,\n &quot; chi_nd: np.ndarray,\\n&quot;,\n &quot; E_in: np.ndarray,\\n&quot;,\n &quot; a: float,\\n&quot;,\n &quot; N: float,\\n&quot;,\n &quot; tau: float,\\n&quot;,\n &quot;) -&gt; np.ndarray:\\n&quot;,\n &quot; \\&quot;\\&quot;\\&quot;\\n&quot;,\n &quot; Function takes as input:\\n&quot;,\n &quot; &gt; w - A vector that describes the frequency spectrum range\\n&quot;,\n &quot; &gt; X_0 - A vector that describes the susceptibility\\n&quot;,\n &quot; without the IR pulse\\n&quot;,\n &quot; &gt; X_nd - A matrix that describes the susceptibility with the\\n&quot;,\n &quot; IR pulse\\n&quot;,\n &quot; &gt; E_in - A vector that describes the frequency spectrum of the\\n&quot;,\n &quot; incoming XUV pulse electric field\\n&quot;,\n &quot; &gt; a - A constant that describes the intensity of the IR pulse\\n&quot;,\n &quot; &gt; N - A constant that describes the optical depth of the\\n&quot;,\n &quot; sample\\n&quot;,\n &quot; &gt; tau - A constant that describes the time delay between the\\n&quot;,\n &quot; IR pulse and the XUV pulse\\n&quot;,\n &quot; Function provides output:\\n&quot;,\n &quot; &gt; A vector that describes the frequency spectrum of the\\n&quot;,\n &quot; XUV pulse electric field at the end of the sample\\n&quot;,\n &quot; \\&quot;\\&quot;\\&quot;\\n&quot;,\n &quot;\\n&quot;,\n &quot; # determines number of frequency steps from input frequency range\\n&quot;,\n &quot; n = len(w) # constant\\n&quot;,\n &quot;\\n&quot;,\n &quot; # determines frequency step size\\n&quot;,\n &quot; delta_w = 1 / (n - 1) # constant\\n&quot;,\n &quot;\\n&quot;,\n &quot; # create matrix sqrt(w_i*w_j)\\n&quot;,\n &quot; sqrt_w = np.outer(np.sqrt(w), np.sqrt(w).T) # nxn matrix\\n&quot;,\n &quot;\\n&quot;,\n &quot; # combine X_0 and X_nd into total susceptibility matrix\\n&quot;,\n &quot; chi_ij = ( # nxn matrix\\n&quot;,\n &quot; a * delta_w * sqrt_w * chi_nd\\n&quot;,\n &quot; + np.diag(np.diag(sqrt_w) * chi_0)\\n&quot;,\n &quot; )\\n&quot;,\n &quot;\\n&quot;,\n &quot; # diagonalize X_ij where sum(U_R_i^2) = 1\\n&quot;,\n &quot; Lambda, u_l, u_r = linalg.eig(chi_ij, left=True, right=True) # vector and nxn matrices\\n&quot;,\n &quot;\\n&quot;,\n &quot; # attain the function that scales U_L'*U_R\\n&quot;,\n &quot; sqrt_F = np.sqrt(np.sum(u_l.T @ u_r, axis=0)) # row vector\\n&quot;,\n &quot;\\n&quot;,\n &quot; # scale U_R and U_L so that U_L'*U_R = 1\\n&quot;,\n &quot; u_r /= sqrt_F # nxn matrix\\n&quot;,\n &quot; u_l /= sqrt_F # nxn matrix\\n&quot;,\n &quot;\\n&quot;,\n &quot; # apply exponential transform to eigenvalues\\n&quot;,\n &quot; exp_lambda = np.diag( # diagonal nxn matrix\\n&quot;,\n &quot; np.exp(2j * np.pi * N / constants.c * Lambda)\\n&quot;,\n &quot; )\\n&quot;,\n &quot;\\n&quot;,\n &quot; # create phase shift due to the time delay\\n&quot;,\n &quot; tau_phase = np.exp(1j * w * tau) # vector\\n&quot;,\n &quot;\\n&quot;,\n &quot; # recombine transformed susceptibility matrix\\n&quot;,\n &quot; u_lambda_u = u_r @ exp_lambda @ u_l.T # nxn matrix\\n&quot;,\n &quot;\\n&quot;,\n &quot; # apply effects of finite propagation and pulse\\n&quot;,\n &quot; # time delay to input electric field spectrum\\n&quot;,\n &quot; E_out = u_lambda_u @ (tau_phase * E_in).T # vector\\n&quot;,\n &quot;\\n&quot;,\n &quot; return E_out&quot;\n ]\n },\n {\n &quot;cell_type&quot;: &quot;markdown&quot;,\n &quot;id&quot;: &quot;8250f881&quot;,\n &quot;metadata&quot;: {},\n &quot;source&quot;: [\n &quot;To test this, run the simulation with\\n&quot;,\n &quot;\\n&quot;,\n &quot;$$ n = 500 $$\\n&quot;,\n &quot;$$ E_0 = 1 $$\\n&quot;,\n &quot;$$ \\\\omega_0 = 0.5 $$\\n&quot;,\n &quot;$$ \\\\sigma = 0.1 $$\\n&quot;,\n &quot;$$ \\\\tau = 0 $$\\n&quot;,\n &quot;$$ N = 1 \\\\times 10^8 $$\\n&quot;,\n &quot;$$ a = 1 $$\\n&quot;,\n &quot;\\n&quot;,\n &quot;via&quot;\n ]\n },\n {\n &quot;cell_type&quot;: &quot;code&quot;,\n &quot;execution_count&quot;: 4,\n &quot;id&quot;: &quot;a9802320&quot;,\n &quot;metadata&quot;: {},\n &quot;outputs&quot;: [],\n &quot;source&quot;: [\n &quot;def generate_test_spectrum() -&gt; Tuple[\\n&quot;,\n &quot; np.ndarray, # w\\n&quot;,\n &quot; np.ndarray, # E_in\\n&quot;,\n &quot; np.ndarray, # E_out\\n&quot;,\n &quot;]:\\n&quot;,\n &quot; \\&quot;\\&quot;\\&quot;\\n&quot;,\n &quot; Testing the finite_sample_transmission_xuv function\\n&quot;,\n &quot; \\&quot;\\&quot;\\&quot;\\n&quot;,\n &quot;\\n&quot;,\n &quot; w = np.linspace(start=0, stop=1, num=500)\\n&quot;,\n &quot;\\n&quot;,\n &quot; chi_0 = (1 + 1j) * np.sin(5 * np.pi * w)**2\\n&quot;,\n &quot; chi_sin = np.sin(1 * np.pi * w)\\n&quot;,\n &quot; chi_sin2 = chi_sin**2\\n&quot;,\n &quot; chi_nd = (1 + 1j) * np.outer(chi_sin2, chi_sin2.T)\\n&quot;,\n &quot;\\n&quot;,\n &quot; E_in = gaussian_spectrum(w=w, E0=1, w_0=0.5, sigma=0.1)\\n&quot;,\n &quot; E_out = finite_sample_transmission_xuv(\\n&quot;,\n &quot; w=w, chi_0=chi_0, chi_nd=chi_nd, E_in=E_in,\\n&quot;,\n &quot; a=1, N=1e8, tau=0,\\n&quot;,\n &quot; )\\n&quot;,\n &quot; return w, E_in, E_out\\n&quot;,\n &quot;\\n&quot;,\n &quot;\\n&quot;,\n &quot;w, E_in, E_out = generate_test_spectrum()&quot;\n ]\n },\n {\n &quot;cell_type&quot;: &quot;markdown&quot;,\n &quot;id&quot;: &quot;3a9d2291&quot;,\n &quot;metadata&quot;: {},\n &quot;source&quot;: [\n &quot;Plots\\n&quot;,\n &quot;------\\n&quot;,\n &quot;\\n&quot;,\n &quot;First we look at the input and output spectral magnitudes:&quot;\n ]\n },\n {\n &quot;cell_type&quot;: &quot;code&quot;,\n &quot;execution_count&quot;: 5,\n &quot;id&quot;: &quot;8b18f532&quot;,\n &quot;metadata&quot;: {},\n &quot;outputs&quot;: [\n {\n &quot;data&quot;: {\n &quot;application/vnd.jupyter.widget-view+json&quot;: {\n &quot;model_id&quot;: &quot;53acc1e145394bc4b0650a1492851d22&quot;,\n &quot;version_major&quot;: 2,\n &quot;version_minor&quot;: 0\n },\n &quot;text/plain&quot;: [\n &quot;Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …&quot;\n ]\n },\n &quot;metadata&quot;: {},\n &quot;output_type&quot;: &quot;display_data&quot;\n }\n ],\n &quot;source&quot;: [\n &quot;def plot_spectra(w: np.ndarray, E_in: np.ndarray, E_out: np.ndarray) -&gt; None:\\n&quot;,\n &quot; fig, ax = plt.subplots(num=1)\\n&quot;,\n &quot; ax.set_title('Input and output spectra')\\n&quot;,\n &quot; ax.set_xlabel('ω normalized')\\n&quot;,\n &quot; ax.set_ylabel('|E| normalized')\\n&quot;,\n &quot; ax.grid()\\n&quot;,\n &quot; E_df = pd.DataFrame(index=w, data={'Entering': E_in, 'Exiting': np.abs(E_out)})\\n&quot;,\n &quot; sns.lineplot(ax=ax, data=E_df, dashes=False)\\n&quot;,\n &quot;\\n&quot;,\n &quot; \\n&quot;,\n &quot;plot_spectra(w, E_in, E_out)&quot;\n ]\n },\n {\n &quot;cell_type&quot;: &quot;markdown&quot;,\n &quot;id&quot;: &quot;5f6eb7f1&quot;,\n &quot;metadata&quot;: {},\n &quot;source&quot;: [\n &quot;The input electric field spectrum is real. The output spectrum has an introduced phase shift:&quot;\n ]\n },\n {\n &quot;cell_type&quot;: &quot;code&quot;,\n &quot;execution_count&quot;: 6,\n &quot;id&quot;: &quot;264e5b17&quot;,\n &quot;metadata&quot;: {},\n &quot;outputs&quot;: [\n {\n &quot;data&quot;: {\n &quot;application/vnd.jupyter.widget-view+json&quot;: {\n &quot;model_id&quot;: &quot;e96a25d0be4b44d1ad6d287bb89334b2&quot;,\n &quot;version_major&quot;: 2,\n &quot;version_minor&quot;: 0\n },\n &quot;text/plain&quot;: [\n &quot;Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …&quot;\n ]\n },\n &quot;metadata&quot;: {},\n &quot;output_type&quot;: &quot;display_data&quot;\n }\n ],\n &quot;source&quot;: [\n &quot;def plot_phase(w: np.ndarray, E_in: np.ndarray, E_out: np.ndarray) -&gt; None:\\n&quot;,\n &quot; fig, ax = plt.subplots(num=2)\\n&quot;,\n &quot; phi = np.fmod(np.angle(E_out) + 2*np.pi, 2*np.pi)\\n&quot;,\n &quot; ax.set_title('Output phase for real input')\\n&quot;,\n &quot; ax.set_xlabel('ω normalized')\\n&quot;,\n &quot; ax.set_ylabel('φ rad')\\n&quot;,\n &quot; ax.set_yticks(np.linspace(0, 2*np.pi, 9))\\n&quot;,\n &quot; ax.grid()\\n&quot;,\n &quot; ax.plot(w, phi)\\n&quot;,\n &quot;\\n&quot;,\n &quot; \\n&quot;,\n &quot;plot_phase(w, E_in, E_out)&quot;\n ]\n },\n {\n &quot;cell_type&quot;: &quot;code&quot;,\n &quot;execution_count&quot;: null,\n &quot;id&quot;: &quot;245ca66b&quot;,\n &quot;metadata&quot;: {},\n &quot;outputs&quot;: [],\n &quot;source&quot;: []\n }\n ],\n &quot;metadata&quot;: {\n &quot;kernelspec&quot;: {\n &quot;display_name&quot;: &quot;Python 3&quot;,\n &quot;language&quot;: &quot;python&quot;,\n &quot;name&quot;: &quot;python3&quot;\n },\n &quot;language_info&quot;: {\n &quot;codemirror_mode&quot;: {\n &quot;name&quot;: &quot;ipython&quot;,\n &quot;version&quot;: 3\n },\n &quot;file_extension&quot;: &quot;.py&quot;,\n &quot;mimetype&quot;: &quot;text/x-python&quot;,\n &quot;name&quot;: &quot;python&quot;,\n &quot;nbconvert_exporter&quot;: &quot;python&quot;,\n &quot;pygments_lexer&quot;: &quot;ipython3&quot;,\n &quot;version&quot;: &quot;3.9.0&quot;\n }\n },\n &quot;nbformat&quot;: 4,\n &quot;nbformat_minor&quot;: 5\n}\n</code></pre>\n<p>and then open it in Jupyter, you'll see the results; some screenshots:</p>\n<p><a href=\"https://i.stack.imgur.com/pGqC3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pGqC3.png\" alt=\"jupyter intro\" /></a></p>\n<p>[...]</p>\n<p><a href=\"https://i.stack.imgur.com/4u2DI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4u2DI.png\" alt=\"ipympl plot\" /></a></p>\n<p>This supports a paper-like narrative with interactive figures, pretty formulae, and full source interspersal.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T16:08:57.573", "Id": "261517", "ParentId": "261494", "Score": "6" } }, { "body": "<p>PEP-8 recommends using spaces around binary operators, such as <code>*</code> and <code>**</code>, and no spaces after a <code>(</code> or before a <code>)</code>. This makes statements like:</p>\n<pre><code>chi_0 = (1 + 1j) * ( np.sin(5*np.pi*w) )**2\n</code></pre>\n<p>into something a little more readable:</p>\n<pre><code>chi_0 = (1 + 1j) * np.sin(5 * np.pi * w) ** 2\n</code></pre>\n<hr />\n<p>You ran into Python's keyword <code>lambda</code>, and had to revert to using <code>Lambda</code> as the variable name, to keep the variable name &quot;clean&quot;, but end up deviating from PEP-8's preference of using <code>snake_case</code> for variable names.</p>\n<p>Here is a controversial solution. Just go ahead and use lambda. It is a greek letter ... which is a Unicode &quot;letter&quot; ... which means it is valid as a Python identifier.</p>\n<pre class=\"lang-py prettyprint-override\"><code>(λ, u_l, u_r) = ...\n</code></pre>\n<p>This can continue to many of your other Python identifiers, like <code>Δω</code>, <code>τ</code>, <code>ϕ</code>, <code>χ</code>. Certain subscripts are even possible (<code>ₐₑₒₓₔₕₖₗₘₙₚₛₜ</code>), allowing you to use <code>τᵩ</code> instead of <code>tau_phase</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; τᵩ = 1\n&gt;&gt;&gt; f&quot;{τᵩ=}&quot;\n'τᵩ=1'\n&gt;&gt;&gt; \n</code></pre>\n<p>While it may make editing you program harder (having a collection of various unicode characters in a comment for easy copy/paste is helpful), using the proper mathematical symbols might actually make the program easier to understand.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from numpy import pi as π\nfrom numpy import sin\n\n...\n\n χ₀ = (1 + 1j) * sin(5 * π * ω) ** 2\n</code></pre>\n<p>Doesn't that look nice?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T13:23:16.293", "Id": "516130", "Score": "2", "body": "Particularly for a scientific script - not something that will be released for example to a production server or an open source package - this is a great idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T13:29:15.123", "Id": "516131", "Score": "1", "body": "As for the operator spacing, I'm a little selective. For long-form algebraic expressions I sometimes like the idea of adding spaces to emphasize order of operations, for example `a*b + c*d**2`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T05:27:18.010", "Id": "261535", "ParentId": "261494", "Score": "3" } } ]
{ "AcceptedAnswerId": "261517", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T03:06:41.420", "Id": "261494", "Score": "4", "Tags": [ "python", "beginner", "simulation", "physics" ], "Title": "Simulate transmission spectrum of extreme ultraviolet laser pulse through laser-dressed finite sample (Python Version)" }
261494
<p>I wrote a <a href="https://en.wikipedia.org/wiki/Pomodoro_Technique" rel="nofollow noreferrer">Pomodoro</a> timer daemon for BSD systems in C (may work on Linux with <code>-lbsd</code>).</p> <p>The server uses poll(2) and sockets to communicate with the client and to implement the timer.<br /> The client starts or stops the timer and gets information about it.</p> <p>For example, in a terminal run <code>$ pomod</code> (the server). In another, run <code>$ pomo start</code> (the client). The server will print <code>pomodoro</code> for a pomodoro has begun. After 25 minutes, the pomodoro will end and it will print <code>short break</code> to indicate that you have to take a short break. Running <code>$ pomo info</code> gets information about the timer (which cycle you're in and the current time).</p> <p>Compile pomod with <code>cc -o pomod pomod.c util.c</code>.<br /> Compile pomo with <code>cc -o pomo pomo.c util.c</code>.</p> <p>Here's <code>pomod.c</code>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;sys/socket.h&gt; #include &lt;sys/time.h&gt; #include &lt;sys/un.h&gt; #include &lt;err.h&gt; #include &lt;limits.h&gt; #include &lt;poll.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include &quot;util.h&quot; #define BACKLOG 5 #define SECONDS 60 /* seconds in a minute */ #define MINUTES 60 /* minutes in a hour */ #define MILISECONDS 1000 /* miliseconds in a second */ #define NANOPERMILI 1000000 #define MAXCLIENTS 10 enum Duration { POMODORO_SECS = SECONDS * 25, SHORTBREAK_SECS = SECONDS * 5, LONGBREAK_SECS = SECONDS * 30 }; enum Cycle { STOPPED, POMODORO, SHORTBREAK, LONGBREAK }; static char *sockpath; static struct timespec pomodoro = {.tv_sec = POMODORO_SECS}; static struct timespec shortbreak = {.tv_sec = SHORTBREAK_SECS}; static struct timespec longbreak = {.tv_sec = LONGBREAK_SECS}; static char *cyclenames[] = { [STOPPED] = &quot;stopped&quot;, [POMODORO] = &quot;pomodoro&quot;, [SHORTBREAK] = &quot;shortbreak&quot;, [LONGBREAK] = &quot;longbreak&quot; }; static void usage(void) { (void)fprintf(stderr, &quot;usage: %s [-S socket] [-l time] [-p time] [-s time]\n&quot;, getprogname()); exit(1); } static int gettime(char *s) { char *ep; long l; l = strtol(s, &amp;ep, 10); if (*s == '\0' || *ep != '\0' || l &lt;= 0 || l &gt;= INT_MAX / SECONDS) goto error; return SECONDS * (int)l; error: errx(1, &quot;%s: invalid time&quot;, s); } /* parse arguments and set global variables */ static void parseargs(int argc, char *argv[]) { int ch; while ((ch = getopt(argc, argv, &quot;l:p:S:s:&quot;)) != -1) { switch (ch) { case 'S': sockpath = optarg; break; case 'l': longbreak.tv_sec = gettime(optarg); break; case 'p': pomodoro.tv_sec = gettime(optarg); break; case 's': shortbreak.tv_sec = gettime(optarg); break; default: usage(); break; } } argc -= optind; argv += optind; if (argc &gt; 0) { usage(); } if (sockpath == NULL) { sockpath = getsockpath(); } } static int createsocket(const char *path, int backlog) { struct sockaddr_un saddr; int sd; memset(&amp;saddr, 0, sizeof saddr); saddr.sun_family = AF_UNIX; strncpy(saddr.sun_path, path, (sizeof saddr.sun_path) - 1); unlink(path); if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) goto error; if (bind(sd, (struct sockaddr *)&amp;saddr, sizeof saddr) == -1) goto error; if (listen(sd, backlog) == -1) goto error; return sd; error: err(1, &quot;%s&quot;, path); } /* return 1 if we handle client */ static int acceptclient(struct pollfd *pfds, size_t n) { struct sockaddr_un caddr; socklen_t len; size_t i; int cd; /* client file descriptor */ len = sizeof caddr; if ((cd = accept(pfds[0].fd, (struct sockaddr *)&amp;caddr, &amp;len)) == -1) err(1, &quot;accept&quot;); for (i = 1; i &lt;= n; i++) { if (pfds[i].fd &lt;= 0) { pfds[i].fd = cd; pfds[i].events = POLLIN; return 1; } } close(cd); /* ignore if we have MAXCLIENTS or more */ return 0; } /* return 1 if we do not handle client anymore */ static int handleclient(int fd) { char cmd; int n; if ((n = read(fd, &amp;cmd, 1)) != 1) return BYE; return cmd; } static void gettimespec(struct timespec *ts) { if (clock_gettime(CLOCK_REALTIME, ts) == -1) { err(1, &quot;time&quot;); } } static void notify(int cycle) { printf(&quot;%s\n&quot;, cyclenames[cycle]); fflush(stdout); } static void timesub(struct timespec *a, struct timespec *b, struct timespec *c) { timespecsub(a, b, c); if (c-&gt;tv_sec &lt; 0) { c-&gt;tv_sec = 0; } if (c-&gt;tv_nsec &lt; 0) { c-&gt;tv_nsec = 0; } } static void info(int fd, struct timespec *stoptime, int cycle) { struct timespec now, diff; time_t mins, secs; char buf[INFOSIZ]; gettimespec(&amp;now); timesub(stoptime, &amp;now, &amp;diff); switch (cycle) { case POMODORO: mins = (pomodoro.tv_sec - diff.tv_sec) / SECONDS; secs = (pomodoro.tv_sec - diff.tv_sec) - mins; break; case SHORTBREAK: mins = (shortbreak.tv_sec - diff.tv_sec) / SECONDS; secs = (shortbreak.tv_sec - diff.tv_sec) - mins; break; case LONGBREAK: mins = (longbreak.tv_sec - diff.tv_sec) / SECONDS; secs = (longbreak.tv_sec - diff.tv_sec) - mins; break; } if (cycle == STOPPED) snprintf(buf, INFOSIZ, &quot;%s&quot;, cyclenames[cycle]); else snprintf(buf, INFOSIZ, &quot;%s: %02lld:%02lld&quot;, cyclenames[cycle], (long long int)mins, (long long int)secs); write(fd, buf, INFOSIZ); } static int gettimeout(struct timespec *stoptime) { struct timespec now, diff; gettimespec(&amp;now); timesub(stoptime, &amp;now, &amp;diff); return MILISECONDS * diff.tv_sec + diff.tv_nsec / NANOPERMILI; } static void run(int sd) { struct pollfd pfds[MAXCLIENTS + 1]; struct timespec now, stoptime; size_t i; int timeout; int nclients; int cycle; int pomocount; int n; nclients = 0; timeout = -1; pfds[0].fd = sd; pfds[0].events = POLLIN; for (i = 1; i &lt;= MAXCLIENTS; i++) pfds[i].fd = -1; cycle = STOPPED; pomocount = 0; for (;;) { if ((n = poll(pfds, nclients + 1, timeout)) == -1) err(1, &quot;poll&quot;); if (n &gt; 0) { if (pfds[0].revents &amp; POLLHUP) { /* socket has been disconnected */ return; } if (pfds[0].revents &amp; POLLIN) { /* handle new client */ if (acceptclient(pfds, MAXCLIENTS)) { nclients++; } } for (i = 1; i &lt;= MAXCLIENTS; i++) { /* handle existing client */ if (pfds[i].fd &lt;= 0 || !(pfds[i].events &amp; POLLIN)) continue; switch (handleclient(pfds[i].fd)) { case BYE: pfds[i].fd = -1; nclients--; break; case START: pomocount = 0; gettimespec(&amp;stoptime); stoptime.tv_sec += pomodoro.tv_sec; notify(cycle = POMODORO); break; case STOP: cycle = STOPPED; break; case INFO: info(pfds[i].fd, &amp;stoptime, cycle); break; } } } gettimespec(&amp;now); switch (cycle) { case STOPPED: timeout = -1; break; case POMODORO: if (timespeccmp(&amp;now, &amp;stoptime, &gt;=)) { pomocount++; if (pomocount &lt; 4) { notify(cycle = SHORTBREAK); stoptime.tv_sec += shortbreak.tv_sec; timeout = gettimeout(&amp;stoptime); } else { pomocount = 0; notify(cycle = LONGBREAK); stoptime.tv_sec += longbreak.tv_sec; timeout = gettimeout(&amp;stoptime); } } else { timeout = gettimeout(&amp;stoptime); } break; case SHORTBREAK: if (timespeccmp(&amp;now, &amp;stoptime, &gt;)) { notify(cycle = POMODORO); stoptime.tv_sec += pomodoro.tv_sec; timeout = gettimeout(&amp;stoptime); } else { timeout = gettimeout(&amp;stoptime); } break; case LONGBREAK: pomocount = 0; if (timespeccmp(&amp;now, &amp;stoptime, &gt;)) { notify(cycle = POMODORO); stoptime.tv_sec += pomodoro.tv_sec; timeout = gettimeout(&amp;stoptime); } else { timeout = gettimeout(&amp;stoptime); } break; } } } int main(int argc, char *argv[]) { int sd; /* socket file descriptor */ setprogname(argv[0]); parseargs(argc, argv); sd = createsocket(sockpath, BACKLOG); run(sd); close(sd); unlink(sockpath); return 0; } </code></pre> <p>Here's <code>pomo.c</code>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;sys/socket.h&gt; #include &lt;sys/un.h&gt; #include &lt;err.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include &quot;util.h&quot; static char *sockpath = NULL; static void usage(void) { (void)fprintf(stderr, &quot;usage: %s [-S socket] [start|stop|info]\n&quot;, getprogname()); exit(1); } static int parseargs(int argc, char *argv[]) { int ch; while ((ch = getopt(argc, argv, &quot;S:&quot;)) != -1) { switch (ch) { case 'S': sockpath = optarg; break; default: usage(); break; } } argc -= optind; argv += optind; if (argc != 1) usage(); if (sockpath == NULL) sockpath = getsockpath(); if (strcasecmp(*argv, &quot;stop&quot;) == 0) return STOP; else if (strcasecmp(*argv, &quot;start&quot;) == 0) return START; else if (strcasecmp(*argv, &quot;info&quot;) == 0) return INFO; usage(); return 0; /* NOTREACHED */ } static int connectsocket(const char *path) { struct sockaddr_un saddr; int fd; if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) err(1, &quot;socket&quot;); memset(&amp;saddr, 0, sizeof saddr); saddr.sun_family = AF_UNIX; strncpy(saddr.sun_path, path, (sizeof saddr.sun_path) - 1); if (connect(fd, (struct sockaddr *)&amp;saddr, sizeof saddr) == -1) err(1, &quot;connect&quot;); return fd; } static void sendcommand(char cmd, int fd) { if (write(fd, &amp;cmd, 1) == -1) { err(1, &quot;write&quot;); } } static void printinfo(int fd) { int n; char buf[INFOSIZ]; if ((n = read(fd, buf, INFOSIZ)) != INFOSIZ) errx(1, &quot;could not get info&quot;); buf[INFOSIZ - 1] = '\0'; printf(&quot;%s\n&quot;, buf); } int main(int argc, char *argv[]) { int fd; /* socket file descriptor */ char cmd; setprogname(argv[0]); cmd = parseargs(argc, argv); fd = connectsocket(sockpath); sendcommand(cmd, fd); if (cmd == INFO) printinfo(fd); close(fd); return 0; } </code></pre> <p>Here's <code>util.c</code> (code shared by both programs):</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #define PATHSIZ 104 #define PATHPREFIX &quot;/tmp/pomodoro.&quot; char * getsockpath(void) { static char buf[PATHSIZ]; snprintf(buf, PATHSIZ, PATHPREFIX &quot;%ld&quot;, (long)geteuid()); return buf; } </code></pre> <p>And here's <code>util.h</code> (the common header).</p> <pre class="lang-c prettyprint-override"><code>#define INFOSIZ 128 enum Command { BYE = 0, STOP = 'p', START = 's', INFO = 'i', }; char *getsockpath(void); </code></pre> <p>It's also <a href="https://github.com/phillbush/pomod" rel="nofollow noreferrer">on github</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T15:58:30.197", "Id": "516219", "Score": "0", "body": "I'm not sure I understand the motivation for using a client-server design for what could be a plain old single-process app. Am I missing something obvious?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-05T23:48:13.423", "Id": "518509", "Score": "0", "body": "@ggorlen I just want to play with sockets and write a simple daemon. But I agree, a client-server design is overwhelming for such small program." } ]
[ { "body": "<p><strong>Nicely written</strong></p>\n<p><strong>Alternative zeroing</strong></p>\n<pre><code>// struct sockaddr_un saddr;\n// memset(&amp;saddr, 0, sizeof saddr);\n\nstruct sockaddr_un saddr = {0};\n</code></pre>\n<p><strong>Off-by-1 limit?</strong></p>\n<p>Perhaps</p>\n<pre><code>// if (*s == '\\0' || *ep != '\\0' || l &lt;= 0 || l &gt;= INT_MAX / SECONDS)\n if (*s == '\\0' || *ep != '\\0' || l &lt;= 0 || l &gt; INT_MAX / SECONDS)\n</code></pre>\n<p><strong>Safer subtraction</strong></p>\n<p>After <code>timespecsub(a, b, c)</code> and when <code>c-&gt;tv_sec &lt; 0</code> is true, I am not certain <code>c-&gt;tv_nsec</code> will not be positive. Recommend when zeroing the <code>.tv_sec</code> member, also do so to the <code>.tv_nsec</code>.</p>\n<pre><code>if (c-&gt;tv_sec &lt; 0) {\n c-&gt;tv_sec = 0;\n c-&gt;tv_nsec = 0; // add\n}\nif (c-&gt;tv_nsec &lt; 0) {\n c-&gt;tv_nsec = 0;\n}\n</code></pre>\n<p><strong>Better names</strong></p>\n<p>Rather than <code>SECONDS</code> to represent &quot;seconds per minute&quot;, consider something like <code>SEC_PER_MIN</code>.</p>\n<p><strong>Unknown integer widths</strong></p>\n<p>Minor: When printing a system integer type (no matching print specifier), I tend to go for the widest specifier.</p>\n<pre><code>// snprintf(buf, PATHSIZ, PATHPREFIX &quot;%ld&quot;, (long)geteuid());\nsnprintf(buf, PATHSIZ, PATHPREFIX &quot;%jd&quot;, (intmax_t) geteuid());\n</code></pre>\n<p><strong>Missing code guard util.h</strong></p>\n<p><strong>Static buffer care</strong></p>\n<p>Consider <code>const</code> to protect caller messing with the buffer.</p>\n<pre><code>// char *getsockpath(void)\nconst char *getsockpath(void)\n</code></pre>\n<p><strong>Define &amp; Initialize</strong></p>\n<p>Consider initialization at definition.</p>\n<pre><code>// int timeout;\n// int nclients;\n// nclients = 0;\n// timeout = -1;\n\nint timeout = -1;\nint nclients = 0;\n</code></pre>\n<p>Other places in code too.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T17:18:00.770", "Id": "261552", "ParentId": "261495", "Score": "1" } } ]
{ "AcceptedAnswerId": "261552", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T03:42:09.687", "Id": "261495", "Score": "3", "Tags": [ "c", "socket", "posix" ], "Title": "Pomodoro timer daemon in C for BSD systems" }
261495
<p>The below code segments compose a simple console game where the user is prompted to enter a randomly generated letter displayed in the console. It also saves and loads user data through a .txt file.</p> <p>It's a good bit of code, so I'm looking for any sort of constructive criticism on the code. Feedback on how to achieve the utmost optimization and how to improve the design of the program overall would be greatly appreciated. Even a skim of the code with a brief analysis would be great. Feedback on any aspect of the code would be great.</p> <p>main.cpp:</p> <pre><code>#include &quot;PLAYER_DATABASE_H.h&quot; const std::string player_data_file = &quot;player_data.txt&quot;; const std::string quit_prompt_msg = &quot;DONE&quot;; enum menu_options { LOGIN=1, REGISTER=2, EXIT=3 }; std::string menu_options_to_string(menu_options option); menu_options main_menu(const Player_database &amp;database, std::ostream &amp;output, std::istream &amp;input); void prompt_username_and_password(std::string &amp;username, std::string &amp;password, std::ostream &amp;output, std::istream &amp;input); Player* prompt_login(Player_database &amp;database, std::ostream &amp;output, std::istream &amp;input, const std::string &amp;quit_msg); Player* prompt_register_account(Player_database &amp;database, std::ostream &amp;output, std::istream &amp;input, const std::string &amp;quit_msg); bool quit_prompt(std::istream &amp;input, std::ostream &amp;output, const std::string &amp;msg, const std::string &amp;quit_msg); int main() { std::cout &lt;&lt; std::numeric_limits&lt;points_t&gt;::max() &lt;&lt; &quot;\n\n&quot;; Player *player; Player_database database(player_data_file); menu_options choice = main_menu(database, std::cout, std::cin); switch (choice) { case LOGIN: { player = prompt_login(database, std::cout, std::cin, quit_prompt_msg); break; } case REGISTER: { player = prompt_register_account(database, std::cout, std::cin, quit_prompt_msg); break; } default: { player = nullptr; } } if (player != nullptr) { Game game(player); while (true) { game.play_round(std::cout, std::cin); if (game.point_limit_reached()) { std::cout &lt;&lt; &quot;\nYou've reached the maximum number of points! If you score another point, your points will be reset to 0.\n\n\n&quot;; } char answer; std::cout &lt;&lt; &quot;Play again? (y/n): &quot;; std::cin &gt;&gt; answer; std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); std::cout &lt;&lt; '\n'; if (answer == 'n' || answer == 'N') break; } } std::cout &lt;&lt; &quot;Exited.&quot;; } std::string menu_options_to_string(menu_options option) { switch (option) { case LOGIN: return &quot;LOGIN&quot;; case REGISTER: return &quot;REGISTER&quot;; default: return &quot;EXIT&quot;; } } menu_options main_menu(const Player_database &amp;database, std::ostream &amp;output, std::istream &amp;input) { unsigned short option = 0; output &lt;&lt; &quot;Type the corresponding number of the action to be executed\n&quot;; for (int elem = LOGIN; elem != EXIT; ++elem) { output &lt;&lt; elem &lt;&lt; &quot;. &quot; &lt;&lt; menu_options_to_string(static_cast&lt;menu_options&gt;(elem)) &lt;&lt; '\n'; } output &lt;&lt; &quot;\nChoice: &quot;; if (!(input &gt;&gt; option) || option &gt; REGISTER) return EXIT; input.ignore(1, '\n'); // get rid of newline character return static_cast&lt;menu_options&gt;(option); } void prompt_username_and_password(std::string &amp;username, std::string &amp;password, std::ostream &amp;output, std::istream &amp;input) { output &lt;&lt; &quot;Username: &quot;; std::getline(input, username); output &lt;&lt; &quot;Password: &quot;; std::getline(input, password); } Player* prompt_login(Player_database &amp;database, std::ostream &amp;output, std::istream &amp;input, const std::string &amp;quit_msg) { std::string username, password; bool valid_entry; do { prompt_username_and_password(username, password, output, input); valid_entry = database.does_account_exist(username, password); if (!valid_entry) { if (quit_prompt(input, output, &quot;Invalid attempt. Type &quot; + quit_msg + &quot; to exit prompt, anything else to continue&quot;, quit_msg)) return nullptr; } } while (!valid_entry); return database.login(username, password); } Player* prompt_register_account(Player_database &amp;database, std::ostream &amp;output, std::istream &amp;input, const std::string &amp;quit_msg) { std::string username, password; bool valid_entry; do { prompt_username_and_password(username, password, output, input); valid_entry = !database.does_username_exist(username); if (!valid_entry) { if (quit_prompt(input, output, &quot;An account with that username already exists. Type &quot; + quit_msg + &quot; to exit prompt, anything else to continue&quot;, quit_msg)) return nullptr; } } while(!valid_entry); return database.register_account(username, password); } bool quit_prompt(std::istream &amp;input, std::ostream &amp;output, const std::string &amp;msg, const std::string &amp;quit_msg) { std::string response; output &lt;&lt; '\n' &lt;&lt; msg &lt;&lt; &quot;: &quot;; std::getline(input, response); output &lt;&lt; '\n'; return (response == quit_msg); } </code></pre> <p>GAME_H:</p> <pre><code>#ifndef GAME_H #define GAME_H #include &lt;chrono&gt; #include &lt;limits&gt; #include &quot;PLAYER_H.h&quot; #include &lt;random&gt; class Game { public: explicit Game(Player *_player) : player(_player) {} void play_round(std::ostream &amp;output, std::istream &amp;input); bool point_limit_reached() const; private: Player *player; }; #endif </code></pre> <p>game.cpp:</p> <pre><code> std::random_device seed; std::uniform_int_distribution&lt;int&gt; uid(65, 90); // where 65 in ASCII = A and 90 = Z void Game::play_round(std::ostream &amp;output, std::istream &amp;input) { char correct_answer = uid(seed); char player_answer; output &lt;&lt; correct_answer &lt;&lt; '\n'; output &lt;&lt; &quot;Type the character above: &quot;; input &gt;&gt; player_answer; input.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); if (player_answer == correct_answer || player_answer == static_cast&lt;char&gt;(correct_answer+32)) { player-&gt;increment_points(); // 32 is lowercase correspondent of answer in ASCII output &lt;&lt; &quot;+1 point\n&quot;; } else { player-&gt;decrement_points(); output &lt;&lt; &quot;-1 point\n&quot;; } output &lt;&lt; &quot;Your points: &quot; &lt;&lt; player-&gt;get_points() &lt;&lt; &quot;\n\n&quot;; } bool Game::point_limit_reached() const { return (player-&gt;get_points() == std::numeric_limits&lt;points_t&gt;::max()); } </code></pre> <p>PLAYER_H:</p> <pre><code>#define PLAYER_H #include &lt;iostream&gt; #include &lt;string&gt; using points_t = unsigned long long; class Player { public: explicit Player(std::istream &amp;input); Player(std::string _username, std::string _password, points_t _points=0) : username(_username), password(_password), points(_points) {} void increment_points(); void decrement_points(); points_t get_points() const; bool is_my_password(const std::string &amp;_password) const; bool operator&lt;(const Player &amp;other_player) const; bool operator&gt;(const Player &amp;other_player) const; bool operator==(const Player &amp;other_player) const; friend std::ostream&amp; operator&lt;&lt;(std::ostream &amp;output, const Player &amp;player); private: std::string username, password; points_t points; }; std::ostream&amp; operator&lt;&lt;(std::ostream &amp;output, const Player &amp;player); #endif </code></pre> <p>player.cpp:</p> <pre><code> Player::Player(std::istream &amp;input) { input &gt;&gt; username &gt;&gt; password &gt;&gt; points; } void Player::increment_points() { ++points; } void Player::decrement_points() { if (!points--) points = 0; } points_t Player::get_points() const { return points; } bool Player::is_my_password(const std::string &amp;_password) const { return (password == _password); } bool Player::operator&lt;(const Player &amp;other_player) const { return (username &lt; other_player.username); } bool Player::operator&gt;(const Player &amp;other_player) const { return (username &gt; other_player.username); } bool Player::operator==(const Player &amp;other_player) const { return (username == other_player.username); } std::ostream&amp; operator&lt;&lt;(std::ostream &amp;output, const Player &amp;player) { output &lt;&lt; player.username &lt;&lt; ' ' &lt;&lt; player.password &lt;&lt; ' ' &lt;&lt; player.points; return output; } </code></pre> <p>PLAYER_DATABASE_H:</p> <pre><code>#define PLAYER_DATABASE_H #include &lt;algorithm&gt; #include &lt;fstream&gt; #include &quot;PLAYER_H.h&quot; #include &lt;vector&gt; class Player_database { public: explicit Player_database(std::string _database_file); ~Player_database(); Player* find_player(const std::string &amp;username, const std::string &amp;password); bool does_username_exist(const std::string &amp;username); bool does_account_exist(const std::string &amp;username, const std::string &amp;password); Player* register_account(const std::string &amp;username, const std::string &amp;password); Player* login(const std::string &amp;username, const std::string &amp;password); private: bool does_file_exist() const; void read_file_data(); void write_file_data() const; using player_vector = std::vector&lt;Player&gt;; player_vector players; const std::string database_file; }; #endif </code></pre> <p>player_database.cpp:</p> <pre><code> Player_database::Player_database(std::string _database_file) : database_file(_database_file) { if (does_file_exist()) read_file_data(); } Player_database::~Player_database() { write_file_data(); } Player* Player_database::find_player(const std::string &amp;username, const std::string &amp;password) { auto player_iter = std::find(players.begin(), players.end(), Player(username, password)); if (player_iter == players.end()) return nullptr; else return &amp;*player_iter; } bool Player_database::does_username_exist(const std::string &amp;username) { return std::binary_search(players.begin(), players.end(), Player(username, &quot;&quot;)); } bool Player_database::does_account_exist(const std::string &amp;username, const std::string &amp;password) { Player *player = find_player(username, password); if (!player || !player-&gt;is_my_password(password)) return false; return true; } Player* Player_database::register_account(const std::string &amp;username, const std::string &amp;password) { Player player(username, password); auto lb = std::lower_bound(players.begin(), players.end(), player); players.insert(lb, player); return &amp;(players[lb-players.begin()]); } Player* Player_database::login(const std::string &amp;username, const std::string &amp;password) { return find_player(username, password); } bool Player_database::does_file_exist() const { std::ifstream checker(database_file); return checker.good(); } void Player_database::read_file_data() { std::ifstream file_in(database_file); while (file_in.peek() != -1) { // is empty file? players.push_back(Player(file_in)); file_in.ignore(1, '\n'); } file_in.close(); } void Player_database::write_file_data() const { std::ofstream file_out(database_file, std::ofstream::trunc); for (auto &amp;player : players) { file_out &lt;&lt; player &lt;&lt; '\n'; } file_out.close(); } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T20:20:09.020", "Id": "516165", "Score": "0", "body": "I thought decrementing a signed int type when it's 0 would work like a clock and cycle to the maximum value it could equal?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T14:29:45.800", "Id": "516211", "Score": "0", "body": "@matmartelli No, but it will behave that way for `unsigned` types. For `signed`, the optimizer will assume that this never happens and not generate the code you expected. Here, the compiler will see that the entire expression exhibits UB when the value was 0, so it will assume it is never called when the value is 0, and throw away the `if` branch in that case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T21:12:13.777", "Id": "516264", "Score": "0", "body": "I'm not sure if this is just going completely over my head or I'm in a different thought process. But a signed type, decremented from 0, would just equal -1?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:55:04.633", "Id": "518338", "Score": "0", "body": "you're right, a signed type will decrement 0 to -1. I saw you mention \"like a clock and cycle to the maximum value\" and that would be for the smallest (negative) value it can hold, not zero. My remarks concern that **signed** types do not \"wrap around\". My first comment was wrong; I was also mixing up 0 and smallest-it-can-hold." } ]
[ { "body": "<p>Use <code>constexpr</code> and also use <code>string_view</code> to avoid copying the contents:</p>\n<pre><code>constexpr std::string_view player_data_file = &quot;player_data.txt&quot;;\n</code></pre>\n<p>Use <code>string_view</code> for parameters instead of <code>const string&amp;</code>.</p>\n<p>Don't compare directly against <code>nullptr</code>. Use the truth tests that are part of the pointer (or smart pointer!) types: <code>(player != nullptr)</code> should be <code>if(!player)</code></p>\n<pre><code>const Player_database &amp;database\n</code></pre>\n<p>In C++, it is normal to put the <code>&amp;</code> ir <code>*</code> qualifier <em>with the type</em> not with the name being declared. Write: <code>const Player_database&amp; database</code>).</p>\n<h1>more (added later)</h1>\n<p>Your <code>main</code> function is meandering. Functions should be <em>cohesive</em> and do one thing. In general, separate your program into input, &quot;the real work&quot;, and output.</p>\n<pre><code>int main() {\n \n std::cout &lt;&lt; std::numeric_limits&lt;points_t&gt;::max() &lt;&lt; &quot;\\n\\n&quot;;\n</code></pre>\n<p>I don't know why you are printing the maximum number here.</p>\n<pre><code> Player *player;\n</code></pre>\n<p>This is declared without being initialized. This is one clue that you have a section of code that really should be broken out into a separate function. E.g.: <code>Player* player = load_player();</code></p>\n<p>All the way from here----</p>\n<pre><code> Player_database database(player_data_file);\n \n menu_options choice = main_menu(database, std::cout, std::cin);\n \n switch (choice) {\n case LOGIN: {\n player = prompt_login(database, std::cout, std::cin, quit_prompt_msg);\n break;\n }\n case REGISTER: {\n player = prompt_register_account(database, std::cout, std::cin, quit_prompt_msg);\n break;\n }\n default: {\n player = nullptr;\n }\n }\n</code></pre>\n<p>----- to here, can be the contents of <code>load_player()</code>.\nBeing a separate function, that code can just <code>return</code> when it has the player, from each spot. Notice also that <code>database</code> is only used by this passage of code, another sign that this clump of code forms a cohesive subroutine on its own.</p>\n<pre><code> if (player != nullptr) {\n</code></pre>\n<p>Here you have the entire rest of the function inside the body of an <code>if</code>, which includes more variables and an even deeper loop. It would be clearer and simpler to just get out if the test fails. Then the rest of the program is on the main level of the function.</p>\n<p>What follows can itself be another function or even two. The user interaction should be in a separate function. Again, look at cohesiveness: is <code>answer</code> needed by the rest of the code? No, only for these few lines. Taken as a group, what is needed by these lines? Nothing; it does not care about the player or the game objects. What is produced? Just a <code>bool</code> result.</p>\n<pre><code> Game game(player);\n \n while (true) {\n game.play_round(std::cout, std::cin);\n \n if (game.point_limit_reached()) {\n std::cout &lt;&lt; &quot;\\nYou've reached the maximum number of points! If you score another point, your points will be reset to 0.\\n\\n\\n&quot;;\n }\n \n char answer;\n std::cout &lt;&lt; &quot;Play again? (y/n): &quot;;\n std::cin &gt;&gt; answer;\n std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\\n');\n std::cout &lt;&lt; '\\n';\n \n if (answer == 'n' || answer == 'N') break;\n }\n }\n \n std::cout &lt;&lt; &quot;Exited.&quot;;\n}\n</code></pre>\n<h1>others</h1>\n<p><code>std::uniform_int_distribution&lt;int&gt; uid(65, 90); // where 65 in ASCII = A and 90 = Z</code><br />\nWhy not just use <code>uid('A','Z')</code> directly? Chars implicitly convert to int, you know. Or if you must, <code>int{'A'}</code> etc. to be explicit.</p>\n<hr />\n<p><code>if (player_answer == correct_answer || player_answer == static_cast&lt;char&gt;(correct_answer+32)) {</code><br />\nHow about <code>if (correct_answer == toupper(player_answer) {</code> ?\nYou don't need to reveal exactly how upper and lower case are related, the <em>meaning</em> is clearly read, and it's better to apply the transformation to the typed input rather than the &quot;correct&quot; value.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T21:01:04.630", "Id": "516108", "Score": "0", "body": "I excluded 'const' for 'Player_database &database' in the prompt_login and prompt_register_account functions because in the function it access a modifier function member of database. Is that what you were addressing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T13:40:22.670", "Id": "516133", "Score": "0", "body": "I don't think so, since I didn't mention anything about `const`. For `database` I'm referring to the whitespace." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T17:45:58.327", "Id": "516154", "Score": "0", "body": "Ah okay, I see, my bad. Didn't know what ir was, it's meant to be or duh." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T17:47:30.127", "Id": "516155", "Score": "0", "body": "Can I ask, were these comments from a quick skim of the code? Or were these the only issues you noticed from thoroughly reading the entire code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T18:35:21.610", "Id": "516157", "Score": "0", "body": "@mastmartelli they are from a quick look. These are things that apply to an individual declaration or expression, easily spotted in isolation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T18:51:59.343", "Id": "516158", "Score": "0", "body": "@mastmartelli I added to the answer." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T19:38:28.057", "Id": "261526", "ParentId": "261496", "Score": "2" } } ]
{ "AcceptedAnswerId": "261526", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T05:25:28.043", "Id": "261496", "Score": "0", "Tags": [ "c++", "performance", "c++17", "memory-optimization" ], "Title": "Enter the randomly displayed letter console game" }
261496
<p>This is an old script I made a while ago.</p> <h2>What it does</h2> <p>It tracks your dose of whatever you want tracked (cigarettes, salt, etc), outputs the total for each day, and the full week.</p> <h2>What I’m looking for</h2> <p>I’ve recently been looking at <code>map()</code> and list comprehensions so I converted this script into both versions.</p> <p>I’d like to know if I’m doing it correctly and if I could do them better. I’d really appreciate some advice and help.</p> <p>They all output the same thing:</p> <h3>output:</h3> <pre class="lang-none prettyprint-override"><code>mon: 0 tue: 0 Total -&gt; changeme: 0changeme </code></pre> <p>1st version using <code>for loop</code>:</p> <pre class="lang-py prettyprint-override"><code>days = [ { &quot;day_name&quot;: &quot;mon&quot;, &quot;taken_at&quot;: { '12:00': 0, '14:00': 0, '16:00': 0 } }, { &quot;day_name&quot;: &quot;tue&quot;, &quot;taken_at&quot;: { '12:00': 0, '14:00': 0, '16:00': 0 } } ] dose_ray = [] unit = 'changeme' substance = 'changeme' for i in days: days = i[&quot;day_name&quot;] dose = i[&quot;taken_at&quot;].values() dose_per_day = sum(dose) print(f&quot;{days}: {dose_per_day}{unit}&quot;) dose_ray.append(dose_per_day) nl='\n' print(f&quot;{nl}Total -&gt; {substance}: {sum(dose_ray)} {unit}&quot;) </code></pre> <p>My first conversion was using <code>map()</code>, as I want to learn some functional techniques.</p> <h2>map version:</h2> <pre class="lang-py prettyprint-override"><code>day = list(map(lambda x: x[&quot;day_name&quot;], days)) nums = list(map(lambda x: sum(x[&quot;taken_at&quot;].values()), days)) list(map(lambda x, y: print(f&quot;{x}: {y}&quot;), day, nums)) </code></pre> <p>Then I converted to a list comprehension which is just a repetition of the map one:</p> <h2>list comprehension version:</h2> <pre class="lang-py prettyprint-override"><code>day = [i[&quot;day_name&quot;] for i in days] nums = [sum(i[&quot;taken_at&quot;].values()) for i in days] [print(f&quot;{i}: {x}&quot;) for i, x in zip(day, nums)] </code></pre>
[]
[ { "body": "<p><code>map</code>, though it is functional, is not the only way to express a functional routine, and I dare say there are much more legible ways to do an equivalent operation.</p>\n<p>First, your data structure itself would be better as an iterable of class instances, but for these purposes I've left it as a dictionary. The date and time data should be Python representations rather than strings.</p>\n<p>It's possible, though not necessary, to do this loop-less:</p>\n<pre><code>from datetime import time\nimport calendar\n\ndays = [\n {\n 'weekday': calendar.MONDAY,\n 'taken_at': {\n time(12): 1,\n time(14): 3,\n time(16): 5,\n }\n },\n {\n 'weekday': calendar.TUESDAY,\n 'taken_at': {\n time(12): 2,\n time(14): 2,\n time(16): 1,\n }\n }\n]\n\nunit = 'mg'\nsubstance = 'maple syrup'\n\nprint(\n '\\n'.join(\n f'{calendar.day_name[day[&quot;weekday&quot;]]}: '\n f'{sum(day[&quot;taken_at&quot;].values())} {unit}'\n for day in days\n )\n)\n\ntotal_dose = sum(\n sum(day['taken_at'].values())\n for day in days\n)\n\nprint(f'\\nTotal -&gt; {substance}: {total_dose} {unit}')\n</code></pre>\n<p>Printing one line at a time in a loop is also fine. But I would avoid <code>map</code>.</p>\n<p>An alternative way to get the last dose total is</p>\n<pre><code>total_dose = sum(\n dose\n for day in days\n for dose in day['taken_at'].values()\n)\n</code></pre>\n<p>which replaces the inner sum with an inner generator iteration.</p>\n<p>Here is one example of an object-oriented approach that is simple, offers a little bit of validation, and is type-hinted:</p>\n<pre><code>from datetime import time\nimport calendar\nfrom typing import Dict\n\nUNIT = 'mg'\nSUBSTANCE = 'maple syrup'\n\n\nclass DoseWeekday:\n def __init__(self, weekday: int, doses: Dict[time, float]):\n if not (0 &lt;= weekday &lt; len(calendar.day_name)):\n raise ValueError(f'{weekday} is not a valid weekday index')\n\n self.weekday, self.doses = weekday, doses\n\n @property\n def dose_total(self) -&gt; float:\n return sum(self.doses.values())\n\n @property\n def weekday_name(self) -&gt; str:\n return calendar.day_name[self.weekday]\n\n def __str__(self):\n return f'{self.weekday_name}: {self.dose_total} {UNIT}'\n\n\ndays = (\n DoseWeekday(\n calendar.MONDAY,\n {\n time(12): 1,\n time(14): 3,\n time(16): 5,\n },\n ),\n DoseWeekday(\n calendar.TUESDAY,\n {\n time(12): 2,\n time(14): 2,\n time(16): 1,\n },\n ),\n)\n\nprint('\\n'.join(str(day) for day in days))\ntotal_dose = sum(day.dose_total for day in days)\nprint(f'\\nTotal -&gt; {SUBSTANCE}: {total_dose} {UNIT}')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T16:05:49.393", "Id": "516220", "Score": "0", "body": "Thank you I like it, I’ll use your python representations for the days and times, though I’d like to go loop less so I’m quite interested in what you’d do for that as this example was quite surprising @reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T16:09:02.120", "Id": "516221", "Score": "0", "body": "Can you also show me what the data structure would look like as an iterable of a class, if you don’t mind? I’m also trying to learn classes but just can’t seem to grasp the point of them over using a file of functions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T16:37:12.383", "Id": "516223", "Score": "0", "body": "Edited. This is a way (though not the only way)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T16:45:55.993", "Id": "516224", "Score": "0", "body": "Thanks a lot I will learn from this :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T14:43:46.407", "Id": "261583", "ParentId": "261497", "Score": "1" } } ]
{ "AcceptedAnswerId": "261583", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T06:22:55.507", "Id": "261497", "Score": "2", "Tags": [ "python-3.x", "functional-programming", "comparative-review" ], "Title": "Dose tracker with daily and weekly totals" }
261497
<p>So this is a programming challenge I saw:</p> <blockquote> <p>Write a program that outputs all possibilities to put + or - or nothing between the numbers 1,2,…,9 (in this order) such that the result is 100. For example 1 + 2 + 3 - 4 + 5 + 6 + 78 + 9 = 100.</p> </blockquote> <p>This is interesting, if useless.</p> <p>Anyway I have written two scripts in Python 3 to solve the problem, and spoilers ahead!</p> <p>The results are:</p> <pre><code>1+2+3-4+5+6+78+9 1+2+34-5+67-8+9 1+23-4+5+6+78-9 1+23-4+56+7+8+9 12+3+4+5-6-7+89 12+3-4+5+67+8+9 12-3-4+5-6+7+89 123+4-5+67-89 123+45-67+8-9 123-4-5-6-7+8-9 123-45-67+89 </code></pre> <p>And the scripts are two-parted, one part to generate expressions and the other to evaluate them.</p> <p>The evaluation parts of the scripts are the same, but the generation parts are different.</p> <p>One script uses random numbers to add the fillers, and only append unique expressions to a list.</p> <p>This script takes less lines (39 lines), but takes a rather long time to generate all the expressions.</p> <p>The other script uses incremental iteration to generate the expressions, this script takes 57 lines, but it executes significantly faster.</p> <p>Here are the scripts:</p> <p><em><strong>Random</strong></em></p> <pre class="lang-py prettyprint-override"><code>import random, re lines = [] Fillers = ('+', '-', '') while len(lines) &lt; 6561: expression = '' n = 0 for i in range(17): if i % 2 == 0: n += 1 expression += str(n) else: expression += Fillers[random.randrange(3)] if expression not in lines: lines.append(expression) lines.remove('123456789') result = [] for line in lines: array = re.split('(\-|\+)', line) ops = 'add' num = 0 for a in array: if a.isdigit(): if ops == 'add': num += int(a) else: num -= int(a) elif a in Fillers: if a == '+': ops = 'add' else: ops = 'sub' if num == 100: result.append(line) result.sort() print(*result, sep='\n') </code></pre> <p><em><strong>Ordered</strong></em></p> <pre class="lang-py prettyprint-override"><code>import re array = [[0, 0, 0, 0, 0, 0, 0, 0]] elems = [0, 0, 0, 0, 0, 0, 0, 0] for n in range(6560): copy = elems.copy() copy[-1] += 1 while 3 in copy: i = copy.index(3) copy[i:] = [0] * (len(copy) - i) copy[i - 1] += 1 array.append(copy) elems = copy lines = [] Fillers = ('+', '-', '') j = 0 while len(lines) &lt; 6561: expression = '' i, k = 0, 0 for n in range(17): if n % 2 == 0: i += 1 expression += str(i) else: expression += Fillers[array[j][k]] k += 1 lines.append(expression) j += 1 lines.remove('123456789') result = [] for line in lines: array = re.split('(\-|\+)', line) ops = 'add' num = 0 for a in array: if a.isdigit(): if ops == 'add': num += int(a) else: num -= int(a) elif a in Fillers: if a == '+': ops = 'add' else: ops = 'sub' if num == 100: result.append(line) result.sort() print(*result, sep='\n') </code></pre> <p>What improvements can be made to the two scripts?</p> <p>Here I am asking about two problems:</p> <p>1, how to make the random generation take less time?</p> <p>2, how to make the ordered generation take less code while maintaining the same logic?</p> <p>Any help will be appreciated. (I will upvote any answers.)</p>
[]
[ { "body": "<p><strong>General</strong></p>\n<ol>\n<li>Move magic numbers into explicitly named variables. Otherwise it takes the reader a lot of unnecessary work to understand why <code>6561</code> and <code>17</code> are relevant and / or correct.</li>\n<li>Avoid multiple imports in one line (<code>import random, re</code>), prefer one import per line.</li>\n<li>Avoid multiple statements in a single line: <code>if num == 100: result.append(line)</code></li>\n<li>The regex <code>'(\\-|\\+)'</code> can be simplified to <code>'([-+])'</code>. <a href=\"https://stackoverflow.com/a/4724613/9173379\">Single character alternation or character class on StackOverflow</a></li>\n<li>Follow <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP8</a> for naming variables: <code>Fillers</code> -&gt; <code>fillers</code> or probably rather <code>FILLERS</code></li>\n<li>You don't need to evaluate expressions on your own, simply pass the <code>str</code> expression to <code>eval()</code>. Surprisingly, this executes a bit slower on my machine than your manual approach. I'd still prefer it for its readability, adaptability and conciseness.</li>\n</ol>\n<hr />\n<p><strong>Random</strong></p>\n<p>Note: This brute-force approach <em>might</em> be an interesting exercise, but the ordered approach is undoubtedly preferable for this challenge.</p>\n<ol>\n<li><code>FILLERS[random.randrange(3)]</code> is better expressed as <code>random.choice(FILLERS)</code></li>\n<li><code>lines.remove('123456789')</code>: I see no reason for manually removing this one single possibility.</li>\n<li>Repeated membership checking (<code>if expression not in lines</code>) can get expensive for a <code>list</code>. <code>set</code>s are optimised for membership checking. This change alone provides roughly a 5x speed-up on my machine.</li>\n<li>Using a list comprehension together with <code>itertools.chain.from_iterable()</code> is faster than manually constructing the expression.</li>\n</ol>\n<p><strong>Suggested code</strong></p>\n<pre><code>import random\nfrom itertools import chain\n\nDIGITS = '123456789'\nLAST_DIGIT = DIGITS[-1]\nNUM_DIGITS = len(DIGITS)\n\nNUM_FILLERS = len(DIGITS) - 1\nFILLERS = ('+', '-', '')\n\nTARGET = 100\n\nNUM_POSSIBILITIES = len(FILLERS) ** (NUM_DIGITS - 1)\n\n\ndef make_expression(digits, fillers):\n return ''.join(chain.from_iterable(zip(digits, fillers))) + LAST_DIGIT\n\n\ndef main():\n expressions = set()\n\n while len(expressions) &lt; NUM_POSSIBILITIES:\n fillers = [random.choice(FILLERS) for _ in range(NUM_FILLERS)]\n expressions.add(make_expression(DIGITS, fillers))\n\n result = sorted(expr for expr in expressions if eval(expr) == TARGET)\n\n print(*result, sep='\\n')\n</code></pre>\n<hr />\n<p><strong>Ordered</strong></p>\n<p>This approach desperately needs comments to explain the underlying logic. Adding proper documentation will increase your chances for a proper review significantly. It's unnecessarily hard to figure out what's going on and why for this snippet alone:</p>\n<pre><code>array = [[0, 0, 0, 0, 0, 0, 0, 0]]\nelems = [0, 0, 0, 0, 0, 0, 0, 0]\n\nfor n in range(6560):\n copy = elems.copy()\n copy[-1] += 1\n while 3 in copy:\n i = copy.index(3)\n copy[i:] = [0] * (len(copy) - i)\n copy[i - 1] += 1\n array.append(copy)\n elems = copy\n</code></pre>\n<p>You don't need to manually create and store <code>array</code> as a list of all possible combinations of characters. You can get a memory-efficient generator from <code>itertools.product</code></p>\n<p><strong>Suggested code</strong></p>\n<pre><code>from itertools import product, chain\n\nDIGITS = '123456789'\nLAST_DIGIT = DIGITS[-1]\n\nNUM_FILLERS = len(DIGITS) - 1\nFILLERS = ('+', '-', '')\n\nTARGET = 100\n\n\ndef make_expression(fillers):\n return ''.join(chain.from_iterable(zip(DIGITS, fillers))) + LAST_DIGIT\n\n\ndef main():\n candidates = product(FILLERS, repeat=NUM_FILLERS)\n\n expressions = [make_expression(candidate) for candidate in candidates]\n\n result = sorted(expr for expr in expressions if eval(expr) == TARGET)\n\n print(*result, sep='\\n')\n</code></pre>\n<p>I personally prefer this lazy approach for the main logic:</p>\n<pre><code>def main():\n candidates = product(FILLERS, repeat=NUM_FILLERS)\n\n expressions = map(make_expression, candidates)\n\n result = filter(lambda ex: eval(ex) == TARGET, expressions)\n\n output = sorted(result)\n\n print(*output, sep='\\n')\n</code></pre>\n<p>Please note that the suggested code executes about 10% slower than your approach (at least on my machine). But it's hard to beat when it comes to conciseness.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T15:55:16.500", "Id": "529041", "Score": "0", "body": "My bad, I missed your answer completely. Although I have to disagree with `print(*result, sep='\\n')` being somewhat hackish, I like your approach a lot and learned something new. Thanks for sharing!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T16:14:00.457", "Id": "529043", "Score": "0", "body": "Well, I just think that the `sep` parameter is *intended* for separators like `', '` or `'-'` or `''`. Not to allow us to do `print`'s job of adding newlines. I'm sure I've done it before myself, perhaps for golfing, but I don't find it clean. Plus I can never remember whether I should be worried about using `\\n` vs `\\r\\n` etc. If I just let `print` do it, I feel satisfied that it'll do the right thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T16:45:39.820", "Id": "529049", "Score": "0", "body": "I see your point (and I'm also always unsure about `\\n` vs `\\r\\n`, thanks Windows). But I think it's a bit of a stretch to call adding newlines `print`'s job, as the newline is simply the convenient default argument to `print`'s `end` argument. If you're not already iterating, I personally find using `sep=linesep` more concise and easier to read compared to `for x in y: print(x)`. Obviously up to some personal preference though." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:09:38.717", "Id": "261505", "ParentId": "261501", "Score": "7" } }, { "body": "<p>Your &quot;Ordered&quot; solution doesn't need to sort the expressions. By using the fillers in the order <code>('+', '-', '')</code> as you do, you already produce all strings in sorted order, as <code>+</code> is smaller than <code>-</code> is smaller than digits:</p>\n<pre><code>&gt;&gt;&gt; sorted('123456789-+')\n['+', '-', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n</code></pre>\n<p>Not having to sort at the end also means that you can simply print the good strings when you find them, instead of collecting them in a list and using the somewhat hackish <code>print(*result, sep='\\n')</code>.</p>\n<p>You're also reinventing several wheels. We can use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"nofollow noreferrer\">itertools.product</a> to build the fillers, <a href=\"https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting\" rel=\"nofollow noreferrer\">printf-style string formatting</a> to build the strings, and <a href=\"https://docs.python.org/3/library/functions.html#eval\" rel=\"nofollow noreferrer\">eval</a> to evaluate them:</p>\n<pre><code>from itertools import product\n\nfor p in product(('+', '-', ''), repeat=8):\n s = '%s'.join('123456789') % p\n if eval(s) == 100:\n print(s)\n</code></pre>\n<p><a href=\"https://tio.run/##NYvNDoIwEITvPMVcyLYRDYg/aMLDEC2xRrqbbTXx6Sto/A5zmG9G3unGoe1Ecx6VJ/jkNDE/IvwkrAmifH1eUlGMrBD48G@MoRVVoPUSZCuoEzekvrPnAjMRPaiMtLmzD4aabbvbH47diSxKyHfiR7jX8DDRou/R1PXvuSDqQ5pFzh8\" rel=\"nofollow noreferrer\" title=\"Python 3.8 (pre-release) – Try It Online\">Try it online!</a></p>\n<p>The format-string could be precomputed and stored in a variable, but the whole process takes only ~0.06 seconds anyway, and the <code>eval</code> takes about 90% of the time. No point optimizing the other 10%.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-22T23:36:34.963", "Id": "528979", "Score": "0", "body": "Woah. I had no idea you could use `str.join` like that (with a different character joining each pair of characters). Could you maybe add an explanation about how that works with the string formatting?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-22T23:40:31.973", "Id": "528981", "Score": "2", "body": "@AlexWaygood Well, it's not really the `join` that does it. That only produces the string `'1%s2%s3%s4%s5%s6%s7%s8%s9'` with *the same* joining string. And then it's the `%` operator that fills in the different fillers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-22T23:50:12.070", "Id": "528983", "Score": "0", "body": "Ahhh that makes sense, thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-22T23:55:19.330", "Id": "528984", "Score": "0", "body": "I think it was the %-style formatting that threw me off, which I haven't used in a while. I guess the equivalent with format-strings would be `'{}'.join('123456789').format(p)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T01:06:50.003", "Id": "528988", "Score": "1", "body": "@AlexWaygood Almost. You'd need to unpack `p`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T10:32:16.060", "Id": "529017", "Score": "1", "body": "Or as a one-liner: `print('\\n'.join(s for s in ('%s'.join('123456789') % p for p in product(('+', '-', ''), repeat=8)) if eval(s) == 100))`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T10:36:57.637", "Id": "529019", "Score": "2", "body": "@TobySpeight Eight characters shorter by using walrus: `print('\\n'.join(s for p in product(('+', '-', ''), repeat=8) if eval(s := '%s'.join('123456789') % p) == 100))`. But I think neither is appropriate for this site :-)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-22T20:22:18.080", "Id": "268264", "ParentId": "261501", "Score": "3" } } ]
{ "AcceptedAnswerId": "261505", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T08:56:00.827", "Id": "261501", "Score": "6", "Tags": [ "python", "performance", "beginner", "python-3.x", "programming-challenge" ], "Title": "Python Place +,-, nothing between 1, 2, …, 9 (in this order) whose sum is 100" }
261501
<p>I have the following code where I am trying to map columns from the input file to output.</p> <p>I have written it using multiple loops. Is there a way to write this more efficiently?</p> <h3>input.csv:</h3> <pre><code> Name, Age, Gender, Nation Joe, 18, Male, British </code></pre> <h3>output.csv:</h3> <pre><code>First_name, Age_Years, Gender_F_M, Religion, Nationality Joe, 18, Male, , British </code></pre> <h3>code:</h3> <pre><code>import csv renamed_headers = { &quot;First_name&quot;: &quot;Name&quot;, &quot;Age_Years&quot;:&quot;Age&quot;, &quot;Gender_F_M&quot;:&quot;Gender&quot;, &quot;Religion&quot;: None, &quot;Nationality&quot;: &quot;Nation&quot;, } with open(&quot;input.csv&quot;) as input_file, open(r&quot;output.csv&quot;, &quot;w&quot;, newline=&quot;&quot;) as output_file: reader = csv.DictReader(input_file, delimiter=&quot;,&quot;) writer = csv.writer(output_file, delimiter=&quot;,&quot;) # write headers header_line = [] for header_name in renamed_headers.keys(): header_line.append(header_name) writer.writerow(header_line) # write values for item in reader: row_to_write = [] print(item) for value in renamed_headers.values(): if value: row_to_write.append(item[value]) else: row_to_write.append(&quot;&quot;) writer.writerow(row_to_write) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:06:19.040", "Id": "516068", "Score": "0", "body": "I suspect that all the parts involving \"writerow\" should be one level of indentation deeper (so that we are still in the \"with\" block)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:07:22.553", "Id": "516069", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:07:33.280", "Id": "516070", "Score": "0", "body": "ah apologies the renamed header names were the wrong way round" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:08:36.463", "Id": "516071", "Score": "0", "body": "Is \"less code\" your only concern? Why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:10:25.270", "Id": "516072", "Score": "0", "body": "@Mast and if theres a more efficient way to write it - i feel as if I am looping too much in write row - what would be the best practice" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:48:41.603", "Id": "516073", "Score": "0", "body": "I think your write headers and write values sections are both wrongly indented. Now the file gets closed before you're done with the writing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:55:59.710", "Id": "516074", "Score": "0", "body": "I suggest you take a look at `pandas` if you ever need something more sophisticated than this. [Read](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html) the `.csv`. Optionally [select](https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html) some columns. [Rename](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html) the columns. [Save](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html) the data as a `.csv`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T12:18:30.773", "Id": "516076", "Score": "0", "body": "I've fixed your indentation (the alternative was closing the question). Please double-check your indentation next time yourself, it's *very* important in Python as it will completely change how your program works if it's pasted wrong. Please double-check if what I've made of it is indeed how it looks like in your IDE as well." } ]
[ { "body": "<p>You have made a good decision to read the rows as dicts. You can simplify the\ncode further by taking fuller advantage of the <code>csv</code> library's ability to write\ndicts as well.</p>\n<p>It's a good habit to write data transformation programs like this with a\nseparation between data collection, data conversion, and data output -- at\nleast if feasible, given other important considerations. Such separation has\nmany benefits related to testing, debugging, and flexibility in the face of\nevolving requirements. In addition, drawing clear boundaries tends to\nresult in code that is easier to read and understand quickly.</p>\n<p>Another good habit for such programs is to avoid hardcoding files paths\nin the script (other than as default values). It's often handy, for example,\nto test and debug with small files. Paths to those alternative files can\ncome from command-line arguments.</p>\n<p>If you want to be rigorous, you could extract a few more constants\nout of the code.</p>\n<p>An illustration:</p>\n<pre class=\"lang-python prettyprint-override\"><code>\nimport csv\nimport sys\n\nRENAMED_HEADERS = {\n 'First_name': 'Name',\n 'Age_Years':'Age',\n 'Gender_F_M':'Gender',\n 'Religion': None,\n 'Nationality': 'Nation',\n}\n\nDELIMITER = ','\n\nPATHS = ('input.csv', 'output.csv')\n\ndef main(args):\n input_path, output_path = args or PATHS\n rows = read_rows(input_path)\n converted = convert_rows(rows)\n write_rows(output_path, converted)\n\ndef read_rows(path):\n with open(path) as fh:\n reader = csv.DictReader(fh, delimiter=DELIMITER)\n return list(reader)\n\ndef convert_rows(rows):\n return [\n {\n new : r.get(old, '')\n for new, old in RENAMED_HEADERS.items()\n }\n for r in rows\n ]\n\ndef write_rows(path, rows):\n header = list(RENAMED_HEADERS)\n with open(path, 'w', newline='') as fh:\n writer = csv.DictWriter(fh, fieldnames=header, delimiter=DELIMITER)\n writer.writeheader()\n writer.writerows(rows)\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T04:52:16.190", "Id": "261534", "ParentId": "261504", "Score": "2" } } ]
{ "AcceptedAnswerId": "261534", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T10:38:38.893", "Id": "261504", "Score": "3", "Tags": [ "python", "python-3.x", "csv" ], "Title": "Mapping CSV columns" }
261504
<p>I am working on a <strong><a href="https://github.com/Ajax30/Larablog" rel="nofollow noreferrer">Laravel application</a></strong> (Github repo) that requires user registration and login.</p> <p>Alter registration, the users can <em>change their registration details</em> (except password, for which there is the default password recovery functionality) and add more info.</p> <p><a href="https://i.stack.imgur.com/8oYEbm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8oYEbm.png" alt="enter image description here" /></a></p> <p>They also have the possibility to replace the default avatar image with a picture of their choice</p> <p>In <code>routes\web.php</code> I have:</p> <pre><code>use Illuminate\Support\Facades\Route; Route::get('/', [App\Http\Controllers\Frontend\HomepageController::class, 'index'])-&gt;name('homepage'); Auth::routes(); Route::get('/dashboard', [App\Http\Controllers\Dashboard\DashboardController::class, 'index'])-&gt;name('dashboard'); Route::get('/dashboard/profile', [App\Http\Controllers\Dashboard\UserProfileController::class, 'index'])-&gt;name('profile'); Route::post('/dashboard/profile/update', [App\Http\Controllers\Dashboard\UserProfileController::class, 'update'])-&gt;name('profile.update'); Route::post('/dashboard/profile/deleteavatar/{id}', [App\Http\Controllers\Dashboard\UserProfileController::class, 'deleteavatar'])-&gt;name('profile.deleteavatar'); </code></pre> <p>In <code>Controllers\Dashboard\UserProfileController.php</code> I have:</p> <pre><code>namespace App\Http\Controllers\Dashboard; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Auth; use App\Models\UserProfile; class UserProfileController extends Controller { // Guard this route public function __construct() { $this-&gt;middleware('auth'); } public function index(UserProfile $user) { return view('dashboard.userprofile', array('current_user' =&gt; Auth::user()) ); } public function update(Request $request) { $current_user = Auth::user(); $request-&gt;validate([ 'first_name' =&gt; ['required', 'string', 'max:255'], 'last_name' =&gt; ['required', 'string', 'max:255'], 'email' =&gt; ['required', 'email', 'max:100', 'unique:users,email,'. $current_user-&gt;id], 'avatar' =&gt; ['mimes:jpeg, jpg, png, gif', 'max:2048'], ]); $current_user-&gt;first_name = $request-&gt;get('first_name'); $current_user-&gt;last_name = $request-&gt;get('last_name'); $current_user-&gt;email = $request-&gt;get('email'); $current_user-&gt;bio = $request-&gt;get('bio'); // Upload avatar if (isset($request-&gt;avatar)) { $imageName = md5(time()) . '.' . $request-&gt;avatar-&gt;extension(); $request-&gt;avatar-&gt;move(public_path('images/avatars'), $imageName); $current_user-&gt;avatar = $imageName; } // Update user $current_user-&gt;update(); return redirect('dashboard/profile') -&gt;with('success', 'User data updated successfully'); } // Delete avatar public function deleteavatar($id) { $current_user = Auth::user(); $current_user-&gt;avatar = &quot;default.png&quot;; $current_user-&gt;save(); } } </code></pre> <p>The <em>update profile</em> form:</p> <pre><code>&lt;form action=&quot;{{ route('profile.update') }}&quot; enctype='multipart/form-data' method=&quot;post&quot; novalidate&gt; {{csrf_field()}} &lt;div class=&quot;form-group&quot;&gt; &lt;input type=&quot;text&quot; id=&quot;first_name&quot; name=&quot;first_name&quot; placeholder=&quot;First name&quot; class=&quot;form-control&quot; value=&quot;{{old('first_name', $current_user-&gt;first_name)}}&quot;&gt; @if ($errors-&gt;has('first_name')) &lt;span class=&quot;errormsg text-danger&quot;&gt;{{ $errors-&gt;first('first_name') }}&lt;/span&gt; @endif &lt;/div&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;input type=&quot;text&quot; id=&quot;last_name&quot; name=&quot;last_name&quot; placeholder=&quot;Last name&quot; class=&quot;form-control&quot; value=&quot;{{old('last_name', $current_user-&gt;last_name)}}&quot;&gt; @if ($errors-&gt;has('first_name')) &lt;span class=&quot;errormsg text-danger&quot;&gt;{{ $errors-&gt;first('last_name') }}&lt;/span&gt; @endif &lt;/div&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;input type=&quot;text&quot; id=&quot;email&quot; name=&quot;email&quot; placeholder=&quot;E-mail address&quot; class=&quot;form-control&quot; value=&quot;{{old('email', $current_user-&gt;email)}}&quot;&gt; @if ($errors-&gt;has('email')) &lt;span class=&quot;errormsg text-danger&quot;&gt;{{ $errors-&gt;first('email') }}&lt;/span&gt; @endif &lt;/div&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;textarea name=&quot;bio&quot; id=&quot;bio&quot; class=&quot;form-control&quot; cols=&quot;30&quot; rows=&quot;6&quot;&gt;{{old('bio', $current_user-&gt;bio)}}&lt;/textarea&gt; @if ($errors-&gt;has('bio')) &lt;span class=&quot;errormsg text-danger&quot;&gt;{{ $errors-&gt;first('bio') }}&lt;/span&gt; @endif &lt;/div&gt; &lt;label for=&quot;avatar&quot; class=&quot;text-muted&quot;&gt;Upload avatar&lt;/label&gt; &lt;div class=&quot;form-group d-flex&quot;&gt; &lt;div class=&quot;w-75 pr-1&quot;&gt; &lt;input type='file' name='avatar' id=&quot;avatar&quot; class=&quot;form-control border-0 py-0 pl-0 file-upload-btn&quot; value=&quot;{{$current_user-&gt;avatar}}&quot;&gt; @if ($errors-&gt;has('avatar')) &lt;span class=&quot;errormsg text-danger&quot;&gt;{{ $errors-&gt;first('avatar') }}&lt;/span&gt; @endif &lt;/div&gt; &lt;div class=&quot;w-25 position-relative&quot; id=&quot;avatar-container&quot;&gt; &lt;img class=&quot;rounded-circle img-thumbnail avatar-preview&quot; src=&quot;{{asset('images/avatars')}}/{{$current_user-&gt;avatar}}&quot; alt=&quot;{{$current_user-&gt;first_name}} {{$current_user-&gt;first_name}}&quot;&gt; &lt;span class=&quot;avatar-trash&quot;&gt; @if($current_user-&gt;avatar !== 'default.png') &lt;a href=&quot;#&quot; class=&quot;icon text-light&quot; id=&quot;delete-avatar&quot; data-uid=&quot;{{$current_user-&gt;id}}&quot;&gt;&lt;i class=&quot;fa fa-trash&quot;&gt;&lt;/i&gt;&lt;/a&gt; @endif &lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;form-group d-flex mb-0&quot;&gt; &lt;div class=&quot;w-50 pr-1&quot;&gt; &lt;input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Save&quot; class=&quot;btn btn-block btn-primary&quot;&gt; &lt;/div&gt; &lt;div class=&quot;w-50 pl-1&quot;&gt; &lt;a href=&quot;{{route('profile')}}&quot; class=&quot;btn btn-block btn-primary&quot;&gt;Cancel&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>The deleting of the user's picture (reverting to the default avatar, in other words, is done via AJAX):</p> <pre><code>(function() { //Delete Avatar $('#delete-avatar').on('click', function(evt) { evt.preventDefault(); var $avatar = $('#avatar-container').find('img'); var $topAvatar = $('#top_avatar'); var $trashIcon = $(this); var defaultAvatar = APP_URL + '/images/avatars/default.png'; //Get user's ID var id = $(this).data('uid'); if (confirm('Delete the avatar?')) { var CSRF_TOKEN = $('meta[name=&quot;csrf-token&quot;]').attr('content'); $.ajax({ url: APP_URL + '/dashboard/profile/deleteavatar/' + id, method: 'POST', data: { id: id, _token: CSRF_TOKEN, }, success: function() { $avatar.attr('src', defaultAvatar); $topAvatar.attr('src', defaultAvatar); $trashIcon.remove(); } }); } }); })(); </code></pre> <h3>Questions:</h3> <ol> <li>Could the code be significantly &quot;shortened&quot;?</li> <li>Are there better alternatives to the means I have chosen to do the various &quot;actions&quot; (inserting/updating the avatar and bio, etc)?</li> <li>How can this be improved (in any way)?</li> </ol>
[]
[ { "body": "<p>I think I'll give it a shot. :)</p>\n<h3>1. Could the code be significantly &quot;shortened&quot;?</h3>\n<p>I think controller wise, it's okay. It's what I've learnt on Laracasts as well, almost the same thing.</p>\n<p>Anw, here are my 2 cents :)</p>\n<p><strong>userprofile.blade.php</strong></p>\n<pre><code>@if ($errors-&gt;has('first_name'))\n &lt;span class=&quot;errormsg text-danger&quot;&gt;{{ $errors-&gt;first('first_name') }}&lt;/span&gt;\n@endif\n</code></pre>\n<p>can be done with:</p>\n<pre><code>@error ('first_name')\n &lt;span class=&quot;errormsg text-danger&quot;&gt;{{ $message }}&lt;/span&gt;\n@enderror\n</code></pre>\n<p>Also, the <code>{{csrf_field()}}</code> can be replaced with <code>@csrf</code></p>\n<hr />\n<h3>2. Are there better alternatives to do the various &quot;actions&quot;?</h3>\n<p>From what I've learnt and experience, I do recommend checking out a few starter packages:</p>\n<ul>\n<li><a href=\"https://laravel.com/docs/8.x/starter-kits#breeze-and-inertia\" rel=\"nofollow noreferrer\">Laravel Breeze</a> (with Inertia)</li>\n<li><a href=\"https://jetstream.laravel.com/2.x/introduction.html\" rel=\"nofollow noreferrer\">Laravel Jetstream</a> (With Inertia or Livewire)</li>\n</ul>\n<p>These little starter kits come with authentication pre-installed. And by looking into it, I'm pretty sure you can make the most use out of these kits. (With smarts like you, I'm pretty sure avatar implementation should be no issue.) :)</p>\n<hr />\n<h3>3. How can this be improved (in any way)?</h3>\n<p>May I suggest Vue? I personally think it's beautiful because everything is in a component. Which includes event listeners, html.</p>\n<p>It's can also easily be injected into your blade file.</p>\n<p><strong>Major plus point</strong>: Paired with Inertia, your pages don't have to make a request every time you visit a page. Inertia automatically intercepts a request and makes a <em>partial page reload</em>, which makes your whole blog significantly faster.</p>\n<p>This can be included in your blog's navbar, perhaps? Maybe for loading tags etc.\nHere's a link to their <a href=\"https://inertiajs.com/\" rel=\"nofollow noreferrer\">docs</a></p>\n<p>Just a suggestion ¯\\_(ツ)_/¯ Let's say, at any point you want to make single page applications (SPA) in your blog, you can do so with Vue.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T15:58:23.003", "Id": "261587", "ParentId": "261507", "Score": "2" } }, { "body": "<p>The suggestions below should allow the code to be shortened and improved.</p>\n<h2>Update method</h2>\n<p>The <code>UserProfileController::update()</code> method is somewhat long. The sections below should allow it to be simplified.</p>\n<h3>Pass fields to update to model method <code>update()</code></h3>\n<p>The <code>UserProfileController::update()</code> method is somewhat long. Presuming that the model <code>UserProfile</code> is a sub-class of <code>Illuminate\\Database\\Eloquent\\Model</code> then the <a href=\"https://laravel.com/api/5.8/Illuminate/Database/Eloquent/Model.html#method_update\" rel=\"nofollow noreferrer\"><code>update()</code> method</a> can be passed an array of attributes to update. Instead of these lines:</p>\n<pre><code>$current_user-&gt;first_name = $request-&gt;get('first_name');\n$current_user-&gt;last_name = $request-&gt;get('last_name');\n$current_user-&gt;email = $request-&gt;get('email');\n$current_user-&gt;bio = $request-&gt;get('bio');\n</code></pre>\n<p>Get an array of fields to update from <code>$request-&gt;all()</code>, then set the <code>avatar</code> on that array if the avatar needs to be updated.</p>\n<h3>Make a form request class for handling the validation</h3>\n<p>The validation rules could be moved out to a <a href=\"https://laravel.com/docs/8.x/validation#form-request-validation\" rel=\"nofollow noreferrer\">FormRequest</a> subclass.</p>\n<pre><code>namespace App\\Http\\Requests;\n\nuse Auth;\nuse Illuminate\\Foundation\\Http\\FormRequest;\n\nclass UserUpdateRequest extends FormRequest\n{\n public function rules()\n {\n return [\n 'first_name' =&gt; ['required', 'string', 'max:255'],\n 'last_name' =&gt; ['required', 'string', 'max:255'],\n 'email' =&gt; ['required', 'email', 'max:100', 'unique:users,email,'. Auth::user()-&gt;id],\n 'avatar' =&gt; ['mimes:jpeg, jpg, png, gif', 'max:2048'],\n ];\n }\n}\n</code></pre>\n<p>If the validation fails <a href=\"https://laravel.com/docs/8.x/validation#form-request-validation\" rel=\"nofollow noreferrer\">and the request was an XHR request, an HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.</a>.</p>\n<p>Then that subclass can be injected instead of <code>Illuminate\\Http\\Request</code> in the <code>update</code> method arguments and use <code>$request-&gt;all()</code> to get the fields to pass to <code>$current_user-&gt;update()</code>.</p>\n<pre><code> public function update(UserUpdateRequest $request)\n {\n $current_user = Auth::user();\n $fieldsToUpdate = $request-&gt;all()\n // Upload avatar\n if (isset($request-&gt;avatar)) {\n $imageName = md5(time()) . '.' . $request-&gt;avatar-&gt;extension();\n $request-&gt;avatar-&gt;move(public_path('images/avatars'), $imageName);\n $fieldsToUpdate['avatar'] = $imageName;\n }\n \n // Update user\n $current_user-&gt;update($fieldsToUpdate);\n return redirect('dashboard/profile')\n -&gt;with('success', 'User data updated successfully');\n }\n</code></pre>\n<h2>Middleware</h2>\n<p>Instead of setting the middleware in the controller, a <a href=\"https://laravel.com/docs/8.x/middleware#middleware-groups\" rel=\"nofollow noreferrer\">Middleware Group</a> could be added to <code>routes\\web.php</code> - e.g.</p>\n<pre><code>Route::group(['middleware' =&gt; ['auth']], function() {\n Route::get('/dashboard', [App\\Http\\Controllers\\Dashboard\\DashboardController::class, 'index'])-&gt;name('dashboard');\n\n Route::get('/dashboard/profile', [App\\Http\\Controllers\\Dashboard\\UserProfileController::class, 'index'])-&gt;name('profile');\n\n Route::post('/dashboard/profile/update', [App\\Http\\Controllers\\Dashboard\\UserProfileController::class, 'update'])-&gt;name('profile.update');\n\n Route::post('/dashboard/profile/deleteavatar/{id}', [App\\Http\\Controllers\\Dashboard\\UserProfileController::class, 'deleteavatar'])-&gt;name('profile.deleteavatar'); \n});\n</code></pre>\n<p>Also, for the sake of readability (e.g. see <a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md#user-content-23-lines\" rel=\"nofollow noreferrer\">section 2.3</a> of <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">PSR-12</a>) it would be wise to alias the profile controller using <a href=\"https://www.php.net/manual/en/language.namespaces.importing.php\" rel=\"nofollow noreferrer\">a <code>use</code> statement</a>.</p>\n<pre><code>use App\\Http\\Controllers\\Dashboard\\UserProfileController;\n</code></pre>\n<p>Then each reference can simply be <code>UserProfileController</code> Instead of the fully qualified name.</p>\n<h2>Resource Controller</h2>\n<p>While it may not save many lines and would likely require updating the route paths, consider using a <a href=\"https://laravel.com/docs/8.x/controllers#resource-controllers\" rel=\"nofollow noreferrer\">Resource controller</a>. The Update route would instead be <code>/dashboard/profile</code> with the verb <code>PUT</code> or <code>PATCH</code>.</p>\n<h2>Testing</h2>\n<p><a href=\"https://laravel.com/docs/8.x/testing#introduction\" rel=\"nofollow noreferrer\">Laravel offers great support for writing feature tests</a> to ensure the routes output what you expect. It appears there is already a factory for the user and a migration for the user table so those could be used with the <a href=\"https://laravel.com/docs/8.x/database-testing#running-seeders\" rel=\"nofollow noreferrer\">RefreshDatabase</a> trait in tests.</p>\n<p>The tests could use the SQLite database engine for testing- simply by uncommenting the lines 24 and 25 of <a href=\"https://github.com/Ajax30/Larablog/blob/master/phpunit.xml\" rel=\"nofollow noreferrer\">phpunit.xml</a>.</p>\n<p>Feature tests can make great use of the <a href=\"https://laravel.com/docs/8.x/http-tests\" rel=\"nofollow noreferrer\">HTTP test</a> functions available- e.g. requesting routes <a href=\"https://laravel.com/docs/8.x/http-tests#session-and-authentication\" rel=\"nofollow noreferrer\">acting as a user</a> (see the example in that section about using a model factory to generate and authenticate a user) and ensuring the status is okay or redirected to a certain route with <a href=\"https://laravel.com/docs/8.x/http-tests#assert-redirect\" rel=\"nofollow noreferrer\"><code>assertRedirect()</code></a>.</p>\n<p>If using a formRequest subclass as suggested above an assertion could be made that the response code is 422 for invalid input (e.g. missing required field, wrong type of field, etc).</p>\n<h2>JavaScript</h2>\n<p>The call to <code>$.ajax()</code> can be replaced with a call to <a href=\"https://api.jquery.com/jQuery.post/\" rel=\"nofollow noreferrer\"><code>$.post()</code></a>. Then there is no need to specify the <code>method</code>, and the keys can be removed from the options:</p>\n<pre><code> $.post(\n APP_URL + '/dashboard/profile/deleteavatar/' + id,\n {\n id: id,\n _token: CSRF_TOKEN,\n },\n function() {\n $avatar.attr('src', defaultAvatar);\n $topAvatar.attr('src', defaultAvatar);\n $trashIcon.remove();\n }\n });\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T09:28:15.717", "Id": "518302", "Score": "0", "body": "Great advice. However, when I go to `/dashboard/profile/update` I am not redirected to the login page..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T04:25:28.257", "Id": "518512", "Score": "0", "body": "I checked out the code suggestion and found that `$current_user` was undefined in that example for `UserUpdateRequest`. Updating it works in my sample test and I have updated the example above." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T23:58:00.607", "Id": "261601", "ParentId": "261507", "Score": "1" } } ]
{ "AcceptedAnswerId": "261601", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:26:52.683", "Id": "261507", "Score": "4", "Tags": [ "javascript", "php", "ajax", "laravel" ], "Title": "Laravel 8 registration and login with user profiles" }
261507
<p>I have a lambda function which returns the nearest city from a latitude and longitude.</p> <p>My algorithm for this is resource heavy and time consuming. To optimise this, I hash the coordinates into a 6 digit combination representing the 5km tile they are in. For example 'apHsvW' might refer to New York.</p> <p>I save the hash in a postgres database, and also Redis. I want Redis to be the first choice and then fallback on the database and then the algorithm as a last resort.</p> <p>Here is my lambda code:</p> <pre><code>const database = require( './database' ) database.connect() const redis = require( './redis' ) redis.connect() exports.handler = async ( event, context ) =&gt; { const get = require( 'lodash.get' ) const set = require( 'lodash.set' ) //Params const { latitude, longitude } = get( event, 'queryStringParameters' ) || event || {} const invalid = isNaN( latitude ) || isNaN( longitude ) if ( invalid ) return response( 200, 'Invalid params' ) console.log( `Getting city for ${ latitude }, ${ longitude }` ) set( context, 'callbackWaitsForEmptyEventLoop', false ) //Hash their coordinates to get their tile const precision = process.env.PRECISION || 6 const hash = require( './hash' ).encode( latitude, longitude, precision ) console.log( `Got hash: ${ hash }` ) //See if redis has the city for this hash console.log( `Checking redis for hash` ) const cached = await redis.get( 'grid', hash ).catch( e =&gt; console.log( e )) if ( cached ) return response( 200, cached ) //Check the database after console.log( `Checking database for ${ hash }` ) const saved = await database.grid.get( hash ) if ( saved ) { await redis.set( 'grid', hash, saved ).catch( e =&gt; console.log( e )) return response( 200, saved ) } //Get the most suitable city console.log( `Running algorithm` ) const city = await getCity( latitude, longitude ) const { id, name, country, code } = city const data = { id, name, country, code } console.log( `City result: ${ id }, ${ name }, ${ country }` ) //Save to database and redis in parallel await Promise.allSettled([ database.grid.set( hash, id ), redis.set( 'grid', hash, data ) ]).catch( e =&gt; console.log( e )) return response( 200, data ) } </code></pre> <p>Here is my database connection function located in './database'</p> <pre><code>let database module.exports = { connect: () =&gt; { database = require( 'knex' )({ client: process.env.DATABASE_CLIENT || 'postgres', connection: { host: process.env.DATABASE_HOST || 'localhost', user: process.env.DATABASE_USER || 'admin', password: process.env.DATABASE_PASSWORD, database: process.env.DATABASE_NAME || 'postgres' } }) } } </code></pre> <p>And here is my redis file at './redis'</p> <pre><code>const get = require( 'lodash.get' ) let client module.exports = { connect: () =&gt; { console.log( '\nConnecting to Redis' ) //Create Redis client with env variables const redis = require( 'redis' ) const { REDIS_HOST, REDIS_PORT } = process.env client = redis.createClient({ host: REDIS_HOST, port: REDIS_PORT }) client.on( 'error', e =&gt; console.log( e )) client.on( 'ready', () =&gt; console.log( 'Connected' )) return client }, get: ( set, key ) =&gt; { return new Promise(( resolve, reject ) =&gt; { if ( !get( client, 'connected' )) return reject( 'Not connected to redis' ) client.hget( set, key, ( e, res ) =&gt; ( e ) ? reject( e ) : resolve( JSON.parse( res ))) }) }, set: ( set, key, value ) =&gt; { return new Promise(( resolve, reject ) =&gt; { if ( !get( client, 'connected' )) return reject( 'Not connected to redis' ) client.hmset( set, key, JSON.stringify( value ), e =&gt; ( e ) ? reject( e ) : resolve() ) }) } } </code></pre> <p>These are the following issues that im mainly concerned about</p> <ol> <li><p>Should my Db and Redis connections be defined outside of the handler?, I read it was good practise as it keeps the connection open for the next request.</p> </li> <li><p>Do I need <code>set( context, 'callbackWaitsForEmptyEventLoop', false )</code> to do this? I read that this should be done to keep Redis open, but im not sure if it applys to the db connection too</p> </li> <li><p>Would it be better to close the connection after im finished?</p> </li> <li><p>Since im not waiting for the success event from redis to know if its connected, Will the code potentially run before its finished connecting? I cant await it outside the handler.</p> </li> </ol> <p>I would also like any feedback in general to optimise this code further, even the smallest thing.</p> <p>Thankyou very much</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T13:46:21.710", "Id": "261510", "Score": "1", "Tags": [ "javascript", "lambda", "postgresql", "redis" ], "Title": "Fetch the nearest city, optimised with Redis on a Lambda" }
261510
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/261109/231235">Android APP FTP host profile class implementation</a> and <a href="https://codereview.stackexchange.com/q/260576/231235">Android APP connect to FTP server in Java</a>. I am attempting to perform the upload operation to specified FTP server in Android APP. With referring to <a href="https://stackoverflow.com/a/8154539/6667035">the answer of FtpClient storeFile always return False</a> and <a href="https://en.wikipedia.org/wiki/List_of_FTP_server_return_codes" rel="nofollow noreferrer">List of FTP server return codes on wikipedia</a>, the returned reply code is translated to <code>string</code> message.</p> <p><strong>The experimental implementation</strong></p> <ul> <li><p><code>FtpConnection</code> class implementation:</p> <pre><code>package com.example.ftpreplycodeclass; import android.util.Log; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.SocketException; import java.net.UnknownHostException; public final class FtpConnection { private final FtpHostProfiles ftpHostProfiles = new FtpHostProfiles(); public FtpConnection(FtpHostProfiles input) { this.ftpHostProfiles.addProfiles(input); } public boolean uploadFile(String profileName, String fullFilename) { File targetFile = new File(fullFilename); if (!targetFile.exists()) { Log.e(&quot;FTPconnection_uploadFile&quot;, &quot;File &quot; + fullFilename + &quot; isn't existed!&quot;); return false; } // Reference: https://stackoverflow.com/a/8761268/6667035 FTPClient ftp = new FTPClient(); try { FtpHostProfile profile = ftpHostProfiles.getProfile(profileName); // Reference: https://stackoverflow.com/a/55950845/6667035 // The argument of `FTPClient.connect` method is hostname, not URL. ftp.connect(profile.getHostname(), profile.getPort()); boolean status = ftp.login(profile.getUsername(), profile.getPassword()); if (status) { ftp.enterLocalPassiveMode(); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.sendCommand(&quot;OPTS UTF8 ON&quot;); } System.out.println(&quot;status : &quot; + ftp.getStatus()); Log.d(&quot;FTPTask&quot;, ftp.getStatus()); FileInputStream in = new FileInputStream(fullFilename); String filename = new File(fullFilename).getName(); boolean result = ftp.storeFile(filename, in); var detailedInfo = ftp.getReplyCode(); Log.d(&quot;FTP Reply Code&quot;, String.valueOf(detailedInfo)); Log.d(&quot;FTP Reply Message&quot;, FtpReplyCode.getReplyMessage(detailedInfo)); in.close(); ftp.logout(); ftp.disconnect(); return result; } catch (UnknownHostException ex) { ex.printStackTrace(); } catch (SocketException en) { // TODO Auto-generated catch block en.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } public FTPClient connectftp(String profileName) { // Reference: https://stackoverflow.com/a/8761268/6667035 FTPClient ftp = new FTPClient(); try { FtpHostProfile profile = ftpHostProfiles.getProfile(profileName); // Reference: https://stackoverflow.com/a/55950845/6667035 // The argument of `FtpClient.connect` method is hostname, not URL. ftp.connect(profile.getHostname(), profile.getPort()); boolean loggedIn = ftp.login(profile.getUsername(), profile.getPassword()); if (loggedIn) { ftp.enterLocalPassiveMode(); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.sendCommand(&quot;OPTS UTF8 ON&quot;); } System.out.println(&quot;status : &quot; + ftp.getStatus()); } catch (UnknownHostException ex) { ex.printStackTrace(); } catch (SocketException en) { en.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ftp; } private static class FtpReplyCode { private static String getReplyMessage(int input) { if (input == 100) { return &quot;The requested action is being initiated, expect another reply before proceeding with a new command.&quot;; } if (input == 110) { return &quot;Restart marker replay.&quot;; } if (input == 120) { return &quot;Service ready in nnn minutes.&quot;; } if (input == 125) { return &quot;Data connection already open; transfer starting.&quot;; } if (input == 150) { return &quot;File status okay; about to open data connection.&quot;; } if (input == 200) { return &quot;The requested action has been successfully completed.&quot;; } if (input == 202) { return &quot;Command not implemented, superfluous at this site.&quot;; } if (input == 211) { return &quot;System status, or system help reply.&quot;; } if (input == 212) { return &quot;Directory status.&quot;; } if (input == 213) { return &quot;File status.&quot;; } if (input == 214) { return &quot;Help message. Explains how to use the server or the meaning of a particular non-standard command. This reply is useful only to the human user.&quot;; } if (input == 215) { return &quot;NAME system type. Where NAME is an official system name from the registry kept by IANA.&quot;; } if (input == 220) { return &quot;Service ready for new user.&quot;; } if (input == 221) { return &quot;Service closing control connection.&quot;; } if (input == 225) { return &quot;Data connection open; no transfer in progress.&quot;; } if (input == 226) { return &quot;Closing data connection. Requested file action successful (for example, file transfer or file abort).&quot;; } if (input == 227) { return &quot;Entering Passive Mode (h1,h2,h3,h4,p1,p2).&quot;; } if (input == 228) { return &quot;Entering Long Passive Mode (long address, port).&quot;; } if (input == 229) { return &quot;Entering Extended Passive Mode (|||port|).&quot;; } if (input == 230) { return &quot;User logged in, proceed. Logged out if appropriate.&quot;; } if (input == 231) { return &quot;User logged out; service terminated.&quot;; } if (input == 232) { return &quot;Logout command noted, will complete when transfer done.&quot;; } if (input == 234) { return &quot;Specifies that the server accepts the authentication mechanism specified by the client, and the exchange of security data is complete. A higher level nonstandard code created by Microsoft.&quot;; } if (input == 250) { return &quot;Requested file action okay, completed.&quot;; } if (input == 257) { return &quot;\&quot;PATHNAME\&quot; created&quot;; } if (input == 300) { return &quot;The command has been accepted, but the requested action is on hold, pending receipt of further information.&quot;; } if (input == 331) { return &quot;User name okay, need password.&quot;; } if (input == 332) { return &quot;Need account for login.&quot;; } if (input == 350) { return &quot;Requested file action pending further information&quot;; } if (input == 400) { return &quot;The command was not accepted and the requested action did not take place, but the error condition is temporary and the action may be requested again.&quot;; } if (input == 421) { return &quot;Service not available, closing control connection. This may be a reply to any command if the service knows it must shut down.&quot;; } if (input == 425) { return &quot;Can\'t open data connection.&quot;; } if (input == 426) { return &quot;Connection closed; transfer aborted.&quot;; } if (input == 430) { return &quot;Invalid username or password&quot;; } if (input == 434) { return &quot;Requested host unavailable.&quot;; } if (input == 450) { return &quot;Requested file action not taken.&quot;; } if (input == 451) { return &quot;Requested action aborted. Local error in processing.&quot;; } if (input == 452) { return &quot;Requested action not taken. Insufficient storage space in system. File unavailable (e.g., file busy).&quot;; } if (input == 500) { return &quot;Syntax error, command unrecognized and the requested action did not take place. This may include errors such as command line too long.&quot;; } if (input == 501) { return &quot;Syntax error in parameters or arguments.&quot;; } if (input == 502) { return &quot;Command not implemented.&quot;; } if (input == 503) { return &quot;Bad sequence of commands.&quot;; } if (input == 504) { return &quot;Command not implemented for that parameter.&quot;; } if (input == 530) { return &quot;Not logged in.&quot;; } if (input == 532) { return &quot;Need account for storing files.&quot;; } if (input == 534) { return &quot;Could Not Connect to Server - Policy Requires SSL&quot;; } if (input == 550) { return &quot;Requested action not taken. File unavailable (e.g., file not found, no access).&quot;; } if (input == 551) { return &quot;Requested action aborted. Page type unknown.&quot;; } if (input == 552) { return &quot;Requested file action aborted. Exceeded storage allocation (for current directory or dataset).&quot;; } if (input == 553) { return &quot;Requested action not taken. File name not allowed.&quot;; } if (input == 600) { return &quot;Replies regarding confidentiality and integrity&quot;; } if (input == 631) { return &quot;Integrity protected reply.&quot;; } if (input == 632) { return &quot;Confidentiality and integrity protected reply.&quot;; } if (input == 633) { return &quot;Confidentiality protected reply.&quot;; } if (input == 10000) { return &quot;Common Winsock Error Codes&quot;; } if (input == 10054) { return &quot;Connection reset by peer. The connection was forcibly closed by the remote host.&quot;; } if (input == 10060) { return &quot;Cannot connect to remote server.&quot;; } if (input == 10061) { return &quot;Cannot connect to remote server. The connection is actively refused by the server.&quot;; } if (input == 10066) { return &quot;Directory not empty.&quot;; } if (input == 10068) { return &quot;Too many users, server is full.&quot;; } return &quot;&quot;; } } } </code></pre> </li> </ul> <p><strong>Full Testing Code</strong></p> <ul> <li><p><code>MainActivity.java</code> implementation:</p> <pre><code>package com.example.ftpreplycodeclass; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.TimeZone; public class MainActivity extends AppCompatActivity { private static final int READ_EXTERNAL_STORAGE_CODE = 1; private static final int WRITE_EXTERNAL_STORAGE_CODE = 2; private static final int ACCESS_NETWORK_STATE_CODE = 3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE_CODE); checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE_CODE); checkPermission(Manifest.permission.ACCESS_NETWORK_STATE, ACCESS_NETWORK_STATE_CODE); User currentUser = new User( &quot;Mike&quot;, &quot;M12345678&quot;, &quot;1990/10/13&quot;, &quot;(555) 555-1234&quot;, &quot;123456@test.com&quot;, &quot;password&quot;); // Using GMT (UTC±00:00) time var gmtTimeZone = new SimpleDateFormat(&quot;yyyyMMdd'T'HHmmss&quot;); gmtTimeZone.setTimeZone(TimeZone.getTimeZone(&quot;GMT&quot;)); String currentTime = gmtTimeZone.format(Calendar.getInstance().getTime()); String newUserRegistrationFilename = currentTime + &quot;_NewUser.ser&quot;; boolean isSaveSuccessfully = Serialization.Save(this, newUserRegistrationFilename, currentUser); if (isSaveSuccessfully) { showToast(&quot;Save current user information successfully&quot;, Toast.LENGTH_SHORT); Log.d(&quot;Save operation&quot;, &quot;Save current user information successfully&quot;); } showToast(Serialization.Load(this, newUserRegistrationFilename).getFullName(), Toast.LENGTH_SHORT); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } new FtpTask().execute(this.getApplicationInfo().dataDir + &quot;/files/&quot; + newUserRegistrationFilename); } // Function to check and request permission. public void checkPermission(String permission, int requestCode) { if (ContextCompat.checkSelfPermission(MainActivity.this, permission) == PackageManager.PERMISSION_DENIED) { // Requesting the permission ActivityCompat.requestPermissions(MainActivity.this, new String[] { permission }, requestCode); } else { Toast.makeText(MainActivity.this, &quot;Permission already granted&quot;, Toast.LENGTH_SHORT).show(); } } void showToast(String textInput, int duration) { Context context = getApplicationContext(); CharSequence text = textInput; Toast toast = Toast.makeText(context, text, duration); toast.show(); } // AsyncTask must be subclassed to be used. The subclass will override at least one method // `doInBackground(Params...)`, and most often will override a second one `onPostExecute(Result)` // Reference: https://developer.android.com/reference/android/os/AsyncTask?authuser=4 // Reference: https://stackoverflow.com/a/12447497/6667035 private class FtpTask extends AsyncTask&lt;String, Void, Boolean&gt; { // `doInBackground` invoked on the background thread immediately after `onPreExecute()` // finishes executing. This step is used to perform background computation // that can take a long time. The parameters of the asynchronous task are // passed to this step. The result of the computation must be returned by // this step and will be passed back to the last step. This step can also use // `publishProgress(Progress...)` to publish one or more units of progress. // These values are published on the UI thread, in the `onProgressUpdate(Progress...)` // step. protected Boolean doInBackground(String... filenames) { FtpHostProfiles ftpHostProfiles = new FtpHostProfiles(); ftpHostProfiles.addProfile(new FtpHostProfile( &quot;Profile1&quot;, &quot;Hostname1&quot;, 21, &quot;Username1&quot;, &quot;Password1&quot;)); ftpHostProfiles.addProfile(new FtpHostProfile( &quot;Profile2&quot;, &quot;Hostname2&quot;, 21, &quot;Username2&quot;, &quot;Password2&quot;)); FtpConnection ftpConnect = new FtpConnection(ftpHostProfiles); for (int i = 0; i &lt; filenames.length; i++) { Log.v(&quot;FTPTask&quot;,&quot;Preparing to upload &quot; + filenames[i]); var result = ftpConnect.uploadFile(&quot;Profile1&quot;, filenames[i]); if (result == false) { Log.v(&quot;FTPTask&quot;,&quot;Fail to upload &quot; + filenames[i] + &quot;!&quot;); return false; } else { Log.v(&quot;FTPTask&quot;,&quot;Upload &quot; + filenames[i] + &quot; successfully!&quot;); } if (isCancelled()) break; } return true; } // `onPostExecute` invoked on the UI thread after the background computation finishes. // The result of the background computation is passed to this step as // a parameter. protected void onPostExecute(boolean result) { if (result) { Log.v(&quot;FTPTask&quot;,&quot;FTP upload complete&quot;); } return; } } } </code></pre> </li> <li><p><code>User</code> class implementation:</p> <pre><code>package com.example.ftpreplycodeclass; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class User implements java.io.Serializable { private String fullName; private String personalID; private String dateOfBirth; private String cellPhoneNumber; private String emailInfo; private String password; public User(final String fullNameInput, final String personalIDInput, final String dateOfBirthInput, final String cellPhoneNumberInput, final String emailInfoInput, final String passwordInput) { fullName = fullNameInput; personalID = personalIDInput; dateOfBirth = dateOfBirthInput; cellPhoneNumber = cellPhoneNumberInput; emailInfo = emailInfoInput; try { password = hashingMethod(passwordInput); } catch (Exception ex) { password = passwordInput; } return; } public String getFullName() { return fullName; } public String getPersonalID() { return personalID; } public String getDateOfBirth() { return dateOfBirth; } public String getCellPhoneNumber() { return cellPhoneNumber; } public String getEmailInfo() { return emailInfo; } public String getHash() throws NoSuchAlgorithmException { return hashingMethod(fullName + personalID); } public String getHashedPassword() throws NoSuchAlgorithmException { return password; } public boolean checkPassword(String password) { boolean result = false; try { result = password.equals(hashingMethod(password)); } catch (Exception e) { e.printStackTrace(); } return result; } //********************************************************************************************** // Reference: https://stackoverflow.com/a/2624385/6667035 private String hashingMethod(String inputString) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance(&quot;SHA-256&quot;); String stringToHash = inputString; messageDigest.update(stringToHash.getBytes()); String stringHash = new String(messageDigest.digest()); return stringHash; } } </code></pre> </li> <li><p><code>Serialization</code> class implementation:</p> <pre><code>package com.example.ftpreplycodeclass; import android.content.Context; import android.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; // Reference: https://codereview.stackexchange.com/q/260909/231235 public class Serialization { // Reference: https://stackoverflow.com/a/4118917/6667035 // fileName cannot contain any path separator public static boolean Save(Context context, String fileName, User user) { try { FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE); String fullFilename = context.getFilesDir() + &quot;/&quot; + fileName; Log.d(&quot;Save&quot;, &quot;Save file in &quot; + fullFilename); ObjectOutputStream os = new ObjectOutputStream(fos); os.writeObject(user); os.close(); fos.close(); if (new File(fullFilename).exists()) { return true; } else { return false; } } catch (IOException i) { i.printStackTrace(); return false; } } public static User Load(Context context, String fileName) { try { FileInputStream fis = context.openFileInput(fileName); ObjectInputStream is = new ObjectInputStream(fis); User simpleClass = (User) is.readObject(); is.close(); fis.close(); return simpleClass; } catch (Exception e) { e.printStackTrace(); } return null; } } </code></pre> </li> <li><p><code>FtpHostProfile</code> class implementation:</p> <pre><code>package com.example.ftpreplycodeclass; public final class FtpHostProfile { private final String profileName; private final String ftpHostName; private final int ftpPort; private final String ftpUserName; private final String ftpPassword; public FtpHostProfile(String hostNameInput, int portInput, String userNameInput, String passwordInput) { this.profileName = &quot;&quot;; this.ftpHostName = hostNameInput; this.ftpPort = portInput; this.ftpUserName = userNameInput; this.ftpPassword = passwordInput; } public FtpHostProfile( String profileNameInput, String hostnameInput, int portInput, String usernameInput, String passwordInput) { this.profileName = profileNameInput; this.ftpHostName = hostnameInput; this.ftpPort = portInput; this.ftpUserName = usernameInput; this.ftpPassword = passwordInput; } public String getProfileName() { return this.profileName; } public String getHostname() { return this.ftpHostName; } public int getPort() { return this.ftpPort; } public String getUsername() { return this.ftpUserName; } public String getPassword() { return this.ftpPassword; } } </code></pre> </li> <li><p><code>FtpHostProfiles</code> class implementation:</p> <pre><code>package com.example.ftpreplycodeclass; import android.util.Log; import java.util.Collection; import java.util.HashMap; import java.util.Map; public final class FtpHostProfiles { private final Map&lt;String, FtpHostProfile&gt; profiles = new HashMap&lt;&gt;(); public FtpHostProfiles() { // Empty constructor } public FtpHostProfiles addProfile(FtpHostProfile input) { this.profiles.put(input.getProfileName(), input); return this; } public FtpHostProfiles addProfiles(Collection&lt;FtpHostProfile&gt; input) { input.stream().forEach(profile -&gt; profiles.put(profile.getProfileName(), profile)); return this; } public FtpHostProfiles addProfiles(FtpHostProfiles input) { this.profiles.putAll(input.profiles); return this; } public FtpHostProfile getProfile(String profileNameInput) { FtpHostProfile profile = profiles.get(profileNameInput); if (profile == null) { Log.d(&quot;GetProfile&quot;, &quot;No such item in stored profiles&quot;); throw new IllegalStateException(&quot;No such item in stored profiles&quot;); } return profile; } } </code></pre> </li> <li><p><code>AndroidManifest.xml</code>:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; package=&quot;com.example.ftpreplycodeclass&quot;&gt; &lt;application android:allowBackup=&quot;true&quot; android:icon=&quot;@mipmap/ic_launcher&quot; android:label=&quot;@string/app_name&quot; android:roundIcon=&quot;@mipmap/ic_launcher_round&quot; android:supportsRtl=&quot;true&quot; android:theme=&quot;@style/Theme.FtpReplyCodeClass&quot;&gt; &lt;activity android:name=&quot;.MainActivity&quot; android:exported=&quot;true&quot;&gt; &lt;intent-filter&gt; &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt; &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.ACCESS_WIFI_STATE&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot;/&gt; &lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; /&gt; &lt;/manifest&gt; </code></pre> </li> </ul> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/261109/231235">Android APP FTP host profile class implementation</a> and</p> <p><a href="https://codereview.stackexchange.com/q/260576/231235">Android APP connect to FTP server in Java</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>I am attempting to perform the upload operation to specified FTP server in Android APP in this post.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any possible improvement, please let me know.</p> </li> </ul>
[]
[ { "body": "<h2>FtpConnection</h2>\n<ul>\n<li>You're duplicating <code>connectftp</code> in <code>uploadFile</code>. <code>uploadFile</code> should probably call <code>connectftp</code> rather than re-implement it itself</li>\n<li>On that note, consider whether or not it makes sense to have construction and connection be two separate steps. While that is often a valid approach, having your class represent an <em>open</em> connection may sometimes be more natural</li>\n<li>The name <code>connectftp</code> is a bit redundant, isn't it? Having an <code>FtpConnection</code> class with a <code>connect</code> method seems clear enough to me</li>\n</ul>\n<h2>FtpReplyCode</h2>\n<ul>\n<li>I'm not sure <code>&quot;&quot;</code> is an appropriate response for unknown reply codes. If your program doesn't understand what the FTP server is asking for, I think that should be made more obvious. Maybe with an exception, or maybe by having <code>getReplyMessage</code> return an <code>Optional&lt;String&gt;</code> instead of a <code>String</code>.</li>\n<li>While there's nothing <em>wrong</em> with having a chain of <code>if</code>s like that, you're really just mapping some inputs to some outputs in a really straightforward way. Having a lookup table in the form of a <code>Map&lt;Integer, String&gt;</code> could be more flexible</li>\n</ul>\n<h2>User</h2>\n<ul>\n<li>I'm not sure if silently storing the password un-hashed if hashing fails is the best idea. It doesn't seem likely to fail, but if it does, you'd probably want to know</li>\n<li>Why is <code>getHashedPassword</code> declared as <code>throws NoSuchAlgorithmException</code>?</li>\n</ul>\n<h2>Serialization</h2>\n<ul>\n<li>You can get the file path using <code>context.getFileStreamPath(fileName)</code></li>\n<li>If something goes wrong during saving or loading, you might not end up closing the input/output streams. You might want to use <code>try-with-resources</code> statements to make sure they do get closed</li>\n<li>Method names should usually begin with a lowercase letter, so <code>save</code> and <code>load</code> rather than <code>Save</code> and <code>Load</code></li>\n</ul>\n<h2>FtpHostProfile / FtpHostProfiles</h2>\n<ul>\n<li>Do the profiles need to know their own names? Maybe they do, but if they don't, you might be able to have the names only exist in the context of a <code>FtpHostProfiles</code>, which could then go from needing a distinct class to just being a <code>Map&lt;String, FtpHostProfile&gt;</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T17:54:29.197", "Id": "261555", "ParentId": "261514", "Score": "1" } } ]
{ "AcceptedAnswerId": "261555", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T15:11:35.480", "Id": "261514", "Score": "1", "Tags": [ "java", "android", "file", "error-handling", "ftp" ], "Title": "Android APP FTP uploading file implementation in Java" }
261514
<p>This was written down solely as a mean to practice basic C++ and isn't meant to serve any production purposes. Clearly, the implementation can't handle all input formats: it always expects the CSV to have a header line, it doesn't treat quoted commas well, the file has to have a newline in the end, hardcoded separator, etc.</p> <p>I'm mostly interested in what am I doing wrong from the effectiveness and idiomatic perspective. I'm sure there's something wrong even with these 60 lines. For instance, I don't like the mech of filling <code>data</code>, I feel there's too much tossing stuff around.</p> <p>Do I feel right about it? Can it be done in a more concise and effective way? Anything else, maybe like a forgotten <code>const</code>, or a totally non-idiomatic way to do something?</p> <p>In short, how can I make this code (and subsequently, my C++) better? Thank you.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;map&gt; #include &lt;string&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;stdexcept&gt; template &lt;typename OutputIterator&gt; void explode(const std::string&amp; input, char sep, OutputIterator output) { std::istringstream buffer(input); std::string temp; while (std::getline(buffer, temp, sep)) { *output++ = temp; } } class CSV { private: std::vector&lt;std::string&gt; headers; std::vector&lt;std::map&lt;std::string, std::string&gt;&gt; data; size_t length{}; public: explicit CSV(const std::string&amp; filename) { std::ifstream ifs(filename); std::string s; std::getline(ifs, s, '\n'); explode(s, ',', std::back_insert_iterator&lt;std::vector&lt;std::string&gt;&gt;(headers)); std::map&lt;std::string, std::string&gt; temp_map; std::vector&lt;std::string&gt; temp_values; while (std::getline(ifs, s, '\n')) { explode(s, ',', std::back_insert_iterator&lt;std::vector&lt;std::string&gt;&gt;(temp_values)); for (size_t i = 0, headers_size = headers.size(); i &lt; headers_size; ++i) { temp_map[headers[i]] = temp_values[i]; } data.emplace_back(temp_map); temp_values.clear(); temp_map.clear(); ++length; } }; const std::map&lt;std::string, std::string&gt;&amp; operator[](const size_t&amp; index) { if (index &lt; 0 || index &gt;= length) throw std::runtime_error(&quot;Invalid index&quot;); return data[index]; } }; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const std::map&lt;std::string, std::string&gt;&amp; m) { for (const auto&amp; el: m) { os &lt;&lt; el.first &lt;&lt; &quot;: &quot; &lt;&lt; el.second &lt;&lt; &quot;, &quot;; } return os; } int main() { CSV c(&quot;data.csv&quot;); std::cout &lt;&lt; c[0] &lt;&lt; std::endl; return 0; } </code></pre>
[]
[ { "body": "<p>This is something I have done several times over the last 20 years, generally in a minimal fashion just for test input and single-use utilities, so like yours it doesn't handle bells and whistles but is simple and fast.</p>\n<p>Just reading through your code, it needs comments. I see what <code>explode</code> does: split an input at a delimiter and send the pieces to an output iterator.</p>\n<p>The main CSV class though, the first thing I wonder is why you have a <code>map</code> for <code>data</code>? I don't think of CSV as a key/value type of format, so what's it doing?</p>\n<p>OK, it reads &quot;headers&quot; as one line only, so it's not like HTTP headers. Later, I see it's supposed to be field names, also in the same CSV.</p>\n<p>So, after splitting a line, you do:</p>\n<pre><code>for (size_t i = 0, headers_size = headers.size(); i &lt; headers_size; ++i)\n temp_map[headers[i]] = temp_values[i];\n</code></pre>\n<p>So, you are storing the fields by name, as given in the header.</p>\n<p>Then a vector of these maps holds all the lines.</p>\n<hr />\n<p>That is a rather inefficient and memory hungry way to do it. All the lines have the <em>same</em> named fields. Maps are dynamic data structures, and thus slow due to memory allocation and cache misses when using them.</p>\n<p>You could store all the fields in a <code>vector</code> or other linear collection, and keep the names separately. Then, have access functions that can look up by name by finding the name in the headers first, and using the resulting index number to look up the field in the vector.</p>\n<hr />\n<pre><code>data.emplace_back(temp_map);\ntemp_map.clear();\n</code></pre>\n<p>You should use <code>std::move</code> since you are done with the <code>temp_map</code> anyway. This will prevent the expensive re-copying of the entire map, which is pointless since you just throw away the original. Or, you could start by pushing an empty element and get a reference to that, to use directly instead of a <code>temp_map</code>.</p>\n<p>You don't need <code>length</code> as it tracks the size of the vector. Just use the vector size directly to determine if an element is in range or not.</p>\n<pre><code>const std::map&lt;std::string, std::string&gt;&amp; operator[](const size_t&amp; index) {\n</code></pre>\n<p>Why are you passing <code>index</code> by reference? It's a simple machine-word integer type, so should be passed by value.</p>\n<p>This member function should also be declared as <code>const</code> as it accesses the data in the class but does not modify it.</p>\n<h2>so how do I do it?</h2>\n<p>Your <code>explode</code> function is fairly general, and could be used for splitting a line of text anywhere that is needed, not just as part of this CSV reader. For example, splitting the fields out of a date, splitting on a '-' or '/' character.</p>\n<p>I call this <code>split</code> and it is modeled after Perl's function of the same name. There is also a similar Boost library function, also called <code>split</code>.</p>\n<p>In my most recent version, I wanted to avoid memory allocation of a <code>vector</code> of results. I do that by returning a <code>std::array</code> instead, with the size known at compile time. This means that the memory is stored by the caller as a simple stack-based variable and no dynamic memory allocation is needed.</p>\n<p>Rather than copy every single <code>string</code>, I return <code>string_view</code> which points back to the original input. It does not need to copy the contents nor allocate memory. Note that it does mean that the result array has a lifetime limited to that of the input string, unlike yours which collects all the lines before returning.</p>\n<pre><code>template &lt;size_t N&gt;\nauto split (char separator, std::string_view input)\n{\n std::array&lt;std::string_view, N&gt; results; \n auto current = input.begin();\n const auto End = input.end();\n for (auto&amp; part : results)\n {\n if (current == End) {\n const bool is_last_part = &amp;part == &amp;(results.back());\n if (!is_last_part) throw std::invalid_argument (&quot;not enough parts to split&quot;);\n }\n auto delim = std::find (current, End, separator);\n part = { &amp;*current, size_t(delim-current) };\n current = delim;\n if (delim != End) ++current;\n }\n if (current != End) throw std::invalid_argument (&quot;too many parts to split&quot;);\n return results;\n}\n</code></pre>\n<p>And that's another difference: I don't parse the entire file before returning, but parse each line as I consume it. There's no need to store the parsed results for everything, unless you are going back and forth through the data before storing it away in its final form.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T19:21:39.040", "Id": "516253", "Score": "1", "body": "Thank you so much for your answer. I started to kind of refactor this, and came to realize: what if, while exploding the string, we do it with a simple class that takes the input string and then returns `std::string_view`s of its parts in succession? Right now I've implemented it with custom `.has_next()` and `.next()` methods, but it could be an iterator as well. Would that make sense? That way we wouldn't even copy the input string to begin with, so the additional memory usage would be kept to minimum. And yeah, I got rid of different maps over and over." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:44:26.627", "Id": "518335", "Score": "1", "body": "Yes, make it an iterator (see Boost Iterator Facade) and the object supports the range semantics so you can feed it directly to a range-based `for` loop. e.g. `for (auto sv : split(s,delim))` Actually you might want to present the label as well, since your files individually define the order (and presence) of the named fields." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T14:49:42.357", "Id": "518336", "Score": "1", "body": "@PavelGurkov In my current work, I drop the array of string views directly into a `struct` that is defined to represent that, converting each string to the proper actual type such as int or date. (The only code I have to write for a specific struct is to make sure the input fields are in the right order as expected by aggregate initialization)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T18:52:14.007", "Id": "261523", "ParentId": "261515", "Score": "2" } } ]
{ "AcceptedAnswerId": "261523", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T15:47:14.163", "Id": "261515", "Score": "4", "Tags": [ "c++", "beginner", "csv" ], "Title": "Basic CSV Parser in C++" }
261515
<p>I have a class called <code>Thing</code>. For simplicity, let's say it initializes with a unique id, and that's all that's unique about it:</p> <pre class="lang-js prettyprint-override"><code>class Thing { id: string; constructor(id: string) { this.id = id; } } </code></pre> <p>Based on its <code>id</code>, a <code>Thing</code> will reference a specific item in the underlying database. It is essentially an abstraction class to help interact with data.</p> <p>I have a helper class to manage the <code>Thing</code>s:</p> <pre class="lang-js prettyprint-override"><code>class AllTheThings { existingThings: Set&lt;Thing&gt; = new Set(); createThing(id: string){ const newThing = new Thing(id) this.existingThings.add(newThing) } } </code></pre> <p>Throughout a certain cycle in the code, <code>createThing</code> is called with a variety of <code>id</code>s. That cycle repeats, and <code>createThing</code> may be called again with the same <code>id</code>s from the last cycle. That is fine. But at the start of any cycle, I need to have a list of the unique <code>Thing</code>s that already have been created in the past.</p> <p>I need a way to keep a list of unique <code>Thing</code>s which have been created so far. I initially thought of using a <code>Set</code>, as above. However, due to the repetition, and the fact that I am adding a class instance to a set, the entries repeat. For example:</p> <pre><code>// cycle1: AllTheThings.createThing(1) AllTheThings.createThing(2) // cycle2: AllTheThings.createThing(2) AllTheThings.createThing(3) </code></pre> <p>My intention at the end of cycle2 is that I would have 3 unique items in the <code>existingThings</code> Set. But I end up with 4. For those not familiar with <code>Set</code>, this is because <code>new Thing(1) !== new Thing(1)</code>. While the resulting objects are identical, they are not the same, and they point to different references in memory. I get that.</p> <p>But the problem remains that I need a list of unique <code>Thing</code>s that have been created in the past. I am considering doing the following:</p> <pre><code>class AllTheThings { existingThings: Set&lt;string&gt; = new Set(); createThing(id: string){ const newThing = new Thing(id) this.existingThings.add(id) } } </code></pre> <p>So in this case, I am keeping a list of unique <code>id</code>s, and I won't get the same type of repetition as before. However, I really need a list of unique <code>Thing</code>s, not <code>Thing</code> ids. In reality the code is more complex, and a <code>new Thing</code> takes more arguments than just an <code>id</code>. While those arguments are available when calling <code>createThing</code>, they may not be available when accessing <code>existingThings</code>, which means I cannot easily recreate a <code>Thing</code> just from an <code>id</code> where <code>existingThings</code> is used - I need the whole <code>Thing</code>. I can go the route of using a <code>Set</code> of <code>id</code>s, but it would require a lot of refactoring.</p> <p>Is there a more concise way to maintain a list of unique objects/class instances in a <code>Set</code>?</p>
[]
[ { "body": "<p>One possible workaround could be to use a <code>Map</code> rather than a <code>Set</code>. That way you can store <code>Thing</code>s by their IDs (which we already know uniquely identify them) and then use those IDs to unambiguously get the <code>Thing</code> back later</p>\n<p>Admittedly, this does carry the risk that the IDs get out of sync and the <code>Map</code> ends up associating a <code>Thing</code> with the wrong ID, but it doesn't sound like <code>Thing</code>s' IDs are meant to change over their lifetimes, in which case it should be safe</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T17:58:57.977", "Id": "516099", "Score": "1", "body": "Interesting...I think this is a nice compromise. I can say `existingThings: Map<string, Thing> = new Map()`, then I can say `this.existingThings.set(newThing.id, newThing)`. Even when that same Thing is created with the same id, it will call `.set` again, but it won't duplicate, it will just overwrite, which I think will be fine. I will try this, thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T16:36:45.350", "Id": "261519", "ParentId": "261518", "Score": "2" } } ]
{ "AcceptedAnswerId": "261519", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T16:09:31.070", "Id": "261518", "Score": "1", "Tags": [ "javascript", "object-oriented", "typescript", "set" ], "Title": "Managing duplicate class instances in a javascript Set" }
261518
<p>Some time ago, I participated in a Game Jam using Pygame for the first time and I faced a few difficulties with some of its elements, notably the sounds and the events. That's why I decided to create my own Pygame wrapper to simplify its use. I made it firstly for my personnal use, but as I uploaded it on GitHub, I want it to be as clean as possible (it's also a good training to write clearner code). I tried to stick to PEP8 as much as possible, and to apply some principles of clean code, but I wanted an external point of view of my code to get feedback on formatting, readability, cleanliness, ...</p> <p>The main files I would like to have feedback about are those:</p> <p><em><strong>sound_manager.py</strong></em></p> <p>This class allows the programmer to add sound with names and to play them just by specifying the name (if multiples have the same name, it will chose randomly). It also handles music which one can play when they want, loop, get an event at the end, ...</p> <pre class="lang-py prettyprint-override"><code>import os import random import pygame import pyghelper.config as config class SoundManager: &quot;&quot;&quot; A class to ease the use of the mixer module of Pygame. &quot;&quot;&quot; def __init__(self): &quot;&quot;&quot;Initialize the sound manager instance and Pygame's Mixer.&quot;&quot;&quot; self.sounds = {} self.musics = {} pygame.mixer.init() def __add_sound_dic(self, sound: str, sound_name: str): &quot;&quot;&quot;Add the sound to the dictionary of sound, creating the entry if it does not exist.&quot;&quot;&quot; if sound_name not in self.sounds: self.sounds[sound_name] = [] self.sounds[sound_name].append(sound) def add_sound(self, sound_path: str, sound_name: str, volume: int = 1.0): &quot;&quot;&quot; Add a new sound to the manager. sound_path: path to the sound file. sound_name: name of the sound, used to play it later. volume: volume of the sound, between 0.0 and 1.0 inclusive (default: 1.0). &quot;&quot;&quot; if sound_name == &quot;&quot;: raise ValueError(&quot;The sound name cannot be empty.&quot;) try: sound = pygame.mixer.Sound(sound_path) except FileNotFoundError: raise FileNotFoundError(&quot;Sound file '{}' does not exist or is inaccessible.&quot;.format(sound_path)) sound.set_volume(volume) self.__add_sound_dic(sound, sound_name) def play_sound(self, sound_name: str): &quot;&quot;&quot; Play a random sound among those with the specified name. sound_name: name of the sound to be played. &quot;&quot;&quot; if sound_name not in self.sounds or len(self.sounds[sound_name]) == 0: raise IndexError(&quot;Sound '{}' does not exist.&quot;.format(sound_name)) sound_to_play = random.choice(self.sounds[sound_name]) sound_to_play.play() def add_music(self, music_path: str, music_name: str): &quot;&quot;&quot; Add a new music to the manager. music_path: path to the music file. music_name: name of the music, used to play it later. &quot;&quot;&quot; if music_name == &quot;&quot;: raise ValueError(&quot;The music name cannot be empty.&quot;) if not os.path.isfile(music_path): raise FileNotFoundError(&quot;Music file '{}' does not exist or is inaccessible.&quot;.format(music_path)) if music_name in self.musics: raise ValueError(&quot;This name is already used by another music.&quot;) self.musics[music_name] = music_path def __load_music(self, music_path: str): try: pygame.mixer.music.load(music_path) except pygame.error: raise FileNotFoundError(&quot;File '{}' does not exist or is inaccessible.&quot;.format(music_path)) def __play_music(self, loop: bool, volume: int = 1.0): # Pygame expects -1 to loop and 0 to play the music only once # So we take the negative value so when it is 'True' we send -1 pygame.mixer.music.play(loops=-loop) pygame.mixer.music.set_volume(volume) def play_random_music(self, loop: bool = False, volume: int = 1.0): &quot;&quot;&quot; Play a random music from the list. loop: indicates if the music should be looped (default: False). volume: volume at which to play the music, between 0.0 and 1.0 inclusive (default: 1.0). &quot;&quot;&quot; if len(self.musics) == 0: raise ValueError(&quot;No music previously added.&quot;) music_to_play = random.choice(list(self.musics.values())) self.__load_music(music_to_play) self.__play_music(loop=loop, volume=volume) def play_music(self, music_name: str, loop: bool = False, volume: int = 1.0): &quot;&quot;&quot; Play the music with the specified name. music_name: name of the music to be played. loop: indicates if the music should be looped (default: False). volume: volume at which to play the music, between 0.0 and 1.0 inclusive (default: 1.0). &quot;&quot;&quot; if music_name not in self.musics: raise IndexError(&quot;Music '{}' does not exist.&quot;.format(music_name)) music_to_play = self.musics[music_name] self.__load_music(music_to_play) self.__play_music(loop=loop, volume=volume) def pause_music(self): &quot;&quot;&quot;Pause the music.&quot;&quot;&quot; pygame.mixer.music.pause() def resume_music(self): &quot;&quot;&quot;Unpause the music.&quot;&quot;&quot; pygame.mixer.music.unpause() def stop_music(self): &quot;&quot;&quot;Stop the music.&quot;&quot;&quot; pygame.mixer.music.stop() def is_music_playing(self) -&gt; bool: &quot;&quot;&quot;Returns True when the music is playing and not paused.&quot;&quot;&quot; return pygame.mixer.music.get_busy() def enable_music_endevent(self): &quot;&quot;&quot; Enable the posting of an event when the music ends. Uses pygame.USEREVENT+1 as type, so be aware of any conflict. &quot;&quot;&quot; pygame.mixer.music.set_endevent(config.MUSICENDEVENT) def disable_music_endevent(self): &quot;&quot;&quot;Disable the posting of an event when the music ends (default state).&quot;&quot;&quot; pygame.mixer.music.set_endevent() </code></pre> <p><em><strong>event_manager.py</strong></em></p> <p>This class allows the adding of callback functions for a lot of premade Pygame's events (quitting, mouse events, keys events, ...) as well as allowing easy-to-use custom events with custom data. It is used by first calling all the <code>set_xxx_callback()</code> functions needed, and then calling <code>listen()</code> for each game loop. This function will call the specified callback when it detects an event.</p> <pre class="lang-py prettyprint-override"><code>import inspect from typing import Callable import pygame import pyghelper.config as config import pyghelper.utils as utils class EventManager: &quot;&quot;&quot; A class to ease the use of premade and custom events of PyGame. &quot;&quot;&quot; def __init__(self, use_default_quit_callback: bool = True): &quot;&quot;&quot; Initialize the event manager instance. No callback are set at the beginning, except the one for the 'QUIT' event if specified. use_default_quit_callback: indicated if the manager should use the Window.close function as a callback for the 'QUIT' event (default: True). &quot;&quot;&quot; self.premade_events = { pygame.QUIT: None, pygame.KEYDOWN: None, pygame.KEYUP: None, pygame.MOUSEMOTION: None, pygame.MOUSEBUTTONDOWN: None, pygame.MOUSEBUTTONUP: None, config.MUSICENDEVENT: None } if use_default_quit_callback: self.premade_events[pygame.QUIT] = utils.Window.close self.custom_events = {} def __get_parameters_count(self, function: Callable): return len(inspect.signature(function).parameters) def __check_function(self, callback: Callable, parameters_count: int): if not callable(callback): raise TypeError(&quot;The callback argument is not callable.&quot;) if self.__get_parameters_count(callback) != parameters_count: raise ValueError(&quot;The callback has {} parameters instead of {}.&quot;.format( self.__get_parameters_count(callback), parameters_count )) def __set_premade_callback(self, event_type: int, callback: Callable[[dict], None], parameters_count: int): self.__check_function(callback, parameters_count) self.premade_events[event_type] = callback def set_quit_callback(self, callback: Callable[[], None]): &quot;&quot;&quot; Set the callback for the 'QUIT' event. callback: function to be called when this event occurs. It should not have any parameters. &quot;&quot;&quot; self.__set_premade_callback(pygame.QUIT, callback, parameters_count=0) def set_keydown_callback(self, callback: Callable[[dict], None]): &quot;&quot;&quot; Set the callback for the 'KEYDOWN' event. callback: function to be called when this event occurs. It should have only one parameter : a dictionary containing the event data. &quot;&quot;&quot; self.__set_premade_callback(pygame.KEYDOWN, callback, parameters_count=1) def set_keyup_callback(self, callback: Callable[[dict], None]): &quot;&quot;&quot; Set the callback for the 'KEYUP' event. callback: function to be called when this event occurs. It should have only one parameter : a dictionary containing the event data. &quot;&quot;&quot; self.__set_premade_callback(pygame.KEYUP, callback, parameters_count=1) def set_mousemotion_callback(self, callback: Callable[[dict], None]): &quot;&quot;&quot; Set the callback for the 'MOUSEMOTION' event. callback: function to be called when this event occurs. It should have only one parameter : a dictionary containing the event data. &quot;&quot;&quot; self.__set_premade_callback(pygame.MOUSEMOTION, callback, parameters_count=1) def set_mousebuttondown_callback(self, callback: Callable[[dict], None]): &quot;&quot;&quot; Set the callback for the 'MOUSEBUTTONDOWN' event. callback: function to be called when this event occurs. It should have only one parameter : a dictionary containing the event data. &quot;&quot;&quot; self.__set_premade_callback(pygame.MOUSEBUTTONDOWN, callback, parameters_count=1) def set_mousebuttonup_callback(self, callback: Callable[[dict], None]): &quot;&quot;&quot; Set the callback for the 'MOUSEBUTTONUP' event. callback: function to be called when this event occurs. It should have only one parameter : a dictionary containing the event data. &quot;&quot;&quot; self.__set_premade_callback(pygame.MOUSEBUTTONUP, callback, parameters_count=1) def set_music_end_callback(self, callback: Callable[[], None]): &quot;&quot;&quot; Set the callback for the music end event (see SoundManager docs). callback: function to be called when this event occurs. It should not have any parameters. &quot;&quot;&quot; self.__set_premade_callback(config.MUSICENDEVENT, callback, parameters_count=0) def add_custom_event(self, event_name: str, callback: Callable[[dict], None]): &quot;&quot;&quot; Add a custom event with the specified name to the manager. event_name: name of the event, unique. callback: function to be called when this event occurs. It should have only one parameter : a dictionary containing the event data. When the event is posted, its data dictionary should at least have a 'name' field containing the name of the event. &quot;&quot;&quot; if event_name == &quot;&quot;: raise ValueError(&quot;Event name cannot be empty.&quot;) if event_name in self.custom_events: raise IndexError(&quot;Event name '{}' already exists.&quot;.format(event_name)) self.__check_function(callback, parameters_count=1) self.custom_events[event_name] = callback def __call_premade_event_callback_no_parameter(self, event_type: int): if event_type not in self.premade_events: return if self.premade_events[event_type] is None: return self.premade_events[event_type]() def __call_premade_event_callback_with_parameters(self, event_type: int, event: pygame.event.Event): if event_type not in self.premade_events: return if self.premade_events[event_type] is None: return self.premade_events[event_type](event.dict) def __call_custom_event_callback(self, event: pygame.event.Event): if 'name' not in event.dict: return event_name = event.dict['name'] if event_name not in self.custom_events: return self.custom_events[event_name](event.dict) def listen(self) -&gt; bool: &quot;&quot;&quot;Listen for incoming events, and call the right function accordingly. Returns True if it could fetch events.&quot;&quot;&quot; if not pygame.display.get_init(): return False for event in pygame.event.get(): if event.type == pygame.QUIT: self.__call_premade_event_callback_no_parameter(pygame.QUIT) elif event.type == pygame.USEREVENT: self.__call_custom_event_callback(event) elif event.type == config.MUSICENDEVENT: self.__call_premade_event_callback_no_parameter(config.MUSICENDEVENT) else: self.__call_premade_event_callback_with_parameters(event.type, event) return True </code></pre> <p>The entire project is available <a href="https://github.com/charon25/PythonGameHelper" rel="noreferrer">on GitHub</a>.</p> <p>Thank you very much for your time and help!</p>
[]
[ { "body": "<p>Here are a few small things I noticed looking through <code>SoundManager</code>. Some are influenced by personal preferences.</p>\n<ul>\n<li><strong>init</strong>: When I see <code>self.sounds = {}</code> I'm not immediately sure if it's supposed to be a <code>dict</code> or a <code>set</code>. The initializiation is of course correct, but I find the explicit constructors to increase readability in such cases.</li>\n<li><strong>__add_sound_dic</strong>: You're basically replicating the functionality of <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>collections.defaultdict</code></a> here. Might be worth looking into.</li>\n<li><strong>add_sound</strong>:\n<ul>\n<li><code>volume</code>'s type should be annotated as <code>float</code> instead of <code>int</code> (same for <code>__play_music</code>, <code>play_random_music</code>)</li>\n<li><code>self.__add_sound_dic(sound, sound_name)</code> gives me a warning, as <code>sound</code> is of type <code>Sound</code> instead of the expected type <code>str</code></li>\n<li><code>&quot;Sound file '{}' does not exist or is inaccessible.&quot;.format(sound_path)</code> can be put into an f-String: <code>f&quot;Sound file '{sound_path}' does not exist or is inaccessible.&quot;</code></li>\n</ul>\n</li>\n<li><strong>play_sound</strong>: <code>if sound_name not in self.sounds or len(self.sounds[sound_name]) == 0</code> can be simplified to <code>if not self.sounds.get(sound_name)</code>. This condition will fail for an empty list (as it's a falsy value) as well as a <code>sound_name</code> that's not in <code>self.sounds</code> (as <code>get</code> will return <code>None</code> in that case). I would propose the following slightly adjusted approach. Note that you need only one reference to <code>self.sounds</code> and the slightly clearer error message.</li>\n</ul>\n<pre><code>sound_candidates = self.sounds.get(sound_name)\n\nif not sound_candidates:\n raise IndexError(f&quot;No sounds found for Sound '{sound_name}'.&quot;)\n\nsound_to_play = random.choice(sound_candidates)\nsound_to_play.play()\n</code></pre>\n<ul>\n<li>I recommend using <code>pathlib.Path</code> instead of <code>os.path</code> (referring to <code>add_music</code>).</li>\n<li><strong>__play_music</strong>: Although it's not necessary, I'd make the <code>bool</code> -&gt; <code>int</code> conversion explicit in <code>pygame.mixer.music.play(loops=-int(loop))</code>. Otherwise it's not immediately clear what <code>-(bool)</code> is doing.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T13:24:52.147", "Id": "261543", "ParentId": "261520", "Score": "1" } } ]
{ "AcceptedAnswerId": "261543", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T16:56:22.807", "Id": "261520", "Score": "5", "Tags": [ "python", "pygame" ], "Title": "Python's Pygame wrapper" }
261520
<p><a href="https://github.com/speedrun-program/load-extender" rel="nofollow noreferrer">https://github.com/speedrun-program/load-extender</a></p> <p>This is the previous version: <a href="https://codereview.stackexchange.com/questions/255255/lengthening-the-time-it-takes-to-access-files-revision-2">lengthening the time it takes to access files REVISION #2</a></p> <p>To compile this, you need to download and include robin_hood.h, and on Windows you also need to install EasyHook.</p> <p>I made this because it helps us save non-load time in a speedrun.</p> <p>In this version, it uses unique_ptr int arrays instead of a class, it has a way to include leading and trailing spaces in file names, and it has a way to deal with if there’s already a file named files_and_delays.txt. I also made it so the txt files are in utf-16 LE on Windows because that’s how file paths are encoded on that OS.</p> <p>load_extender.cpp</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;chrono&gt; #include &lt;thread&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;mutex&gt; #include &lt;filesystem&gt; #include &lt;memory&gt; #include &lt;climits&gt; #ifndef THIS_IS_NOT_THE_TEST_PROGRAM #define THIS_IS_NOT_THE_TEST_PROGRAM #endif #ifdef _WIN32 using wstring_or_string = std::wstring; #include &lt;Windows.h&gt; // easyhook.h installed with NuGet // https://easyhook.github.io/documentation.html #include &lt;easyhook.h&gt; #else using wstring_or_string = std::string; #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include &lt;dlfcn.h&gt; #endif #include &quot;robin_hood.h&quot; #include &quot;other_functions.h&quot; // thank you for making this hash map, martinus. // here's his github: https://github.com/martinus/robin-hood-hashing static robin_hood::unordered_node_map&lt;wstring_or_string, std::unique_ptr&lt;int[]&gt;&gt; rh_map; static std::mutex delay_array_mutex = read_delays_file(rh_map); #ifdef _WIN32 static NTSTATUS WINAPI NtCreateFileHook( PHANDLE FileHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PIO_STATUS_BLOCK IoStatusBlock, PLARGE_INTEGER AllocationSize, ULONG FileAttributes, ULONG ShareAccess, ULONG CreateDisposition, ULONG CreateOptions, PVOID EaBuffer, ULONG EaLength) { const std::wstring&amp; file_path = ObjectAttributes-&gt;ObjectName-&gt;Buffer; // +1 so '\' isn't included. If '\' isn't found, the whole wstring is checked because npos + 1 is 0 const std::wstring&amp; file_name = file_path.substr(file_path.rfind(L&quot;\\&quot;) + 1); delay_file(rh_map, file_name, delay_array_mutex); return NtCreateFile( FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock, AllocationSize, FileAttributes, ShareAccess, CreateDisposition, CreateOptions, EaBuffer, EaLength ); } extern &quot;C&quot; void __declspec(dllexport) __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO * inRemoteInfo); void __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO* inRemoteInfo) { HOOK_TRACE_INFO hHook1 = {NULL}; LhInstallHook( GetProcAddress(GetModuleHandle(TEXT(&quot;ntdll&quot;)), &quot;NtCreateFile&quot;), NtCreateFileHook, NULL, &amp;hHook1 ); ULONG ACLEntries[1] = {0}; LhSetExclusiveACL(ACLEntries, 1, &amp;hHook1); } #else static auto original_fopen = reinterpret_cast&lt;FILE * (*)(const char* path, const char* mode)&gt;(dlsym(RTLD_NEXT, &quot;fopen&quot;)); FILE* fopen(const char* path, const char* mode) { // finding part of path which shows file name int file_name_index = -1; // increases to 0 and checks entire path if no slash is found for (int i = 0; path[i] != '\0'; i++) { if (path[i] == '/') { file_name_index = i; } } const std::string file_name(&amp;path[file_name_index + 1]); delay_file(rh_map, file_name, delay_array_mutex); return original_fopen(path, mode); } #endif </code></pre> <p>load_extender_test.cpp</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;mutex&gt; #include &lt;memory&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;filesystem&gt; #include &lt;climits&gt; #include &quot;robin_hood.h&quot; // thank you for making this hash map, martinus. // here's his github: https://github.com/martinus/robin-hood-hashing #ifdef _WIN32 using wstring_or_string = std::wstring; // file paths are UTF-16LE on Windows #else using wstring_or_string = std::string; #endif #include &quot;other_functions.h&quot; static void print_rh_map(robin_hood::unordered_node_map&lt;wstring_or_string, std::unique_ptr&lt;int[]&gt;&gt;&amp; rh_map) { printf(&quot;\n---------- hash map current state ----------\n&quot;); for (auto&amp; it : rh_map) { #ifdef _WIN32 printf(&quot;%ls /&quot;, it.first.c_str()); #else printf(&quot;%s /&quot;, it.first.c_str()); #endif int i = 1; // used after loop to check if -1 is at the end for (; it.second[i] &gt;= 0; i++) { printf(&quot; %d&quot;, it.second[i]); } if (it.second[i] == -1) { if (i == 1) { printf(&quot; RESET ALL&quot;); } else { printf(&quot; REPEAT&quot;); } } printf(&quot;: INDEX %d\n&quot;, it.second[0]); } printf(&quot;---------------------------------------------\n\n&quot;); } static void test_all_inputs() { #ifdef _WIN32 wchar_t path_separator = L'\\'; #else char path_separator = '/'; #endif wstring_or_string test_path; std::ifstream input_test_file; input_test_file.open(&quot;test_input.txt&quot;, std::ios::binary); if (input_test_file.fail()) { printf(&quot;couldn't open test_input.txt\n&quot;); return; } std::string file_content( (std::istreambuf_iterator&lt;char&gt;(input_test_file)), (std::istreambuf_iterator&lt;char&gt;()) ); if (file_content.length() &gt; 0 &amp;&amp; file_content[file_content.length() - 1] == '\n') { file_content.erase(file_content.length() - 1); } input_test_file.close(); #ifdef _WIN32 if (file_content.length() &lt; 2) { printf(&quot;test_input.txt byte order mark is missing\nsave test_input.txt as UTF-16 LE\n&quot;); return; } size_t start_index = 2; // first two bytes are BOM bytes #else size_t start_index = 0; #endif size_t stop_index = 0; robin_hood::unordered_node_map&lt;wstring_or_string, std::unique_ptr&lt;int[]&gt;&gt; rh_map; std::mutex delay_array_mutex = read_delays_file(rh_map); print_rh_map(rh_map); do // go through each line { #ifdef _WIN32 stop_index = file_content.find(&quot;\n\0&quot;, start_index); if (stop_index != std::string::npos) { // - 1 because of carriage return character test_path = string_to_wstring(file_content.substr(start_index, stop_index - start_index - 1)); } else { test_path = string_to_wstring(file_content.substr(start_index)); } start_index = stop_index + 2; // + 2 to go past newline character and null character printf(&quot;testing path: %ls\n&quot;, test_path.c_str()); #else stop_index = file_content.find(&quot;\n&quot;, start_index); if (stop_index != std::string::npos) { test_path = file_content.substr(start_index, stop_index - start_index); } else { test_path = file_content.substr(start_index); } start_index = stop_index + 1; // + 1 to go past newline character printf(&quot;testing path: %s\n&quot;, test_path.c_str()); #endif // +1 so separator isn't included // If separator isn't found, the whole wstring is checked because npos + 1 is 0 const wstring_or_string&amp; test_file = &amp;test_path[test_path.rfind(path_separator) + 1]; delay_file(rh_map, test_file, delay_array_mutex); print_rh_map(rh_map); test_path.clear(); } while (stop_index != std::string::npos); } int main(int argc, char* argv[]) { printf(&quot;\ntest start\n&quot;); test_all_inputs(); printf(&quot;test finished, press Enter to exit\n&quot;); std::string x; std::getline(std::cin, x); return 0; } </code></pre> <p>other_functions.h</p> <pre class="lang-cpp prettyprint-override"><code>#ifndef THIS_IS_NOT_THE_TEST_PROGRAM #include &lt;iostream&gt; #endif #ifdef _WIN32 static std::wstring string_to_wstring(std::string line) { std::wstring ws_line; for (size_t i = 1; i &lt; line.length(); i += 2) { ws_line.push_back((line[i - 1]) + (line[i] &lt;&lt; 8)); } return ws_line; } #endif static void remove_start_and_end_whitespace(wstring_or_string&amp; file_name) { wstring_or_string white_space = {9, 11, 12, 13, 32}; // whitespace character values size_t first_not_whitespace = file_name.find_first_not_of(white_space); size_t last_not_whitespace = file_name.find_last_not_of(white_space); if (first_not_whitespace == std::string::npos) { file_name.erase(0); } else { file_name = file_name.substr(first_not_whitespace, last_not_whitespace - first_not_whitespace + 1); } } static void set_key_and_value(robin_hood::unordered_node_map&lt;wstring_or_string, std::unique_ptr&lt;int[]&gt;&gt;&amp; rh_map, wstring_or_string&amp; line) { #ifndef THIS_IS_NOT_THE_TEST_PROGRAM static bool too_big_delay_seen = false; // this is used so the message will only be printed once #endif // 47 is forward slash, 45 is dash character, 10 is newline // numbers used so it will work with both string and wstring int current_delay = 0; size_t current_index = (line.length() &gt; 0 &amp;&amp; line[0] == 47); // start at 1 if first character is forward slash wstring_or_string file_name; std::vector&lt;int&gt; delay_sequence; delay_sequence.push_back(1); // first index keeps track of next index to get delay time from // get file name for (; current_index &lt; line.length() &amp;&amp; line[current_index] != 47 &amp;&amp; line[current_index] != 10; current_index++) { file_name.push_back(line[current_index]); } if (line[0] != 47) // remove leading and trailing whitespace if first character wasn't forward slash { remove_start_and_end_whitespace(file_name); } // get delay sequence for (current_index++; current_index &lt; line.length() &amp;&amp; line[current_index] != 10; current_index++) { if (line[current_index] &gt;= 48 &amp;&amp; line[current_index] &lt;= 57) // character is a number { int current_digit = line[current_index] - 48; // avoid going over INT_MAX if (((INT_MAX / 10) &gt; current_delay) || ((INT_MAX / 10) == current_delay &amp;&amp; (INT_MAX % 10) &gt;= current_digit)) { current_delay = ((current_delay * 10) + current_digit); } else { #ifndef THIS_IS_NOT_THE_TEST_PROGRAM if (!too_big_delay_seen) { too_big_delay_seen = true; printf(&quot;delay time can only be %d milliseconds\n&quot;, INT_MAX); } #endif current_delay = INT_MAX; } } else if (line[current_index] == 47) { delay_sequence.push_back(current_delay); current_delay = 0; } else if (line[current_index] == 45) { delay_sequence.push_back(-1); // sequence starts over after reaching the end current_delay = 0; break; } } if (current_delay != 0) { delay_sequence.push_back(current_delay); } if (delay_sequence[delay_sequence.size() - 1] != -1) { delay_sequence.push_back(-2); // sequence ends without starting over } if (delay_sequence[1] != -2) // no delay sequence written on this line { std::unique_ptr&lt;int[]&gt; delay_sequence_unique_ptr = std::make_unique&lt;int[]&gt;(delay_sequence.size()); // copy delays into std::unique_ptr&lt;int[]&gt; for (size_t i = 0; i &lt; delay_sequence.size() &amp;&amp; i &lt; INT_MAX; i++) { delay_sequence_unique_ptr[i] = delay_sequence[i]; } // delay sequence can't be longer that INT_MAX because first index keeps track of next index to get delay time from if ((delay_sequence.size() &gt; INT_MAX) || ((delay_sequence.size() == INT_MAX) &amp;&amp; (delay_sequence[INT_MAX] &gt;= 0))) { #ifndef THIS_IS_NOT_THE_TEST_PROGRAM printf(&quot;only %d delays can be stored in a delay sequence\n&quot;, INT_MAX - 2); #endif delay_sequence_unique_ptr[INT_MAX] = -2; } rh_map[wstring_or_string(file_name)] = std::move(delay_sequence_unique_ptr); } } static std::mutex read_delays_file(robin_hood::unordered_node_map&lt;wstring_or_string, std::unique_ptr&lt;int[]&gt;&gt;&amp; rh_map) { std::ifstream delays_file; std::string txt_file_name = &quot;files_and_delays.txt&quot;; // find files_and_delays.txt file with highest number at the end // this is used in case the directory already has a file named files_and_delays.txt for (int file_number = 0; std::filesystem::exists(&quot;files_and_delays&quot; + std::to_string(file_number) + &quot;.txt&quot;); file_number++) { txt_file_name = &quot;files_and_delays&quot; + std::to_string(file_number) + &quot;.txt&quot;; } #ifndef THIS_IS_NOT_THE_TEST_PROGRAM printf(&quot;opening %s\n&quot;, txt_file_name.c_str()); #endif delays_file.open(txt_file_name, std::ios::binary); if (delays_file.fail()) { #ifndef THIS_IS_NOT_THE_TEST_PROGRAM printf(&quot;couldn't open %s\n&quot;, txt_file_name.c_str()); #endif return std::mutex(); } std::string file_content( (std::istreambuf_iterator&lt;char&gt;(delays_file)), (std::istreambuf_iterator&lt;char&gt;()) ); delays_file.close(); #ifdef _WIN32 if (file_content.length() &lt; 2) { printf(&quot;files_and_delays.txt byte order mark is missing\nsave files_and_delays.txt as UTF-16 LE\n&quot;); return std::mutex(); } size_t start_index = 2; // first two bytes are BOM bytes #else size_t start_index = 0; #endif size_t stop_index = 0; do // go through each line { #ifdef _WIN32 stop_index = file_content.find(&quot;\n\0&quot;, start_index); std::wstring line = L&quot;&quot;; if (stop_index != std::string::npos) { // - 1 because of carriage return character line = string_to_wstring(file_content.substr(start_index, stop_index - start_index - 1)); } else { line = string_to_wstring(file_content.substr(start_index)); } start_index = stop_index + 2; #else stop_index = file_content.find(&quot;\n&quot;, start_index); std::string line = &quot;&quot;; if (stop_index != std::string::npos) { line = file_content.substr(start_index, stop_index - start_index); } else { line = file_content.substr(start_index); } start_index = stop_index + 1; #endif set_key_and_value(rh_map, line); } while (stop_index != std::string::npos); return std::mutex(); } void delay_file(robin_hood::unordered_node_map&lt;wstring_or_string, std::unique_ptr&lt;int[]&gt;&gt;&amp; rh_map, const wstring_or_string&amp; file_name, std::mutex&amp; delay_array_mutex) { #ifndef THIS_IS_NOT_THE_TEST_PROGRAM #ifdef _WIN32 char print_format[] = &quot;%ls&quot;; #else char print_format[] = &quot;%s&quot;; #endif #endif robin_hood::unordered_node_map&lt;wstring_or_string, std::unique_ptr&lt;int[]&gt;&gt;::iterator rh_map_iter = rh_map.find(file_name); if (rh_map_iter != rh_map.end()) { #ifndef THIS_IS_NOT_THE_TEST_PROGRAM printf(print_format, file_name.c_str()); printf(&quot; found in hash map\n&quot;); #endif int delay = 0; { std::lock_guard&lt;std::mutex&gt; delay_array_mutex_lock(delay_array_mutex); std::unique_ptr&lt;int[]&gt;&amp; delay_sequence = rh_map_iter-&gt;second; if (delay_sequence[1] == -1) { for (auto&amp; it : rh_map) { it.second[0] = 1; } #ifndef THIS_IS_NOT_THE_TEST_PROGRAM printf(&quot;all delay sequences reset\n&quot;); #endif } else if (delay_sequence[delay_sequence[0]] == -1) { delay_sequence[0] = 1; #ifndef THIS_IS_NOT_THE_TEST_PROGRAM printf(print_format, file_name.c_str()); printf(&quot; delay sequence reset\n&quot;); #endif } #ifndef THIS_IS_NOT_THE_TEST_PROGRAM else if (delay_sequence[delay_sequence[0]] == -2) { printf(print_format, file_name.c_str()); printf(&quot; delay sequence already finished\n&quot;); } #endif delay = delay_sequence[delay_sequence[0]]; delay_sequence[0] += (delay_sequence[delay_sequence[0]] &gt;= 0); // if it's -1 or -2, it's at the end already #ifndef THIS_IS_NOT_THE_TEST_PROGRAM delay *= (delay &gt;= 0); // it might be set to -1 or -2 printf(print_format, file_name.c_str()); printf(&quot; access delayed for %d second(s) and %d millisecond(s)\n&quot;, delay / 1000, delay % 1000); #endif } #ifdef THIS_IS_NOT_THE_TEST_PROGRAM if (delay &gt; 0) // it might be set to -1 or -2 { std::this_thread::sleep_for(std::chrono::milliseconds(delay)); } #endif } #ifndef THIS_IS_NOT_THE_TEST_PROGRAM else { printf(print_format, file_name.c_str()); printf(&quot; not found in hash map\n&quot;); } #endif } </code></pre> <p>load_extender_injector.cpp (only used on Windows because LD_PRELOAD and DYLD_INSERT_LIBRARIES can be used on Linux and Mac OS)</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;tchar.h&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;Windows.h&gt; // easyhook.h installed with NuGet // https://easyhook.github.io/documentation.html #include &lt;easyhook.h&gt; void get_exit_input() { std::wcout &lt;&lt; &quot;Press Enter to exit&quot;; std::wstring input; std::getline(std::wcin, input); std::getline(std::wcin, input); } int _tmain(int argc, _TCHAR* argv[]) { WCHAR* dllToInject32 = NULL; WCHAR* dllToInject64 = NULL; LPCWSTR lpApplicationName = argv[0]; DWORD lpBinaryType; if (GetBinaryType(lpApplicationName, &amp;lpBinaryType) == 0 || (lpBinaryType != 0 &amp;&amp; lpBinaryType != 6)) { std::wcout &lt;&lt; &quot;ERROR: This exe wasn't identified as 32-bit or as 64-bit&quot;; get_exit_input(); return 1; } else if (lpBinaryType == 0) { dllToInject32 = (WCHAR*)L&quot;load_extender_32.dll&quot;; } else { dllToInject64 = (WCHAR*)L&quot;load_extender_64.dll&quot;; } DWORD processId; std::wcout &lt;&lt; &quot;Enter the target process Id: &quot;; std::cin &gt;&gt; processId; wprintf(L&quot;Attempting to inject dll\n\n&quot;); // Inject dllToInject into the target process Id, passing // freqOffset as the pass through data. NTSTATUS nt = RhInjectLibrary( processId, // The process to inject into 0, // ThreadId to wake up upon injection EASYHOOK_INJECT_DEFAULT, dllToInject32, // 32-bit dllToInject64, // 64-bit NULL, // data to send to injected DLL entry point 0 // size of data to send ); if (nt != 0) { printf(&quot;RhInjectLibrary failed with error code = %d\n&quot;, nt); PWCHAR err = RtlGetLastErrorString(); std::wcout &lt;&lt; err &lt;&lt; &quot;\n&quot;; get_exit_input(); return 1; } else { std::wcout &lt;&lt; L&quot;Library injected successfully.\n&quot;; } get_exit_input(); return 0; } </code></pre>
[]
[ { "body": "<pre><code>// finding part of path which shows file name\n int file_name_index = -1; // increases to 0 and checks entire path if no slash is found\n for (int i = 0; path[i] != '\\0'; i++)\n {\n if (path[i] == '/')\n {\n file_name_index = i;\n }\n }\n</code></pre>\n<p>You mean <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/rfind\" rel=\"nofollow noreferrer\"><code>string::rfind</code></a>? Don't re-write functions that are already present in the collections or algorithms!</p>\n<p><strong>update:</strong> I see that <code>path</code> is a <code>const char*</code>. If you can't change the function to take a <code>string_view</code> just pop it into a <code>string_view</code> as the first line:</p>\n<pre><code>FILE* fopen(const char* path_raw, const char* mode)\n{\n std::string_view path(path_raw);\n const auto file_name_index = path.rfind('/');\n const std::string file_name(path,1,path.length()-1);\n ...\n</code></pre>\n<hr />\n<pre><code>static void remove_start_and_end_whitespace(wstring_or_string&amp; file_name)\n{\n wstring_or_string white_space = {9, 11, 12, 13, 32}; // whitespace character values\n</code></pre>\n<p>This would be easier and more efficient if you used <code>string_view</code>, which has a way to create a sub-view of the original, or a substring of a string, without recopying all the data when you trim from the front. I'd suggesting writing it to take a <code>string_view</code> that is constant, and return another <code>string_view</code>. You can still call it with an actual <code>string</code>.</p>\n<p>The <code>white_space</code> should be <code>constexpr</code> and you didn't even make it <code>static const</code>, so your code is re-creating a fresh one every time it is called.</p>\n<p>But you should not need to do this; use <code>isspace</code> to test whether a character is whitespace. There are forms of <code>std::find</code> that takes a functor, and it can search backwards by using reverse iterators.</p>\n<hr />\n<pre><code> // 47 is forward slash, 45 is dash character, 10 is newline\n // numbers used so it will work with both string and wstring\n</code></pre>\n<p>You should define the <em>character</em> type, not the whole string. Then you can use that with <code>basic_string</code>, <code>basic_string_view</code>, and single characters!</p>\n<p>Your &quot;numbers&quot; would become</p>\n<pre><code>constexpr auto slash = CharT(47);\n</code></pre>\n<p>but really you are widening the ASCII chars so you don't need the numbers:</p>\n<pre><code>constexpr auto slash = CharT('/');\n</code></pre>\n<p>If <code>CharT</code> is just <code>char</code> the cast does nothing; if it's <code>wchar_t</code> it is widened.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T19:15:22.350", "Id": "516101", "Score": "0", "body": "No because it’s a char array. I considered using strrchr there, but that ended up needing more to be written to deal with if NULL is returned." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T19:21:54.953", "Id": "516102", "Score": "0", "body": "Use `string_view` to wrap the raw string, and get all the useful members. Or use the standard algorithms instead: `std::find` on reverse iterators." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T19:32:36.570", "Id": "516103", "Score": "1", "body": "I updated my answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T19:07:03.013", "Id": "261524", "ParentId": "261522", "Score": "1" } } ]
{ "AcceptedAnswerId": "261524", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T18:05:08.113", "Id": "261522", "Score": "0", "Tags": [ "c++", "beginner" ], "Title": "lengthening the time it takes to access files REVISION #3" }
261522