body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Asking for a review of my implementation of a command pattern. In a Editor, words can be entered and the entering of words can be undone.</p> <p>General purpose Interface</p> <pre><code>public interface Command { void execute(); } </code></pre> <p>The concrete write word command</p> <pre><code>// Command public class WriteCommand implements Command { private Editor editor; private String word; public WriteCommand(String w, Editor e) { this.word = w; this.editor = e; } public String getWord() { return this.word; } public void execute() { this.editor.addToWordList(this.getWord()); } } </code></pre> <p>The undo command</p> <pre><code>public class UndoCommand implements Command { private Editor editor; public UndoCommand(Editor e) { this.editor = e; } @Override public void execute() { editor.removeFromWordList(); } } </code></pre> <p>The editor (i.e. receiver, i believe):</p> <pre><code>// Receiver public class Editor { private List&lt;String&gt; wordList; public Editor() { wordList = new ArrayList&lt;&gt;(); } public void addToWordList(String w) { this.wordList.add(w); } public void removeFromWordList() { this.wordList.remove(this.wordList.size()-1); } List&lt;String&gt; getWordList() { return this.wordList; } } </code></pre> <p>The invoker keeping the command queue:</p> <pre><code>public class Invoker { private List&lt;Command&gt; undoList; private List&lt;Command&gt; redoList; public Invoker() { undoList = new ArrayList&lt;&gt;(); redoList = new ArrayList&lt;&gt;(); } public void executeCommand(Command c) { undoList.add(c); c.execute(); } } </code></pre> <p>The client responsible for creating the commands:</p> <pre><code>public class Client { public static void main(String[] args) { Editor e = new Editor(); Invoker invoker = new Invoker(); invoker.executeCommand(new WriteCommand("Hello", e)); invoker.executeCommand(new WriteCommand("World", e)); System.out.println(e.getWordList()); invoker.executeCommand(new UndoCommand(e)); System.out.println(e.getWordList()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T01:28:34.440", "Id": "462753", "Score": "1", "body": "Seems to fit the bill. As general remarks: I would not include a reference to the editor in the `Command` itself - it makes more sense to make it a parameter for the `execute` method. That's more flexible, and you would have less trouble e.g. serializing the `Command` instances that way. Of course, you should not put the `UndoCommand` instances in the `undoList`. But to me, this seems to be on the right track." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T07:45:22.507", "Id": "462779", "Score": "1", "body": "Same as @MaartenBodewes, passing the \"context\" as parameter is more flexible than having it as an instance field. Just for the undo, it seems strange to use `removeFromWordList` your undo maye be used to undo other changes but also to remove another word; your user may want to have a menu to undo \"Hello\".. (think of your browser's history, you can go back to teh last \"n\" entries)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T10:31:54.093", "Id": "462809", "Score": "1", "body": "execute() should not take any arguments. Thats correct. Some commands may work over editor, some commands may work over other things. If execute accepted the editor than all commands have to. And that is not \"more flexible\". On other hand the undo logic should be contained within the commands themselves. Check my PoC PHP implementation, it is much more generic, but it should be well explanatory. https://github.com/slepic/PhpX/blob/master/src/CommandPattern/Undo/UndoableInvoker.php" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T12:56:52.420", "Id": "462823", "Score": "0", "body": "The requirement for command pattern is that the command object contains all required state in itself. Adding parameters to the method breaks this requirement and it stops being a command pattern." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T14:59:56.320", "Id": "462839", "Score": "0", "body": "@TorbenPutkonen The editors state is not part of the state of the command itself. There are certainly reasons to choose one over the other, but that's just bad argumentation. Similarly, I would not want every command in the same queue, so mixing commands for various parts of the program is not recommended. I don't want to have the \"Save\" action be in my `Edit -> Undo` queue, for one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T17:36:58.020", "Id": "462871", "Score": "0", "body": "Editor's state is part of the command in the sense that the command has a reference to the editor it manipulates. It wouldn't make sense to create an undo command on one editor and execute it on another. Anyway, I didn't invent this. If you're not sure about it, read Gang of Four. Also implementing save as a command that is executed some time in the future is silly. Q generic command queue is not a thing. The queue always has a specific purpose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T18:35:39.993", "Id": "462873", "Score": "0", "body": "I've read the book (although I am pretty sure that it is not *called* \"Gang of Four\"). I don't treat it as a bible though. Heck, I don't even treat the bible as a bible. I've also read e.g. Efficient Java, and commands can be made immutable and stateless *unless* you refer to `Editor` from within them. Serializing commands can be *very* useful, I hope you agree. OTOH, the editor state is dependent on the commands given and vice versa, so that says that including the editor reference can be useful. In that case you'll have to take extra care when serializing though." } ]
[ { "body": "<p><strong>If this was a school exercise</strong></p>\n\n<p>It's a basic command pattern without any safety checks against programming errors. :) It would be a good idea to check that a word can not be removed from an empty list.</p>\n\n<p><strong>If this was a job interview assignment</strong></p>\n\n<p>While the code shows that you know how to code a command pattern it doesn't tell me if you understand why one would want to use it. Having WriteCommand and UndoCommand objects going around in isolation makes very little sense. And domain-wise, writing to a text editor with command objects is probably not something that I would do.</p>\n\n<p>Instead put the command pattern into actual use by, for example, integrating it to the editor in the form of an undo/redo stack. Appending strings to the editor automatically create undo commands into the stack and performing the undo command executes the last command and adds a corresponding redo command into the redo stack.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T13:13:14.863", "Id": "236230", "ParentId": "236208", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-26T22:20:07.303", "Id": "236208", "Score": "5", "Tags": [ "java", "design-patterns" ], "Title": "Command Pattern: Does my implementation make the point?" }
236208
<p>I'm solving a problem with find and replace a substring in a string. I've solved it using Python with a couple of lines, in C++ using std library and now solved it with C by using allocation on the stack. I want to get genuine feedback on the code I wrote and perhaps make it simpler.</p> <p>The constraints:</p> <ul> <li>do not use standard library, write logic by hand. (I've included stdio.h primarily for debugging. Final version of the algorithm could be a function like: void find_and_replace(char* source, char* find, char* replace); )</li> </ul> <p>Requirements:</p> <ul> <li>Replace should replace all matches</li> <li>Match and replace same length string</li> <li>Replace longer match with shorter replacement</li> <li>Replace shorter match with longer replacement</li> </ul> <p></p> <pre><code>#include &lt;stdio.h&gt; int main() { enum SIZE { ARRAY_MAX = 50 }; char original[ARRAY_MAX] = "one two three two\0"; char find[ARRAY_MAX] = "two\0"; char replace[ARRAY_MAX] = "22222\0"; printf("original: %s\n", original); printf("find: %s\n", find); printf("replace: %s\n", replace); char* current = original; while (*current != '\0') { if (*current == find[0]) { char* match_iter = current; char* find_iter = find; int match = 0; while(*match_iter!='\0' &amp;&amp; *find_iter!='\0') { if (*match_iter == *find_iter) { match = 1; } else { match = 0; break; } match_iter++; find_iter++; } if (match) { printf("the whole word matched\n"); find_iter = find; char* replace_iter = replace; while(*find_iter != '\0' &amp;&amp; *current != '\0' &amp;&amp; *replace_iter != '\0') { *current = *replace_iter; ++find_iter; ++replace_iter; ++current; } if (*find_iter != '\0' &amp;&amp; *replace_iter == '\0') { printf("match is longer than replace\n"); char* move_left = current; while(*find_iter != '\0' &amp;&amp; *move_left != '\0') { ++find_iter; ++move_left; } char* temp_current = current; while(*move_left != '\0' &amp;&amp; *temp_current != '\0') { *temp_current = *move_left; ++temp_current; ++move_left; } *temp_current = '\0'; } else if (*find_iter == '\0' &amp;&amp; *replace_iter != '\0') { printf("replace is longer than match\n"); char* move_right = current; char temp[ARRAY_MAX]; char* temp_iter = temp; while(*replace_iter != '\0') { *temp_iter = *current; *current = *replace_iter; ++current; ++temp_iter; ++replace_iter; } char* current_to_end = current; while(*current_to_end != '\0') { *temp_iter = *current_to_end; ++temp_iter; ++current_to_end; } *temp_iter = '\0'; temp_iter = temp; char* temp_current = current; while(*temp_iter != '\0') { *temp_current = *temp_iter; ++temp_current; ++temp_iter; } *temp_current = '\0'; } else if (*find_iter == '\0' &amp;&amp; *replace_iter == '\0') { printf("replace and match are same length\n"); } } else { printf("only a fraction matched\n"); } } ++current; } printf("The sentence after replacement: %s\n", original); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T03:16:25.617", "Id": "462763", "Score": "5", "body": "Welcome to Code Review! Is this intended to be C? Or C++? C and C++ are different languages with very different programming techniques and idioms, so questions oriented to C and C++ are likely to generate very different reviews. Also, you seem to have violated the \"*do not use standard library*\" requirement by `#include <stdio.h>`. Is it meant to be something else?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T07:53:30.890", "Id": "462781", "Score": "1", "body": "@L.F. `<stdio.h>` is for...well i/o. Code sold1er is trying to show an algorithm for find/replace in string...not re-implementing standard input/output." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T08:11:34.180", "Id": "462783", "Score": "0", "body": "I am having a closer look at your code. Your code current compiles as `C`. Without the STL (ie the algorithms in the `std::`) and in this sort of problem domain any `C++` solution is going to be awfully close to the `C` solution. We could \"introduce\" some `C++` eg `constexpr` for the enum, but it would be a bit arbitrary..? Is the aim to make the code \"better and shorter\" or \"to use C++\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T08:16:36.310", "Id": "462784", "Score": "1", "body": "@L.F. Also, i think your edit confuses things. I believe the original poster wrote \"std\", Jamal changed it to \"STD\", and you changed it to \"standard\". `std` has special meaning in C++, it's the namespace for the standard library, and that's what the OP meant I believe. (so `<stdio.h>` is not part of that, because it's a C header for input output and not part of namespace `std::`). I presume you know all this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T08:20:14.857", "Id": "462786", "Score": "0", "body": "@OliverSchonrock So you're saying *standard library* is meant to be *the `std` namespace*? Well, that makes sense (just a bit counter-intuitive cuz that's \"use only a subset of the deprecated facilities of the standard library\" in C++). I've reverted that change; let's leave it up to the OP to judge. (btw, there's a \"do not use standard library\" requirement below)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T09:18:08.110", "Id": "462791", "Score": "0", "body": "1. stdio.h is used primarily for debugging purposes, to output information on the screen. I included it and the printfs for convenience. Later on the code could be used as a function call, such as void find_and_replace(char* source, char* find, char* replace). I see your point regarding the library I included. I will remove later on, in the final version. The main point here is just the code of algorithm. @L.F." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T09:25:28.053", "Id": "462792", "Score": "2", "body": "I see. Please [edit] your question to include this information. And then, please answer this question (as I mentioned in my [first comment](https://codereview.stackexchange.com/questions/236212/find-and-replace-a-string-in-c-c-without-using-standard-library?noredirect=1#comment462763_236212)): C or C++?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T09:27:15.030", "Id": "462793", "Score": "0", "body": "2. Regarding your comment if this is a c or c++. C code can be compiled by c++ compiler. I compiled this with gcc, and I believe it will compile under g++. I've asked both communities because I want to get a feedback on the logic, the ways to simplify code. I would consider both versions, c and c++. @L.F." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T22:17:15.980", "Id": "463513", "Score": "0", "body": "\" C code can be compiled by c++ compiler\" --> Not all C code compiles as C++. Not all will compile with the same functionality. Best practices differ." } ]
[ { "body": "<h2>Aim</h2>\n\n<p>It's not 100% clear in your question, but what I am <em>assuming</em> is that you would like some feedback on:</p>\n\n<ul>\n<li>How to utilize C++ for this problem domain without using the STL (ie namespace <code>std::</code>)</li>\n<li>How to improve / re-structure the code to make it \"better and shorter\". </li>\n</ul>\n\n<p>Just a general point. Obviously both C and C++ have standard functions and algorithms for doing this task. You have said that don't want to use these. You have not said \"why\". Perhaps you are on an embedded system, so C++ STL is not available? But then C <code>stdlib.h</code> should still be available and it has building blocks which you could be using (e.g. <code>strstr</code> <code>strncpy</code>) thereby avoiding quite so much manual pointer fiddling. So is your constraint of hand-coding this purely for educational purposes, or is there a possibility of at least using <code>stdlib</code> (which is also available under C++, of course)?</p>\n\n<h2>Evaluating existing code</h2>\n\n<ul>\n<li>Compiles => good</li>\n<li>Works => good</li>\n<li>doesn't appear to leak memory or access out of bounds (I only ran <code>valgrind</code>, more checks are needed) => good </li>\n<li><p>One warning generated:</p>\n\n<pre><code>fr.cpp:60:17: warning: unused variable 'move_right' [-Wunused-variable]\n char* move_right = current;\n</code></pre>\n\n<p>if I enable <code>-Wall -Wextra</code> on <code>clang</code>. You should turn warnings on and address them. </p></li>\n<li>Structure: One big <code>while</code> loop => could be better. </li>\n<li>Clarity: Related to structure. Without diving deep and putting my \"pointer-foo\" hat on, it's not trivial to understand what the code is doing. I get the general idea, but it's not very clear.</li>\n</ul>\n\n<h2>Feedback</h2>\n\n<p>Follows straight from the evaluation:</p>\n\n<ul>\n<li>Decide what you can and cannot use. Is <code>stdlib</code> (as opposed to C++ <code>std::</code>) allowed? If not, why not? If so, you should use it. I could show how, but it's been done already: <a href=\"https://www.geeksforgeeks.org/c-program-replace-word-text-another-given-word/\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/c-program-replace-word-text-another-given-word/</a>. That example uses the heap, but could be easily adapted to use the stack. Although the problem with <em>any</em> stack implementation (including yours) is that the <code>max_length</code> needs to be fixed at compile time. If I change your <code>replace</code> string to something > 25 characters long (replaced twice) the program segfaults due to clobbering its own stack. </li>\n<li>Decide if this is just an educational exercise and you do not want to use <code>stdlib</code> string primitives. The main answer to improving your code is using <em>functions</em>. Using functions will make each piece more digestible. Using good names for your functions will make the code self-documenting. A casual reader might get close to being able to read it like an English sentence. </li>\n</ul>\n\n<p>If you look at the link above, it shows you how the primitives can be used to make the code more readable, maintainable, reusable, and shorter. If you were to start with your own code and pull out some sections of the <code>while</code> loop as functions, you may find that the functions you pull out are very similar to the <code>stdlib</code> primitives. </p>\n\n<p>This could be a neat piece of experience. If you are unsure how to split your while loop, you could let the example above using the C library primitives guide you. Or you could do it blind and find out if you end up with similar functions/abstractions as the C library writers did. </p>\n\n<p>In the end <code>main()</code> should be a few lines, and each function should be no longer than say 10-15 lines at most. </p>\n\n<p>Assuming educational purpose, it would be better for you to try to pull out those sections rather than having someone do it for you. You learn more that way. </p>\n\n<h2>Some C++ points:</h2>\n\n<ul>\n<li>If you don't use any library at all, then, for this specific problem domain, the difference between C and C++ is going to be minimal. However, in general, one of big gains of using C++ over C for day-to-day usage is the convenience of handling strings using <code>std::string</code>. No more <code>malloc</code> <code>strncpy</code> <code>strdup</code> <code>strstr</code> etc. </li>\n<li>in C++ the include should be <code>#include &lt;cstdio&gt;</code></li>\n<li>C++ usually shouldn't use <code>printf</code>, but <code>std::cout</code> (assuming you don't mind about I/O using a base lib, as you already are). </li>\n<li>You should use a <code>constexpr</code> variable for <code>ARRAY_MAX</code>. <code>enum</code> is \"one of set\", which is not the case. (In C you should use a <code>#define</code> for this). </li>\n</ul>\n\n<h2>Python comparison</h2>\n\n<p>I feel the \"few lines of python\" comparison is not very relevant, because:</p>\n\n<ul>\n<li>a manually coded <code>str_replace</code> in python is likely to be unacceptably slow as a general function</li>\n<li>the operators you would have likely used in python (eg <code>str1 = str2</code>) are just calling some C or C++ function which are using <code>strncpy</code>/<code>std::string operator=()</code> or similar. </li>\n<li>So to use those operators in python, but refuse to use the C-functions is not a reasonable comparison IMO. </li>\n</ul>\n\n<p>Hope that gives you something to get on with. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T09:52:51.357", "Id": "462797", "Score": "0", "body": "Thanks a lot for taking the time and listing all this valuable points. After re-reading I do agree my question and intentions are not clear. I will try to improve my questions as I go along. This is my first PR here though :). The main reason why I put on restriction not to use any library functions is for educational purposes. I wanted to write the algorithm myself to better understand the logic, fiddle around with pointers, and appreciate how much easier it would've been, if I used c or a c++ library functions. I want to understand and be able to solve this questions on an interview etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T09:58:11.997", "Id": "462799", "Score": "0", "body": "@Code_So1dier That's fair enough. It's good to do at least once. And yes it's painful and error prone. Don't do this in an interview! I would not want someone to code that in an interview. I would want them to use the STL or libc. But it's good for learning. If you try to pull out those sections as functions you should find that the algorithm becomes clearer. Since you are new: If you are happy with an answer, upvote it and accept it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T10:03:22.123", "Id": "462801", "Score": "1", "body": "The comment I made regarding using a couple of lines in python is an example of solving a problem in multiple domains. Python here is at the top of programming language abstraction, where code is really easy to write and it utilises library calls, which is pre-compiled c. Then I solve the same question by using c++ with std library. Then goes c with standard library. Finally there is c without library calls, one solution with stack memory, another solution with heap memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T10:04:31.987", "Id": "462802", "Score": "0", "body": "@Code_So1dier Yes, exactly. You clearly understand how this all works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T16:48:38.113", "Id": "462996", "Score": "0", "body": "I prefer nothing but you can do whatever. `code`-formatting just looks odd to me for C." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T09:36:26.843", "Id": "236220", "ParentId": "236212", "Score": "6" } }, { "body": "<p>As mentioned in another answer, the best improvements to the code would be a function that is the equivelent of the C library function <code>strstr(char *hay_stack, char *needle)</code> and a function that replaces the string. This would simplify the <code>main()</code> function. One of the basic ways of writing a program is to keep breaking the problem down until the result is small functions that are easy to implement. The function <code>strstr()</code> can be written in less than 15 minutes, I know this because I used to use <code>implement strstr()</code> as an interview question.</p>\n\n<p>This would also reduce the number of variables required in <code>main()</code> and you wouldn't need to worry about partial matches.</p>\n\n<h2>Defining Symbolic Constants</h2>\n\n<p>In the code <code>ARRAY_MAX</code> is defined using an enum, and it is not really clear why. In C++ this could be defined using</p>\n\n<pre><code>int constexpr ARRAY_MAX = 50;\n</code></pre>\n\n<p>and in the C programming language </p>\n\n<pre><code>int const ARRAY_MAX2 = 50; // preferred method\n</code></pre>\n\n<p>or</p>\n\n<pre><code>#define ARRAY_MAX3 50 // Almost obsolete\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T19:07:05.267", "Id": "462876", "Score": "1", "body": "I don't think you can use a `const int` in an array size declaration. It has to be a `#define` (enum works too, but that's a style question). using a `const int` produces a VLA which is \"optional\" as per C11." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T23:13:29.180", "Id": "462890", "Score": "2", "body": "I disagree with you on \"int const ARRAY_MAX2 = 50; // preferred method\" - it would not even compile. Regarding \"strstr(char *hay_stack, char *needle)\" - yes it is a good way to wrap what I've written. I see your point regarding breaking up logic into smaller bits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T04:05:09.243", "Id": "462901", "Score": "0", "body": "`ARRAY_MAX3` usable in pre-processor, `ARRAY_MAX2` not so much. Minor: I'd expect `ARRAY_MAX2` in lower case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T11:56:12.900", "Id": "462942", "Score": "0", "body": "In C++ we can use `const int` in constant expressions, but unfortunately C doesn't allow that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T12:30:50.547", "Id": "462946", "Score": "0", "body": "`int const` isn't a good idea. It will cause the compiler to check the variable at runtime and generate a VLA unless you compile with optimization. It will also cause a symbol to be generated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T18:25:21.070", "Id": "463159", "Score": "0", "body": "@OliverSchonrock, I have heard that constants initialized from a literal count as constexpr too. Might need to search for a reference, but I am pretty certain on this one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T18:27:38.037", "Id": "463161", "Score": "0", "body": "@Incomputable I did search it. I didn't spend time finding a \"reference quality\" source, but everything I saw said `const int` makes a VLA. We don't want VLAs, I think." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T18:34:22.283", "Id": "463165", "Score": "0", "body": "@OliverSchonrock, https://godbolt.org/z/MGrEqK please recheck as I typed on the phone. The important bit is not const int, but that it is initialized from a literal. By the way I enabled erroring out if vla creation is detected by flag -error=vla" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T15:22:20.207", "Id": "463463", "Score": "0", "body": "@Incomputable Your link only had the assembly not the source code. Are you sure you are compiling as C and not as C++. The compiler tab in your godbolt link showed c++?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-01T11:22:45.103", "Id": "467140", "Score": "0", "body": "@OliverSchönrock, hi, I forgot about this thread. Here is the more complete version: https://godbolt.org/z/rcseVP Notice the -Werror=vla in the command line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T13:44:44.647", "Id": "467239", "Score": "0", "body": "@Incomputable Your godlbolt link was still set to C++ in the source code frame. ie it was compiling this as C++. We know this works with C++. To test you need to switch the source code window to \"C\" like this: https://godbolt.org/z/mn56Pu\n\nAnd we get the expected error: \"<source>:4:5: error: ISO C90 forbids array 'arr' whose size can't be evaluated [-Werror=vla]\n\n 4 | int arr[n] = {0};\"\n\nThese errors are the same for `-std=c99/c11/c18` . So, sorry, I remain unconvinced. that a `const int` can be used to initialise a non-vla array in C." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-03T08:58:21.953", "Id": "467307", "Score": "0", "body": "@OliverSchönrock, it seems like I lost the C part somewhere. Sorry for taking your time." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T17:46:11.520", "Id": "236243", "ParentId": "236212", "Score": "3" } }, { "body": "<p>Comment about your naming conventions. Statements such as <code>current = original</code> show that you conflate the array and the pointer view of things. Clearly <code>original</code> refers to a string, whereas <code>current</code> seems to be \"the current location in the string\". (I would be almost tempted to write <code>current = &amp;(original[0])</code> just to show what's happening.)</p>\n\n<p>However, the name <code>current</code> gives no indication of what type it is: a current <em>what?</em>. Also, the expression <code>*current</code> indicates that current is not \"current character\" but \"pointer to current character\".</p>\n\n<p>How about you use more descriptive names, such as \"pointer_into_original_string\"?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T18:14:32.427", "Id": "462872", "Score": "0", "body": "Hmm. quite \"Hungarian\" that suggestion?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T22:19:57.390", "Id": "462883", "Score": "0", "body": "I agree with your point that \"current\" is too short of a name and could be improved here, and think that \"pointer_into_original_string\" is a bit too long :). May be current_character would be better. Regarding current = &(original[0]) - imho it is superfluous, but may be it highlights the intention more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T12:32:42.450", "Id": "462947", "Score": "0", "body": "Because you don't want big names. If I tossed extremely descriptive variable names into my code I'd be well over 80 characters for each line and that makes it harder to read." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T17:50:04.457", "Id": "236244", "ParentId": "236212", "Score": "1" } } ]
{ "AcceptedAnswerId": "236220", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T02:13:18.340", "Id": "236212", "Score": "-2", "Tags": [ "c++", "c", "strings" ], "Title": "Find and replace a string in C/C++ without using standard library" }
236212
<p>Here is the Interface I am using in my working app. </p> <pre class="lang-php prettyprint-override"><code> &lt;?php declare(strict_types=1); namespace midorikocak\nano; use Exception; interface CrudInterface { /** * @param array $data Array data of an Item. * @return array Array data of an Item with id. * @throws Exception if the data does not pass validate */ public function create(array $data): array; /** * @param string $id * @return array Returns the array of New Item. * @throws Exception if something bad happens */ public function read($id): array; /** * @param string $id Can be an integer or a string * @param array $data Accepts Array data of an Item with or without id. * @return array Returns the array of Updated Item. * @throws Exception if something bad happens * @todo Is it ok to have id in array data? */ public function update(string $id, array $data): array; /** * @param string $id Can be an integer or a string * @return void Returns nothing. Simple Command Query separation. * @throws Exception if id not found or something bad happens * @todo Should create different exceptions for negative outcomes */ public function delete(string $id): void; /** * @return array[] Should return an array of arrays that contain Item Data. */ public function list(): array; /** * We have to validate data in every operation that receives item array. * @param array $data Accepts Array data of an Item with or without id. * @todo How can we be sure that this runs in every method that acceps item data? * @todo Maybe an abstract class? * * @return bool */ public function validateData(array $data): bool; } </code></pre> <p>I have some questions.</p> <ol> <li>In update method, is it ok to have id in array data?</li> <li>Should I create different exceptions for negative outcomes? Instead of returning false or null, when something is wrong, I prefer to throw exceptions.</li> <li>How can we be sure that In validateData method runs in every method that accepts item data? Maybe an abstract class?</li> <li>Are there any violations or can it be some better? </li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T07:20:26.813", "Id": "462909", "Score": "4", "body": "I see a bunch of function declarations here, but the actual code, the code that does the heavy lifting, is missing. There's not much to say about it in it's current state. Your numbered questions seem to indicate you're actually looking for a design review instead of a code review, and that's not what we do. Please take a look at the [help/on-topic]." } ]
[ { "body": "<p>Ad 1) it Is ok to pass id in the Array data of you want to change the id. If you were asking if you can omit the id argument. Then yes but you Will never be able to change id And honestly it becomes more verbose to use. And honestly it Is quite premature to expect this on this generic level.</p>\n\n<p>Ad 2) if \"wrong\" means empty id or database unreachable and similar, then yes, throw (or pass up) exceptions. But if it means object with given id not found then return null, it is not exceptional to ask for non-existent id, it just leads to a different result. But when database is unreachable, you are unable to say wheteher it exists or not and if it does what are its data and so here exception is appropriate.</p>\n\n<p>Although many will argue here that exceptions are better. I think that exceptions are there to halt program (and do cleanup and notify someone) when something went really bad, not to be used to control flow of your program.</p>\n\n<p>Ad 3) You have (at least) 2 options here:</p>\n\n<p>Dont make it part of the interface. Let implementations take care of this. Could be abstrakt but in generál i advise against abstract classes as they sooner or later start cousing troubles when an implementation wants something done slightly differently And nobody thought about it when the abstract class was designed.</p>\n\n<p>Or,</p>\n\n<p>if it is / has to be part of the interface than it might better return error messages/codes instead of just bool. And the caller should be responsible for calling it first, if He does not call IT than the interface Is being used incorrectly And anything can happen, but that would be a dev's Mistake.</p>\n\n<p>To provide an analogy, it would be like calling Iterator::current() before making sure Iterator::valid() returned true -> undefined behaviour, anything can happen, exception thrown, or nothing, or random element returned, or anything else - simply whatever was the most convenient for that implementation, anyway it is not important because at that point the interface is being misused and the code calling it is wrong and need to be fixed.</p>\n\n<p>Calling it from inside the other method (valid from current, or validateData from create/update) just to make sure that the first method returns true and throw exception otherwise is also wrong because it will get called twice (redundantly) for whoever used the interface correctly. </p>\n\n<p>Although many (especialy PHP) devs may argue that it is better to always throw exception to make sure the dev notices this as soon as possible. I personaly think that you should just write it into the interface's doc comments to state very explicitly that calling create/update without validating the data first is undefined behaviour. How many consumer classes will there be for CrudInterface anyway? One? Two? You make sure that these are correct and then everyone is going to use them, right? So...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T11:58:21.543", "Id": "236225", "ParentId": "236219", "Score": "2" } } ]
{ "AcceptedAnswerId": "236225", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T08:32:37.970", "Id": "236219", "Score": "0", "Tags": [ "php", "object-oriented" ], "Title": "The CRUD interface I created for my new app. Creates, updates, deletes, reads and lists" }
236219
<p>I'm writing toy parsers for toy languages to understand how parsers work.</p> <p>Assuming a language as follows (in sketchy EBNF patois)</p> <pre><code>expression := lparen [datum] [expression [datum]] rparen datum := any string of characters other than ( or ) rparen := ( lparen := ) </code></pre> <p>These are some valid expressions</p> <pre><code>(hello(one(two(three)a)b)c) (()abc) ((())) </code></pre> <p>whereas the following strings are illegal</p> <pre><code>)( abc ((abc) ((abc)( ((abc)(abc)) </code></pre> <p>So, these are strings consisting of balanced parentheses, with alphanumeric strings possible between both open and closed parentheses. The data can be arbitrarily nested, but not repeating (so each pair of parentheses contains at most one pair of parentheses at its toplevel -- see the last example in the block above). </p> <p>I wrote a Python implementation of a parser for this language as follows:</p> <pre><code>import inspect class Parser: def __init__(self, expression, verbose=True): self.expression = expression self.position = 0 self.tokens = [] self.paren_state = 0 self.verbose = verbose def peek(self): if self.position + 1 == len(self.expression): return "EOF" else: return self.expression[self.position + 1] def advance(self): self.pretty_print_stack() if (self.position + 1) &gt;= len(self.expression): return self.tokens else: self.position += 1 def current(self): return self.expression[self.position] def parse_paren(self): self.pretty_print_stack() if self.current() == "(": self.parse_lparen() elif self.current() == ")": self.parse_rparen() else: raise Exception(f"Expected parentheses at {self.position}") def parse_lparen(self): self.pretty_print_stack() if self.current() == "(": self.paren_state += 1 self.advance() else: raise Exception(f"Expected left parentheses at position {self.position}") def parse_rparen(self): self.pretty_print_stack() if self.current() == ")": self.paren_state -= 1 if self.paren_state &lt; 0: raise Exception(f"Imbalanced parentheses") else: self.advance() else: raise Exception(f"Expected right parentheses at position {self.position}") def is_paren(self): return self.current() in ["(", ")"] def parse_datum(self): self.pretty_print_stack() buffer = "" while not self.is_paren(): self.pretty_print_stack() buffer += self.current() self.advance() if buffer: self.tokens.append(buffer) def parse_expression(self): self.pretty_print_stack() if self.peek() != "EOF": self.parse_paren() self.parse_datum() self.parse_expression() else: if self.paren_state &gt; 1 or self.current() != ")": raise Exception("Imbalanced parentheses") return self.tokens def pretty_print_stack(self): if self.verbose: pretty_printed = "" for idx, char in enumerate(self.expression): if idx == self.position: pretty_printed += f"&gt;{char}&lt;" else: pretty_printed += char current_frame = inspect.currentframe() caller_frame = inspect.getouterframes(current_frame, 2) print(f"{pretty_printed:&lt;20} Position {self.position}, in {caller_frame[1][3]}, paren_state: {self.paren_state} peek: {self.peek()}") </code></pre> <p>This has the expected behavior, which is to bomb on imbalanced parentheses, and build up a list of "tokens" (actually "datums", which are the substrings between the parentheses). </p> <p>I feel it has some issues</p> <ol> <li><p>The way I detect imbalanced parentheses (adding 1 to <code>paren_state</code> everytime an <code>lparen</code> is encountered and subtracting 1 if an <code>rparen</code> is encountered, then making sure the value of <code>paren_state</code> is always non-negative) feels like a hack. Is there a better way to do this?</p></li> <li><p>The code in <code>Parser.parse_expression</code> doesn't "read" like the grammar as recursive descent parsers are supposed to, and overall the implementation feels clumsy </p></li> <li><p>Related to the grammar, I have a vague sense that it would help if I could refactor the grammatical definition of <code>expression</code> so that it isn't recursive, but I'm not sure how to do this (or if it is even possible) since the language has a recursive structure</p></li> </ol> <p>Happy and grateful for any thoughts and feedback on this. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T07:57:11.450", "Id": "463076", "Score": "1", "body": "With #3, I actually feel that a recursive parser is quite an elegant solution to this sort of issue, and that especially for if you wanted to add more in the future, having expression recursive is more useful and easier to read than making it iterative" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T22:43:58.087", "Id": "463570", "Score": "1", "body": "Balanced / Imbalanced already been analyzed as unusual or imposible to check with a syntax grammar, and other developers also do \"hacks\"" } ]
[ { "body": "<p><sub><i>Assuming you used python-3.x.</i></sub></p>\n\n<hr>\n\n<h1><code>Parser.peek</code></h1>\n\n<p>This method can be simplified:</p>\n\n<pre><code>def peek(self):\n if self.position + 1 == len(self.expression):\n return \"EOF\"\n return self.expression[self.position + 1]\n</code></pre>\n\n<p>The <code>else</code> is necessary, since the method will finish if the condition is satisfied.</p>\n\n<hr>\n\n<h1><code>Parser.advance</code></h1>\n\n<p>This method can be improved, with the same reasons defined above:</p>\n\n<pre><code>def advance(self):\n self.pretty_print_stack()\n if (self.position + 1) &gt;= len(self.expression):\n return self.tokens\n self.position += 1\n</code></pre>\n\n<hr>\n\n<h1><code>Parser.parse_rparen</code></h1>\n\n<p>This function can be improved:</p>\n\n<pre><code>def parse_rparen(self):\n self.pretty_print_stack()\n if self.current() == \")\":\n self.paren_state -= 1\n if self.paren_state &lt; 0:\n raise Exception(f\"Imbalanced parentheses\")\n self.advance()\n else:\n raise Exception(f\"Expected right parentheses at position {self.position}\")\n</code></pre>\n\n<p>Raising an <code>Exception</code> will stop the program (<a href=\"https://stackoverflow.com/questions/438894/how-do-i-stop-a-program-when-an-exception-is-raised-in-python\">if you don't catch it</a>), so an <code>else</code> here is unnecessary.</p>\n\n<hr>\n\n<h1><code>Parser.is_paren</code></h1>\n\n<p>This function can be simplified:</p>\n\n<pre><code>def is_paren(self):\n return self.current() in \"()\"\n</code></pre>\n\n<p>This is the same as you had before, but more pythonic.</p>\n\n<hr>\n\n<h1><code>Parser.pretty_print_stack</code></h1>\n\n<p>This function can be simplified:</p>\n\n<pre><code>def pretty_print_stack(self):\n if self.verbose:\n pretty_printed = \"\".join([\n f\"&gt;{char}&lt;\" if idx == self.position else char for idx, char in enumerate(self.expression)\n ])\n current_frame = inspect.currentframe()\n caller_frame = inspect.getouterframes(current_frame, 2)\n print(f\"{pretty_printed:&lt;20} Position {self.position}, in {caller_frame[1][3]}, paren_state: {self.paren_state} peek: {self.peek()}\")\n</code></pre>\n\n<p>Utilizing <a href=\"https://www.geeksforgeeks.org/join-function-python/\" rel=\"nofollow noreferrer\"><code>.join()</code></a> and <a href=\"https://www.geeksforgeeks.org/generator-expressions/\" rel=\"nofollow noreferrer\">generator expressions</a>, you can reduce the amount of clutter code in this function.</p>\n\n<hr>\n\n<h1>Other Suggestions</h1>\n\n<ul>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">Documentation Strings</a></li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">Type Hints</a></li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"nofollow noreferrer\">Method Naming</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T12:50:14.917", "Id": "462820", "Score": "0", "body": "Thanks, really appreciate these. I was hoping for something more focused on the business logic of the parser implementation (ie speaking specifically to points #1, #2 and #3 in my post)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T18:05:48.877", "Id": "463010", "Score": "3", "body": "The first half of your answer is just \"don't use `else`\". Which comes down to style, and doesn't need a ridiculous amount of examples." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T12:44:13.303", "Id": "236228", "ParentId": "236222", "Score": "-1" } }, { "body": "<p>A potential solution to points #1 and #2 is to rework some of the recursive logic of the code. The basic premise is to rework the expression so it is more like:</p>\n\n<p><code>expression := [datum] [lparen expression rparen]</code></p>\n\n<p>This allows it to handle brackets by recursively calling itself until they are gone without using a bracket counter. I won't code the solution for you, I will leave that to you but I will run you through the basic logic. It firstly has to check if the next character is a lparen or not. If it is not an lparen then it runs parse_datum. If it is an lparen then it runs advance and then runs parse_expression. Once that parse_expression finishes running, it can check if there is an rparen, if there is then it can continue, otherwise it will raise an error, as they are unmatched parentheses.</p>\n\n<p>The only other thing is that your language needs the outer item to be in parentheses but that can be implemented simply by a check for an lparen before passing it to the parse_expression method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T19:56:30.733", "Id": "236312", "ParentId": "236222", "Score": "3" } }, { "body": "<p>Here's a suggestion:</p>\n\n<p>For question #1 and #2, <code>parse_expression</code> is written in a way that matches the grammar, which also ensures the parens are balanced. If a '(' is matched, then the optional internal parts of an expression are parsed and then the ')'.</p>\n\n<p>There is a separate top level function call, <code>parse()</code>, that takes the expression to parse and makes sure it starts with a '(' before calling <code>parse_expression</code>. This helps with questions #1 and #3.</p>\n\n<p>I left out <code>pretty_print_stack()</code> for brevity.</p>\n\n<pre><code>class ParseError(Exception):\n def __init__(self, message=''):\n self.message = f\"ParseError: {message}\"\n\n\n\nclass Parser:\n def __init__(self, verbose=1):\n self.verbose = verbose\n\n\n def advance(self):\n if self.position &lt; len(self.expression):\n self.position += 1\n\n if self.position &lt; len(self.expression):\n self.current = self.expression[self.position]\n else:\n self.current = \"EOF\"\n\n\n def parse(self, expression):\n \"\"\"\n Takes expression to parse and returns a parse tree in the form of a\n nested list. E.g., (a((b)c)) -&gt; ['a', ['', ['b', None, ''], 'c'], ''].\n\n At this level, an expression is required, so make sure the '(' is there.\n Then call self.expression(); otherwise, it's a syntax error.\n \"\"\"\n\n self.expression = expression\n self.position = 0\n self.current = self.expression[:1]\n\n if self.current != '(':\n raise ParseError(f\"Missing '(' at position {self.position}.\")\n\n return self.parse_expression()\n\n\n def parse_datum(self):\n \"\"\"\n datum := any string of characters other than ( or ) or EOF.\n\n returns string of chars or empty string\n \"\"\"\n\n start = self.position\n\n while self.current not in ('(',')','EOF'):\n self.advance()\n\n return self.expression[start:self.position]\n\n\n def parse_expression(self):\n \"\"\"expression := '(' [datum] [expression [datum]] ')'\n\n returns list of elements, or None if it doesn't parse\n \"\"\"\n\n if self.current == '(':\n self.advance()\n\n datum1 = self.parse_datum()\n\n expression = self.parse_expression()\n\n datum2 = self.parse_datum() if expression else ''\n\n if self.current != ')':\n raise ParseError(f\"Missing ')' at position {self.position}.\")\n\n self.advance()\n return [ datum1, expression, datum2 ]\n\n else:\n return None\n</code></pre>\n\n<p>And the test cases:</p>\n\n<pre><code>tests = {\n 'good':[line.strip() for line in \"\"\"\n (hello(one(two(three)a)b)c)\n (()abc)\n ((()))\n \"\"\".strip().splitlines()],\n 'bad':[line.strip() for line in \"\"\"\n )(\n abc\n ((abc)\n ((abc)(\n ((abc)(abc))\n \"\"\".strip().splitlines()]\n}\n\np = Parser(verbose=True)\n\nfor kind, testset in tests.items():\n print(f\"{kind} tests\")\n\n for n,test in enumerate(testset):\n print(f\"\\n Test {n}: {test}\\n\")\n try:\n tree = p.parse(test)\n print(f\" {tree}\\n\")\n\n except ParseError as e:\n print(f\" {e.message}\")\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>good tests\n\n Test 0: (hello(one(two(three)a)b)c)\n\n ['hello', ['one', ['two', ['three', None, ''], 'a'], 'b'], 'c']\n\n\n Test 1: (()abc)\n\n ['', ['', None, ''], 'abc']\n\n\n Test 2: ((()))\n\n ['', ['', ['', None, ''], ''], '']\n\nbad tests\n\n Test 0: )(\n\n ParseError: Missing '(' at position 0.\n\n Test 1: abc\n\n ParseError: Missing '(' at position 0.\n\n Test 2: ((abc)\n\n ParseError: Missing ')' at position 6.\n\n Test 3: ((abc)(\n\n ParseError: Missing ')' at position 6.\n\n Test 4: ((abc)(abc))\n\n ParseError: Missing ')' at position 6.\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T08:06:08.290", "Id": "236401", "ParentId": "236222", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T11:28:46.117", "Id": "236222", "Score": "10", "Tags": [ "python", "parsing", "grammar" ], "Title": "Recursive Descent Parser Implementation for a Recursive Language" }
236222
<p>I posted a question here <a href="https://codereview.stackexchange.com/questions/236052/ffmpeg-batch-script-for-video-resizing">ffmpeg batch script for video resizing</a> but I forgot the issue of the rotation and the video files were scaled with wrong dimensions.</p> <p>Below is the improved version of the script</p> <pre><code>#!/bin/bash set -eu status=true fail() { echo "$@" &gt;&amp;2 status=false } # Resize a single file resize() { exiftool -p 'Filename:$filename Megapixel:$megapixels Dimension:$imagesize Rotation:$rotation' $1 if exiftool -if '$imageheight == 1920 &amp;&amp; $imageheight == 1080' $1 &gt; /dev/null then fail "-&gt; No need to convert" return fi filename="$(date +%s)".mp4 rotation=$(exiftool -p '$rotation' $1) if [ "${rotation}" -eq 0 ] || [ "${rotation}" -eq 180 ] then scaling="-1:720" elif [ "${rotation}" -eq 90 ] || [ "${rotation}" -eq 270 ] then scaling="720:-1" else fail "-&gt; Unhandled rotation" return fi if ffmpeg -v error -stats -i "$1" -map_metadata 0 \ -vf scale="$scaling" -c:v libx264 -crf 23 \ -c:a copy "$filename" &lt; /dev/null &amp;&amp; exiftool -TagsFromFile "$1" '-all:all&gt;all:all' \ -overwrite_original "$filename" then # success rename 's/.mp4/.success.mp4/' $1 mv "$filename" $1 true else rename 's/.mp4/.error.mp4/' $1 # failed; destroy the evidence rm -f "$filename" 2&gt;/dev/null fail "-&gt; Failed to convert" fi } [ $# -gt 0 ] || fail "Usage: $0 FILE FILE..." for arg do if [ -f "$arg" ] then resize "$arg" echo elif [ -e "$arg" ] then fail "$arg: not a plain file or directory" else fail "$arg: file not found" fi done exec $status # true or false </code></pre>
[]
[ { "body": "<p>Is it intended that <code>date</code> is executed separately for each input, or should all converted files have consistent names (for that use of the script)? It's certainly worth a comment explaining your choice.</p>\n\n<p>I'm not a fan of the big space in the redirection <code>&gt; /dev/null</code> - that makes it harder to parse.</p>\n\n<p>This <code>if</code>/<code>else</code> chain looks a little clumsy:</p>\n\n<blockquote>\n<pre><code>if [ \"${rotation}\" -eq 0 ] || [ \"${rotation}\" -eq 180 ]\nthen\n scaling=\"-1:720\"\nelif [ \"${rotation}\" -eq 90 ] || [ \"${rotation}\" -eq 270 ]\nthen\n scaling=\"720:-1\"\nelse\n fail \"-&gt; Unhandled rotation\"\n return\nfi\n</code></pre>\n</blockquote>\n\n<p>When testing a single value against various possibilities, it tends to be neater using <code>case</code>:</p>\n\n<pre><code>case \"$rotation\" in\n 0|180) scaling=\"-1:720\" ;;\n 90|270) scaling=\"720:-1\" ;;\n *) fail \"-&gt; Unhandled rotation '$rotation'\"; return ;;\nesac\n</code></pre>\n\n<p>(I also added extra information in the failure case, that may help diagnose problem input files).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T17:02:16.457", "Id": "236303", "ParentId": "236224", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T11:50:04.060", "Id": "236224", "Score": "3", "Tags": [ "bash" ], "Title": "ffmpeg batch script for video resizing - improved" }
236224
<p>I am a beginner so please keep it in mind while answering! <strong>For player vs CPU is there any more effective way to make CPU better ??</strong></p> <pre><code>import numpy as np board=['-','-','-', '-','-','-', '-','-','-'] def check_win(): global winner global game_over if board[0]=='X' and board[1]=='X' and board[2]=='X': winner='Player' game_over=True elif board[3]=='X' and board[4]=='X' and board[5]=='X': winner='Player' game_over=True elif board[6]=='X' and board[7]=='X' and board[8]=='X': winner='Player' game_over=True elif board[0]=='X' and board[4]=='X' and board[8]=='X': winner='Player' game_over=True elif board[2]=='X' and board[4]=='X' and board[6]=='X': winner='Player' game_over=True elif board[0]=='X' and board[3]=='X' and board[6]=='X': winner='Player' game_over=True elif board[1]=='X' and board[4]=='X' and board[7]=='X': winner='Player' game_over=True elif board[2]=='X' and board[5]=='X' and board[8]=='X': winner='Player' game_over=True elif board[0]=='O' and board[1]=='O' and board[2]=='O': winner='CPU' game_over=True elif board[3]=='O' and board[4]=='O' and board[5]=='O': winner='CPU' game_over=True elif board[6]=='O' and board[7]=='O' and board[8]=='O': winner='CPU' game_over=True elif board[0]=='O' and board[4]=='O' and board[8]=='O': winner='CPU' game_over=True elif board[2]=='O' and board[4]=='O' and board[6]=='O': winner='CPU' game_over=True elif board[0]=='O' and board[3]=='O' and board[6]=='O': winner='CPU' game_over=True elif board[2]=='O' and board[5]=='O' and board[8]=='O': winner='CPU' game_over=True def res_gm(): board=['-','-','-', '-','-','-', '-','-','-'] play_game() def player_turn(): a=int(input("Enter the position to pux X (1-9) : ")) valid=False while valid==False: if a&lt;=9 and board[a-1]=='-': board[a-1]='X' valid=True elif a=='': print("You Cannot Leave This Empty") else: print("This move is invalid ! ") a=int(input("Enter the position to pux X (1-9) : ")) def Compute(): if board[0]=='O' and board[1]=='O' and board[2]=='-': board[2]='O' main_board() elif board[0]=='O' and board[2]=='O' and board[1]=='-': board[1]='O' main_board() elif board[1]=='O' and board[2]=='O' and board[0]=='-': board[0]='O' main_board() elif board[3]=='O' and board[4]=='O' and board[5]=='-': board[5]='O' main_board() elif board[3]=='O' and board[5]=='O' and board[4]=='-': board[4]='O' main_board() elif board[4]=='O' and board[5]=='O' and board[3]=='-': board[3]='O' main_board() elif board[6]=='O' and board[7]=='O' and board[8]=='-': board[8]='O' main_board() elif board[7]=='O' and board[8]=='O' and board[6]=='-': board[6]='O' main_board() elif board[6]=='O' and board[8]=='O' and board[7]=='-': board[7]='O' main_board() elif board[0]=='O' and board[4]=='O' and board[8]=='-': board[8]='O' main_board() elif board[4]=='O' and board[8]=='O' and board[0]=='-': board[0]='O' main_board() elif board[0]=='O' and board[8]=='O' and board[4]=='-': board[4]='O' main_board() elif board[0]=='X' and board[1]=='X' and board[2]=='-': board[2]='O' main_board() elif board[0]=='X' and board[2]=='X' and board[1]=='-': board[1]='O' main_board() elif board[1]=='X' and board[2]=='X' and board[0]=='-': board[0]='O' main_board() elif board[3]=='X' and board[4]=='X' and board[5]=='-': board[5]='O' main_board() elif board[3]=='X' and board[5]=='X' and board[4]=='-': board[4]='O' main_board() elif board[4]=='X' and board[5]=='X' and board[3]=='-': board[3]='O' main_board() elif board[6]=='X' and board[7]=='X' and board[8]=='-': board[8]='O' main_board() elif board[7]=='X' and board[8]=='X' and board[6]=='-': board[6]='O' main_board() elif board[6]=='X' and board[8]=='X' and board[7]=='-': board[7]='O' main_board() elif board[0]=='X' and board[4]=='X' and board[8]=='-': board[8]='O' main_board() elif board[4]=='X' and board[8]=='X' and board[0]=='-': board[0]='O' main_board() elif board[0]=='X' and board[8]=='X' and board[4]=='-': board[4]='O' main_board() elif board[0]=='X' and board[3]=='X' and board[6]=='-': board[6]='O' main_board() elif board[2]=='X' and board[5]=='X' and board[8]=='-': board[8]='O' main_board() elif board[1]=='X' and board[4]=='X' and board[7]=='-': board[7]='O' main_board() else: valid=False while valid==False: b=np.random.randint(0,9) if board[b]=='-': board[b]='O' main_board() valid=True else: valid=False def main_board(): print(board[0]+'|'+board[1]+'|'+board[2]+' For reference 1|2|3') print(board[3]+'|'+board[4]+'|'+board[5]+' 4|5|6') print(board[6]+'|'+board[7]+'|'+board[8]+' 7|8|9') def play_game(): global game_over global winner main_board() game_over=False n=0 while game_over==False: if n&lt;9 and n%2==0: player_turn() n+=1 check_win() elif n&lt;9 and n%2!=0: Compute() check_win() n=n+1 elif n==9 and board[0]!='-' and board[1]!='-' and board[2]!='-' and board[3]!='-'and board[4]!='-' and board[5]!='-' and board[6]!='-' and board[7]!='-' and board[8]!='-' and game_over==False: print('Tie') winner='None' game_over=True print('The winner is ',winner) print('Choose a game mode : \n1. Player Vs CPU \n2. Player1 vs Player2') q=int(input('Enter the Corresponding number of game mode : ')) while q in [1,2,3]: if q==1: p='y' while p=='y': play_game() p=str(input('Want to play again ? ')) else: print('Exiting Game!') q=3 elif q==2: print('this game mode is not available yet, ask Utkarsh to develop it ') q=int(input('Enter the Corresponding number of game mode : ')) else: quit() else: print('There is no game mode like this ') q=int(input('Enter the Corresponding number of game mode : ')) </code></pre>
[]
[ { "body": "<p>You need to fix indentation for the program to run (the fix is easy though, just look at the elif branches on line 102 onwards).</p>\n\n<p>What you've essentially done is an explicit if-else structure where you've hardcoded all possible positions. While this works, it's quite difficult to read and it's easy to make mistakes. Thus, it would be a good idea to use a data structure not only for the board, but for the wins (rows, diagonals, columns) as well:</p>\n\n<pre><code>player_symbol = 'X'\ncpu_symbol = 'O'\n\nboard=np.array(['-','-','-',\n '-','-','-',\n '-','-','-'])\n\nwins = [\n [0,1,2], [3,4,5], [6,7,8], # rows\n [0,4,8], [2,4,6], # diagonals\n [0,3,6], [1,4,7], [2,5,8], # columns\n ]\n</code></pre>\n\n<p>Now, to check for a win we can do something much simpler like:</p>\n\n<pre><code>def check_win():\n player_win = any(len(set(board[pos])) == 1 and player_symbol in board[pos] for pos in wins)\n cpu_win = any(len(set(board[pos])) == 1 and cpu_symbol in board[pos] for pos in wins)\n\n game_over = player_win or cpu_win\n winner = None\n if game_over:\n winner = 'Player' if player_win else 'CPU'\n\n return game_over, winner\n</code></pre>\n\n<p>In here, note that we can simply return values and we don't need global variables which are always difficult to reason about. Further, the \"win checks\" a reduced to simple generator expression: it goes over each element of <code>wins</code>, grabs the corresponding row, column or diagonal from <code>board</code>, checks to see if it has all of the same symbols (i.e., if the <code>set</code> taken over the elements of <code>board</code> has size 1) <em>and</em> checks if the unique symbol it contains is the <code>player_symbol</code> or <code>cpu_symbol</code>.</p>\n\n<ul>\n<li><p>For <code>Compute()</code>, the function could use a better name: it starts with an uppercase letter while all the other functions don't. Also, <code>compute()</code> is a very generic name and it doesn't explain what the function is supposed to move. So perhaps a better name would be e.g., <code>compute_cpu_move()</code>. </p></li>\n<li><p>Now, using the same logic we <em>could</em> beautify <code>Compute()</code> as well but this is not necessarily a great idea. If you are interested in more challenge, you could make the CPU <em>perfect</em> by <a href=\"https://en.wikipedia.org/wiki/Tic-tac-toe#Strategy\" rel=\"nofollow noreferrer\">playing with the optimal strategy</a> or implementing the <a href=\"https://en.wikipedia.org/wiki/Minimax\" rel=\"nofollow noreferrer\">minimax algorithm</a>. </p></li>\n</ul>\n\n<p>There's definitely more we could say here as well, but I hope this is enough to get you going. There are tons of questions and resources on tic-tac-toe on this site and elsewhere online that you can get more inspiration from.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T14:11:55.133", "Id": "236234", "ParentId": "236229", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T13:07:12.413", "Id": "236229", "Score": "0", "Tags": [ "python", "python-3.x", "tic-tac-toe" ], "Title": "Tic-Tac-Toe game suggestion" }
236229
<p>I've recently completed a vanilla JS challenge . It is a method for calculating and ranking scores. If possible, I would love to make it better. Any suggestions are welcome.</p> <p>Challenge Directions: The input array contains a series of objects that hold user scores. Scores are ranked both individually (within the object) as well as against the other score objects to find overall ranking.</p> <p>MY CODE:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>//STEP 1 - CALCULATE TOTAL SCORE &amp; SCORE RANKS FOR EACH OBJECT function calculateResults(input) { return input.map((scoreSeries) =&gt; { let final_rank = 0; calculatedScoreSeries = {...scoreSeries} Object.keys(scoreSeries).forEach((key) =&gt; { if (key !== 'category') { final_rank = final_rank + scoreSeries[key] //Adding up the score. calculatedScoreSeries[key] = calculateSourceRank(scoreSeries, key) //calculating the rank }}) calculatedScoreSeries.final_rank = final_rank //adding total_score prop to the new object return calculatedScoreSeries }) } //to calculate the ranking of each source function calculateSourceRank(scoreSeries, key) { let rank = 1; for (let i = 1; i &lt; Object.keys(scoreSeries).length; i++) { if (scoreSeries[Object.keys(scoreSeries)[i]] &gt; scoreSeries[key]) { rank++ } } return rank } //STEP 2 - COMPARE OBJECTS FOR FINAL RANK function calculateFinalRank(calculatedResults) { return calculatedResults.map((calculatedScoreSeries) =&gt; { let rankedScoreSeries = {...calculatedScoreSeries} let rank = 1; for (let i = 0; i &lt; calculatedResults.length; i++) { if (calculatedResults[i].final_rank &gt; calculatedScoreSeries.final_rank) { rank++ } rankedScoreSeries.final_rank = rank } return rankedScoreSeries }) } let output = calculateFinalRank(calculateResults(input)) console.log(output)</code></pre> </div> </div> </p> <p>TEST INPUTS W EXPECTED OUTPUTS:</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>//each object's score sources are ranked (if two are equal they share the higher ranking). //then all objects are compared for the overall rnking (if two are equal they share the higher ranking) input = [ // test input 1 { "category":"test3", "source1":50, "source2":100, "source3":30, "source4":10, "source5":10, }, { "category":"test4", "source1":100, "source2":30, "source3":10, "source4":10, "source5":50, }, { "category":"test5", "source1":5, "source2":10, "source3":10, "source4":40, "source5":5, }, ] output = [ { "category":"test3", "source1":2 "source2":1 "source3":3 "source4":4 "source5":4 "final_rank":1 }, { "category":"test4", "source1":1 "source2":3 "source3":4 "source4":4 "source5":2 "final_rank":1 }, { "category":"test5", "source1":4, "source2":2, "source3":2, "source4":1, "source5":4, "final_rank":3 }, ] input = [ // test input 2 { "category":"cat1", "src1":20, "src2":30, "src3":40, "src4":50, "src5":50 }, { "category":"cat1", "src1":10, "src2":0, "src3":20, "src4":20, "src5":100 }, ] output = [ { "category":"cat1", "src1":5, "src2":4, "src3":3, "src4":1, "src5":1, "final_rank":1 }, { "category":"cat1", "src1":4, "src2":5, "src3":2, "src4":2, "src5":1, "final_rank":2 }, ] </code></pre> </div> </div> </p> <p>BUSINESS LOGIC:</p> <p>1 - Category will always have at least one 'category'. More than 1 catgeory will be saved as an array under the category key. Category will always be the first key.</p> <p>2 - each object in the input array will have an equal number of sources (although this number can be any amount)</p> <p>3 - if a total score is equal to anothers, then they will share the higher ranking (same as individual score ranking)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T15:11:05.650", "Id": "462842", "Score": "1", "body": "If this is a programming challenge from an online site it would be nice if the text of the challenge as well as a link to the challenge was posted as part of the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T16:51:13.007", "Id": "462863", "Score": "0", "body": "@pacmaninbw this is all the info, not an online one I can link to, unfortunately. The idea was to look at the input data and determine what is happening yourself, and then build business logic based on your findings (which I've outlined for my particular case)." } ]
[ { "body": "<h2>Good things</h2>\n\n<p>I like the functional approach taken with this code, and that some <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged &#39;ecmascript-6&#39;\" rel=\"tag\">ecmascript-6</a> features like arrow functions are used.</p>\n\n<h2>Suggestions</h2>\n\n<h3><code>const</code> vs <code>let</code></h3>\n\n<p>It would be wise to default to using <code>const</code> for any variable that doesn't need to be re-assigned. If you later determine a value should be re-assigned then switch it to using <code>let</code>. This helps prevent accidental re-assignment in the future.</p>\n\n<h3>Use consistent indentation</h3>\n\n<p>Some lines appear to be indented with two spaces, while others are indented with four. It is wise to use uniform indentation throughout the code.</p>\n\n<h3>Use consistent line terminators</h3>\n\n<p>Many lines are terminated with a semi-colon but some are not. Unless you completely understand rules of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion\" rel=\"nofollow noreferrer\">Automatic semicolon insertion</a> or are using a compiler/module bundler it is best to include line terminators. </p>\n\n<h3>multiple calls to <code>Object.keys()</code> in loop</h3>\n\n<p>Let us take a look at the following block:</p>\n\n<blockquote>\n<pre><code>for (let i = 1; i &lt; Object.keys(scoreSeries).length; i++) {\n if (scoreSeries[Object.keys(scoreSeries)[i]] &gt; scoreSeries[key]) {\n rank++\n }\n} \n</code></pre>\n</blockquote>\n\n<p>For each iteration of the loop, <code>Object.keys()</code> is called twice. That function could be called once if the result is stored in a variable. </p>\n\n<pre><code>const scoreKeys = Object.keys(scoreSeries)\nfor (let i = 1; i &lt; scoreKeys.length; i++) {\n if (scoreSeries[scoreKeys[i]] &gt; scoreSeries[key]) {\n rank++\n }\n} \n</code></pre>\n\n<p>The syntax could be simplified using 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>:</p>\n\n<pre><code>const scoreKeys = Object.keys(scoreSeries)\nfor (const scoreKey of scoreKeys) {\n if (scoreSeries[scoreKey] &gt; scoreSeries[key]) {\n rank++\n }\n} \n</code></pre>\n\n<p>The whole function could be simplified with a more function approach using <code>.filter()</code>:</p>\n\n<pre><code>//to calculate the ranking of each source\nfunction calculateSourceRank(scoreSeries, key) {\n const scoreKeys = Object.keys(scoreSeries)\n return 1 + scoreKeys.filter(scoreKey =&gt; scoreSeries[scoreKey] &gt; scoreSeries[key]).length\n}\n</code></pre>\n\n<p>A similar approach could be applied to <code>calculateFinalRank()</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T21:49:31.303", "Id": "236315", "ParentId": "236232", "Score": "3" } } ]
{ "AcceptedAnswerId": "236315", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T13:48:05.773", "Id": "236232", "Score": "5", "Tags": [ "javascript", "functional-programming", "json", "ecmascript-6" ], "Title": "Program for calculating and ranking scores" }
236232
<p>First I have two conditions on the number of list elements,then in one of these conditions I have two others conditons to treat it :</p> <p>My code:</p> <pre><code>List&lt;StringBuilder&gt; result = ReadResult_WS_Import(NameFile); if ((result != null) &amp;&amp; (result.Any())) { var is_No_Errors_Found_Exist = result[0].ToString().Contains(Properties.Resources.ARGS_RESULT_Is_No_Errors_Found_Exist); var is_Import_Failed_Exist = result[0].ToString().Contains(Properties.Resources.ARGS_RESULT_Is_Import_Failed_Exist); var is_The_Import_Has_Failed_Exist = result[0].ToString().Contains(Properties.Resources.ARGS_RESULT_Is_The_Import_has_Failed_Exist); string[] result_LOG = result[0].ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); if ((result.Count == 2) &amp;&amp; (!is_The_Import_Has_Failed_Exist)) { result_REJECT = result[1].ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); StatusResult = Properties.Resources.ARGS_RESULT_OK_REJECT; } else if (is_No_Errors_Found_Exist) { StatusResult = Properties.Resources.ARGS_RESULT_OK; } else if (is_Import_Failed_Exist) { StatusResult = Properties.Resources.ARGS_RESULT_KO; } if ((is_The_Import_Has_Failed_Exist) &amp;&amp; (result.Count == 2)) { result_REJECT = result[1].ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); StatusResult = Properties.Resources.ARGS_RESULT_KO_REJECT; } returnObject = new ReturnObject { CountLines = CountLines, Status = StatusResult, LOG = result_LOG, REJECT = result_REJECT }; } </code></pre> <p>It works well, I don't have any problems, but I want to know if there is other code organization ? or any feedback ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T20:49:28.260", "Id": "462881", "Score": "0", "body": "What's the purpose of your code? You completely forgot to describe that in natural language. Plus, your code doesn't compile because most names cannot be resolved. This makes the question off-topic here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T10:03:18.490", "Id": "463089", "Score": "0", "body": "Is the current formatting your code's actual formatting, or a result of copying it into your browser?" } ]
[ { "body": "<h2>Naming and underscores</h2>\n\n<p>Underscores help to separate long sentences. But variable names should not be long sentences. You should drop the underscores, stick with camelCasing (as per convention), and shorten the names.</p>\n\n<pre><code>bool errorsFound;\nbool importFailed;\n</code></pre>\n\n<p>The underscores in your constants are not as much of an issue. I have generally moved away from the SCREAMCASING for constants and instead just PascalCase them (without underscores); but that's not a globally agreed upon standard.</p>\n\n<p>As an aside, unit and integration test methods often do have long sentences for names, and underscores are actually useful there. So you're definitely allowed to use underscores <strong>where appropriate</strong>. Local variables with long names are hardly ever appropriate.</p>\n\n<hr>\n\n<h2>Simplifying the logic</h2>\n\n<pre><code>if ((result.Count == 2) &amp;&amp; (!is_The_Import_Has_Failed_Exist))\n{\n result_REJECT = result[1].ToString().Split(new string[] { \"\\r\\n\" }, StringSplitOptions.RemoveEmptyEntries);\n StatusResult = Properties.Resources.ARGS_RESULT_OK_REJECT;\n} \n\nif ((is_The_Import_Has_Failed_Exist) &amp;&amp; (result.Count == 2))\n{\n result_REJECT = result[1].ToString().Split(new string[] { \"\\r\\n\" }, StringSplitOptions.RemoveEmptyEntries);\n StatusResult = Properties.Resources.ARGS_RESULT_KO_REJECT;\n} \n</code></pre>\n\n<p>These two evaluations share some commonalities, and their bodies are identical (assuming OK/KO is a typo). This can be merged into a single evaluation:</p>\n\n<pre><code>if(result.Count() == 2 &amp;&amp; (!is_The_Import_Has_Failed_Exist || is_The_Import_Has_Failed_Exist) )\n{ \n result_REJECT = result[1].ToString().Split(new string[] { \"\\r\\n\" }, StringSplitOptions.RemoveEmptyEntries);\n StatusResult = Properties.Resources.ARGS_RESULT_OK_REJECT;\n}\n</code></pre>\n\n<hr>\n\n<h2>Clear naming</h2>\n\n<pre><code>var is_Import_Failed_Exist = ...;\nvar is_The_Import_Has_Failed_Exist = ...;\n</code></pre>\n\n<p>For the life of me, I cannot figure out what the difference between them is. The naming of these variables (and the constants after which they are named) is not good, since a reader cant figure out what they represent.</p>\n\n<pre><code>returnObject = new ReturnObject { ... }\n</code></pre>\n\n<p><code>ReturnObject</code> is such a vague name that it fails to express anything meaningful. I'll happily admit that I've struggled coming up with names for return DTOs too, but it needs to have <em>some</em> sort of descriptive name, e.g. <code>ImportStatusDto</code> or <code>ImportStatusResult</code>.</p>\n\n<pre><code>Properties.Resources.ARGS_RESULT_OK_REJECT\n</code></pre>\n\n<p>\"OK\" and \"reject\" seemingly contradict one another. Is this a good outcome, or a bad one? It's unclear and needs better naming to make this clear.</p>\n\n<pre><code>else if (is_No_Errors_Found_Exist)\n{\n StatusResult = Properties.Resources.ARGS_RESULT_OK;\n}\nelse if (is_Import_Failed_Exist)\n{\n StatusResult = Properties.Resources.ARGS_RESULT_OK; // I assume \"KO\" was a typo\n}\n</code></pre>\n\n<p>As a developer reading your code, it's very confusing why the failure of an import is considered a positive (\"OK\") outcome. This seemingly contradicts the evaluation above where the existence of errors is clearly <em>not</em> OK.</p>\n\n<p>This may be a bug in your code. In that case, you probably would've spotted the bug easier if your variable names had been easier to read (see the above tips). </p>\n\n<p>If this isn't a bug, then I'm still inclined to conclude that your naming introduces confusion where none should have existed.</p>\n\n<pre><code>CountLines \n</code></pre>\n\n<p>This sounds like a command or instruction (\"Hey, you! Count those lines!\"), which is how <strong>methods</strong> should be named. </p>\n\n<p>Variable names (except for booleans) should be nouns or noun phrases. <code>LineCount</code> is the better name here.</p>\n\n<p>For completeness' sake, boolean names should generally adhere to yes/no questions: <code>isAlive</code>, <code>hasFood</code>, ... or in other cases phrasings that strongly convey a binary result: <code>userWasDeleted</code>, <code>importFailed</code>, ...<br>\nIn all of these cases, if I were to put a question mark behind the name, it would be bad English but you would understand the question and would easily identify what the meaning of \"yes\" and \"no\" is.</p>\n\n<hr>\n\n<h2>Avoid negative variable names</h2>\n\n<pre><code>is_No_Errors_Found_Exist\n</code></pre>\n\n<p>While you can read it now, this can quickly get out of hand. How would you check that errors were found?</p>\n\n<pre><code>if(!is_No_Errors_Found_Exist)\n</code></pre>\n\n<p>That's a double negative, and really hard to parse. It's much better to stick with \"positive\" naming and then negate the boolean value</p>\n\n<pre><code>bool errorsFound = ...;\n\nif(!errorsFound) { ... }\n\nif(errorsFound) { ... }\n</code></pre>\n\n<p>In this example, there's no need to use a double negative, which improves readability.</p>\n\n<p>Your internal voice should read this as \"not errors found\", which it intuitive and clearly expresses the intention of the evaluation.</p>\n\n<p>Note that when I say \"positive\", I mean \"<strong>not negated</strong>\" instead of \"good\". A boolean called <code>isFailed</code> is a \"positive\" naming. Not because failure is <em>good</em> (it clearly isn't), but because it's not negated.<br>\n<code>importDidNotFail</code> would be the \"negative\" naming (because of the \"not\"), which you should try to avoid to enhance overall readability.</p>\n\n<hr>\n\n<h2>In conclusion</h2>\n\n<p>This is more of a review on your question than the code, but there is a common thread here.</p>\n\n<blockquote>\n <p>First I have two conditions on the number of list elements,then in one of these conditions I have two others conditons to treat it</p>\n</blockquote>\n\n<p>Try to read this from the perspective of a StackExchange user who knows nothing about you or your code. Does this explain what your code is trying to achieve?</p>\n\n<p>I think you're explaining things the way they already make sense to you, while not considering how others will (or won't) understand what you write.</p>\n\n<p>I mention this because <strong>code readability should be written from the perspective of those who don't know the code</strong>. Whenever you name something (a variable, a method, ...) you need to ask yourself a simple question:</p>\n\n<blockquote>\n <p><em>Would a developer who is new to the project understand what this method does/what this variable expresses?</em></p>\n</blockquote>\n\n<p>This is by far the biggest issue in your code. Your naming has made it very hard for anyone else to read your code and understand its purpose. </p>\n\n<p>And it's not just about other people. If you start working on another project, and in a few months' time you have to return to this project, you're going to be scratching your head too, because you won't remember all the things you currently know and will have to build up that working knowledge again.</p>\n\n<p>The other minor issues/bugs I've found are actually fairly common in codebases where readability is hampered, because low readability leads to a high likelyhood of making unintentional mistakes. </p>\n\n<p>I suspect that if you work on improving your code readability, you'll automatically start seeing how to improve parts of the code more and more.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T09:35:12.963", "Id": "462930", "Score": "0", "body": "Thank you so much for all the explanations and advices, it is very detailed" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T17:29:44.057", "Id": "236242", "ParentId": "236235", "Score": "6" } }, { "body": "<p>You use several times the result[0].ToString(). Store it if you need it several times.</p>\n\n<p>The 3 variables in the beginning result in, those variables are computed, also when their value is not used. If you do not use these variables, but put the \"Contains\" evaluation directly in place, they would be only evaluated, when needed.</p>\n\n<p>The last 'If' has no else before. That means it might be possible, a formerly set StatusResult will be overriden.</p>\n\n<p>StatusResult is not always set, I'm not sure there is always at least one path taken.</p>\n\n<p>You could create the ResultObject in the beginning, and store the member values directly, instead of first in local variables, and then copy the local variables. That's minor, cause it's fast, but more lines make the code less readable.</p>\n\n<p>You really distinguish \"OK\" and \"KO\" ? You play tricks on everyone's brain. As more similar words are, as more easy they are mixed up by people. This comment is different from the other answer. I do not try to understand the meaning.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T09:36:40.433", "Id": "462931", "Score": "0", "body": "Thanks a lot for your reply and your advices" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T21:19:39.027", "Id": "236253", "ParentId": "236235", "Score": "2" } }, { "body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><p>A <code>List&lt;StringBuilder&gt;</code> seems a very bad return value, IMHO. Is there a reason for such an unusual type?</p></li>\n<li><p><code>result</code> is a <code>List&lt;StringBuilder&gt;</code>, so it should be <code>results</code>.</p></li>\n<li><p>What is returned in the case of <code>if ((result == null) || (!result.Any()))</code>? I'm guessing a <code>null</code>, so return that as fast as possible, that way the rest of the code doesn't need to be indented as much.</p></li>\n<li><p>Instead of \"\\r\\n\", use <code>Environment.NewLine</code>.</p></li>\n<li><p>This code is almost 40 lines long and yet it seems to be only a part of a longer section of code. This worries me, because it suggests that the method it is part of is much longer and even more convoluted. I'd urge you to split your code into smaller methods which each do one particular task.</p></li>\n</ul>\n\n<hr>\n\n<p>But my main objection is <code>List&lt;StringBuilder&gt;</code>, and that you use this list to do a <code>Contains()</code> on its contents (and then even assume some kind of order in the returned result when a condition about <code>result[0]</code> causes you to parse <code>result[1]</code>). Considering that you're searching for specific predefined phrases, suggests that the return of <code>ReadResult_WS_Import</code> should really be a custom class with meaningful properties.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T10:50:24.703", "Id": "463094", "Score": "0", "body": "Thank you so much for these good advices and tips" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T14:56:14.953", "Id": "236298", "ParentId": "236235", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T14:17:42.193", "Id": "236235", "Score": "0", "Tags": [ "c#", "performance" ], "Title": "Code to test four conditions if C#" }
236235
<p>I have this class to generate unique ids and random ids from those unique ids. </p> <p>For the unique ids, it's a sequence of numbers between (start number = given number [start_seed]/or random number (0:1000000), and end number = start number + number of desired unique id -1) converted to string and hashed using md5 and converted to hex digest.</p> <p>For the random id, get a random number between the start and the end and converted to string and hashed using md5 and converted to hex digest.</p> <p>Is there any better way to generate random ids, and if there are feedbacks in the code structure, efficiency, and performance</p> <pre class="lang-py prettyprint-override"><code>import hashlib import random class RandomIdsGenerator: """ Generate random ids from specific numbers of auto-generated unique ids. For instance: you maybe want to generate 1000 random user ids from 10 unique ids. How it works: it generate random number in specific range and hash this number using md5 and convert it to hexdigest """ __slots__ = ['__n_unique_id', '__start_num', '__end_num'] def __init__(self, n_unique_id: int, start_seed: int = None): """ Initialize RandomIdsGenerator :param n_unique_id: number of unique ids you desire :param start_seed: start number of the unique ids, Default is None that will pick up a number between (0:1000000) you can can use if you want generate ids in specific ranges. """ self.__n_unique_id = n_unique_id self.__start_num = start_seed if not self.__start_num: self.__start_num = random.randrange(1000000) self.__end_num = self.__start_num + n_unique_id - 1 def random(self): """ Generate single random id :return: random id """ random_num = random.randrange(self.__start_num, self.__end_num) hashed_num = hashlib.md5(str(random_num).encode()) return hashed_num.hexdigest() def randoms(self, n_ids: int): """ Generate list of random ids :param n_ids: number of id you need to generate :return: list of random ids it might contains duplications """ random_ids = [] for i in range(0, n_ids): random_ids.append(self.random()) return random_ids def get_unique_ids(self): """ :return: list of unique ids it randomize from """ unique_ids = [] for i in range(self.__start_num, self.__end_num + 1): hashed_num = hashlib.md5(str(i).encode()) unique_ids.append(hashed_num.hexdigest()) return unique_ids </code></pre> <p>The benchmark of <code>get_unique_ids()</code> </p> <pre><code>number of unique ids:10 - avg time of 1k iteration: 2.090144157409668e-05 number of unique ids:100 - avg time of 1k iteration: 7.855653762817383e-05 number of unique ids:1000 - avg time of 1k iteration: 0.0006839170455932617 number of unique ids:10000 - avg time of 1k iteration: 0.006684443712234497 number of unique ids:100000 - avg time of 1k iteration: 0.07844765543937683 number of unique ids:1000000 - avg time of 1k iteration: 0.7951802101135254 </code></pre> <p>The benchmark of getting random id <code>random()</code> from 1M unique id. Time calculated from creating the object and call the function n times</p> <pre><code>get random id:10 - avg time of 1k iteration: 2.903556823730469e-05 get random id:100 - avg time of 1k iteration: 0.00015737485885620117 get random id:1000 - avg time of 1k iteration: 0.0019962642192840577 get random id:10000 - avg time of 1k iteration: 0.01631594944000244 get random id:100000 - avg time of 1k iteration: 0.17304418659210205 </code></pre> <p>Measure performance code</p> <pre><code>from time import time def average(lst): return sum(lst) / len(lst) def measure_performance_generate_unique_ids(n_unique_id, n_iterations=1000): time_performance = [] for i in range(0, n_iterations): start = time() random_id_generator = RandomIdsGenerator(n_unique_id) random_id_generator.get_unique_ids() end = time() total_time = end - start time_performance.append(total_time) perf_str = 'number of unique ids:{} - avg time per iteration: {}'.format(n_unique_id, average(time_performance)) print(perf_str) def measure_performance_pick_random_id(n_random_ids,n_unique_ids=1000000, n_iteration=1000): time_performance = [] for i in range(0, n_iteration): start = time() random_id_generator = RandomIdsGenerator(n_unique_ids) for n in range(0, n_random_ids): random_id_generator.random() end = time() total_time = end - start time_performance.append(total_time) perf_str = 'get random id:{} - avg time per iteration: {}'.format(n_random_ids ,average(time_performance)) print(perf_str) </code></pre> <p>Call the measurement methods:</p> <pre><code>measure_performance_generate_unique_ids(10) measure_performance_generate_unique_ids(100) measure_performance_generate_unique_ids(1000) measure_performance_generate_unique_ids(10000) measure_performance_generate_unique_ids(100000) measure_performance_generate_unique_ids(1000000) measure_performance_pick_random_id(10) measure_performance_pick_random_id(100) measure_performance_pick_random_id(1000) measure_performance_pick_random_id(10000) measure_performance_pick_random_id(100000) measure_performance_pick_random_id(1000000) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T16:26:13.440", "Id": "462859", "Score": "1", "body": "Why not use a GUID? There are lots of libraries that handle this. [How to create a GUID/UUID in Python](https://stackoverflow.com/q/534839/14065)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T16:42:40.027", "Id": "462862", "Score": "0", "body": "Because I need a specific number of unique ids and select randomly from those ids.\nFor instance, want to have 100k unique id and generate 1M randomly from the unique 100K ids. And to do that using GUID/UUID I have to save those 100K unique ids. so this class makes you able to generate random id from unique ids on the fly without saving it. @MartinYork" } ]
[ { "body": "<p>This is some nice-looking Python code. Good work. Though, if you were to run <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\"><code>pylint</code></a> over this, you'd still find:</p>\n\n<blockquote>\n<pre><code>************* Module cr\ncr.py:1:0: C0114: Missing module docstring (missing-module-docstring)\ncr.py:44:12: W0612: Unused variable 'i' (unused-variable)\n\n------------------------------------------------------------------\nYour code has been rated at 9.20/10\n</code></pre>\n</blockquote>\n\n<p>So, it's usually good practice to add a module docstring at the beginning of the module. I've seen many people adding the same docstring as the one for the class within that module (if it's just one).</p>\n\n<p>From <a href=\"https://www.python.org/dev/peps/pep-0257/#id15\" rel=\"nofollow noreferrer\">PEP8</a>:</p>\n\n<blockquote>\n <p>All modules should normally have docstrings, and all functions and\n classes exported by a module should also have docstrings. Public\n methods (including the <code>__init__</code> constructor) should also have\n docstrings. A package may be documented in the module docstring of the\n <code>__init__.py</code> file in the package directory.</p>\n</blockquote>\n\n<p>So, in the end, it is just a matter of preference.</p>\n\n<p>You also have a magic number: <code>1000000</code>. I'd just take it out of your <code>__init__</code> and define it as a constant. Something like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>MAX_RANGE = 1000000\n</code></pre>\n\n<p>Now, the second pylint warning tells you that here:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(0, n_ids): # you're not using i at all\n random_ids.append(self.random())\nreturn random_id\n</code></pre>\n\n<p>So you could just replace it with <code>_</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for _ in range(0, n_ids):\n random_ids.append(self.random())\nreturn random_id\n</code></pre>\n\n<p>Even better, you could entirely rewrite the above and use a list comprehension instead:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def randoms(self, n_ids: int):\n \"\"\"\n Generate list of random ids\n :param n_ids: number of id you need to generate\n :return: list of random ids it might contains duplications\n \"\"\"\n\n return [self.random() for _ in range(0, n_ids)]\n</code></pre>\n\n<p>The same applies for <code>get_unique_ids()</code> method (although some might argue that there's a small benefit in favour of readability):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_unique_ids(self):\n \"\"\"\n :return: list of unique ids it randomize from\n \"\"\"\n\n return [\n hashlib.md5(str(i).encode()).hexdigest()\n for i in range(self.__start_num, self.__end_num + 1)\n ]\n</code></pre>\n\n<p>From <a href=\"https://stackoverflow.com/a/30245465/8605514\">this SO answer</a>:</p>\n\n<blockquote>\n <p>List comprehension is basically just a \"syntactic sugar\" for the\n regular for loop. In this case the reason that it performs better is\n because it doesn't need to load the append attribute of the list and\n call it as a function at each iteration. In other words and in\n general, list comprehensions perform faster because suspending and\n resuming a function's frame, or multiple functions in other cases, is\n slower than creating a list on demand.</p>\n</blockquote>\n\n<p>This won't have such a big impact on the actual speed, but it's definitely giving you a nice start :)</p>\n\n<p>Another advice would be to use Numpy if you want to generate <strong>large numbers</strong> of random ints; if you're just generating one-at-a-time, it may not be as useful (but then how much do you care about performance, really?). </p>\n\n<p>Libraries like Numpy carefully move as much compute as possible to underlying C code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T16:17:51.097", "Id": "236239", "ParentId": "236238", "Score": "2" } } ]
{ "AcceptedAnswerId": "236239", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T15:01:58.923", "Id": "236238", "Score": "3", "Tags": [ "python", "python-3.x", "random" ], "Title": "Generate random ids from specific numbers of auto generated unique ids" }
236238
<p>I recently wrote the following Java 1.8 snippet to generate a CLABE control digit based on the following subheading on the CLABE page on <a href="https://en.wikipedia.org/wiki/CLABE#Control_digit" rel="nofollow noreferrer">Wikipedia</a> and I was curious on how it could be improved.</p> <pre><code>private void generateCLABEControlDigit() { final int[] expectedResults = {0,1,2,3,6,0,0,0,0,3,7,8,9,5,9,1,7}; final String incompleteClabe = "03218000011835971"; final String completeClabe = "032180000118359719"; char[] clabeChars = incompleteClabe.toCharArray(); int[] weightFactors = {3, 7, 1}; int[] results = new int[clabeChars.length]; int count = 0; for (int i = 0; i &lt; incompleteClabe.length(); i++) { int clabeInt = Integer.parseInt(String.valueOf(clabeChars[i])); int weightFactor = weightFactors[count]; int result = clabeInt * weightFactor % 10; results[i] = result; if(count == 2) { count = 0; } else { count++; } } final int controlDigit = (10 - Arrays.stream(results).sum() % 10) % 10; assert Boolean.TRUE.equals(Arrays.equals(expectedResults, results)); assert completeClabe.equals(incompleteClabe + controlDigit); } </code></pre> <p>I have included the incomplete CLABE and complete expected CLABE, these are also present within the Wiki article. </p> <p>This snippet normally takes a String value and would return an integer, this being the generated control digit. However, for purposes of the review I've simply refactored it so it can be simply lifted into a class and run along with the expected outcome (See the <code>assert</code>).</p> <p>The CLABE comes into the system as a String, which resulted in the not so elegant one liner. </p> <pre><code>int clabeInt = Integer.parseInt(String.valueOf(clabeChars[i])); </code></pre>
[]
[ { "body": "<p>For the <code>Integer.parseInt(String.valueOf(clabeChars[i]))</code> part, you can use <a href=\"https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/Character.html#digit(char,int)\" rel=\"nofollow noreferrer\"><code>java.lang.Character#digit(char, int)</code></a> to get the integer value in base 10.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> //[...]\n int clabeInt = Character.digit(clabeChars[i], 10);\n //[...]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T03:36:55.137", "Id": "462898", "Score": "0", "body": "Generally we use the dot separator for static / class methods, don't we? The `#` is there for indicating method calls on *instances* of the class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T12:46:49.430", "Id": "462950", "Score": "0", "body": "In the code yes, but for myself, when I write in markdown, I prefer to use the [#link](https://docs.oracle.com/en/java/javase/11/docs/specs/doc-comment-spec.html#link) javadoc style when referring to methods." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T17:01:21.513", "Id": "463001", "Score": "0", "body": "Oh, OK, although that only seems to be the syntax of the JavaDoc source. It is replaced by a dot in the text when I refer to e.g. `BigInteger#valueOf(long)` (or even one of the non-static methods)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T22:49:07.067", "Id": "236259", "ParentId": "236241", "Score": "3" } }, { "body": "<p>There are certainly a few things that can be improved.</p>\n\n<p>Mainly the amount of intermediate (array) variables is just unnecessary. They use up memory, which means things get big and slow. The adding up can be performed within the loop.</p>\n\n<p>Computers don't like branching (<code>if</code> statements), so if you can remove branches from a loop and replace them by a calculation (such as <code>% 3</code>) then that's always a boon, especially if the result is more readable as well.</p>\n\n<p>The integer <code>count</code> is not well named. If it would be used in my code below, it would be named <code>weightIndex</code> or something similar.</p>\n\n<p>I think the method is better named <code>calculateCLABEControlDigit</code> but I'm a bit lazy and won't rename it here. \"Generate\" is a bit much for such a calculation in my opinion.</p>\n\n<pre><code>public class CLABE {\n private static final String INCOMPLETE_CLABE = \"03218000011835971\";\n private static final String COMPLETE_CLABE = \"032180000118359719\";\n private static final int[] WEIGHT_FACTORS = {3, 7, 1};\n\n public static char generateCLABEControlDigit(final String incompleteClabe) {\n int sum = 0;\n for (int i = 0; i &lt; incompleteClabe.length(); i++) { \n final int digitValue = Character.digit(incompleteClabe.charAt(i), 10);\n final int weightFactor = WEIGHT_FACTORS[i % 3];\n sum = (sum + (digitValue * weightFactor) % 10) % 10;\n }\n\n final int controlDigitValue = (10 - (sum % 10) % 10);\n return Character.forDigit(controlDigitValue, 10);\n }\n\n public static void main(String[] args) {\n String clabe = INCOMPLETE_CLABE + generateCLABEControlDigitLessMod(INCOMPLETE_CLABE);\n if (clabe.equals(COMPLETE_CLABE)) {\n System.out.println(\"Yay!\");\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Now just to spook you a bit, some modular operations can be removed from the loop. For multiplication and addition, the final digit will remain correct after all. That is, as long as the sum is below <code>Integer.MAX_VALUE</code>. Of course you'd need a <em>very</em> long CLABE before you can add up to that (with 9 x 7 = 63 being the highest value that may be added per digit).</p>\n\n<p>The double modulus is required for the final subtraction, as the sum can be 0 (an all zero incomplete CLABE) and because the Java mod operator is terrible when it comes to negative left-operand values. Actually, it's not a modulus operator at all. It is called the <strong>rest operator</strong>, as it may return negative values even if the modulus is positive. That's OK though because it is not in the loop.</p>\n\n<pre><code> public static char generateCLABEControlDigitLessMod(final String incompleteClabe) {\n int sum = 0;\n for (int i = 0; i &lt; incompleteClabe.length(); i++) { \n final int digitValue = Character.digit(incompleteClabe.charAt(i), 10);\n final int weightFactor = WEIGHT_FACTORS[i % 3];\n sum += digitValue * weightFactor;\n }\n\n final int controlDigitValue = (10 - (sum % 10) % 10);\n return Character.forDigit(controlDigitValue, 10);\n }\n</code></pre>\n\n<p>Of course this speedup doesn't make any difference for this particular method. However, adding or removing modular operations is an interesting speedup trick to use in cases where it <em>does</em> matter, so I thought it was interesting enough to show you.</p>\n\n<hr>\n\n<p>The testing with the vectors from Wikipedia (or preferably a banking standard) should be done by a Unit test.</p>\n\n<p>Besides that, I'd probably make sure that the input is consisting just of digits before running any code on it by using a guard statement such as:</p>\n\n<pre><code>if (!incompleteClabe.matches(\"\\\\d*\")) {\n throw new IllegalArgumentException(\"Not a valid CLABE sans control digit\");\n}\n</code></pre>\n\n<p>or even:</p>\n\n<pre><code>if (!incompleteClabe.matches(\"\\\\d{17}\")) {\n throw new IllegalArgumentException(\"Not a valid CLABE sans control digit\");\n}\n</code></pre>\n\n<p>The <code>CLABE</code> class as specified should be made <code>final</code> <strong>and</strong> should not be instantiated as it only contains <code>static</code> methods. That is performed by adding a private, no argument constructor to it.</p>\n\n<p>Finally, I might also create a <code>validateCLABEControlDigit(final String fullClabe): boolean</code> method that uses the other method. I'll leave the implementation up to you...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T19:05:36.473", "Id": "463484", "Score": "0", "body": "Thanks for the helpful insight on the modulus operator. As I was writing it I knew I went overkill on the array declarations, and the integer count. The `WEIGHT_FACTORS[i % 3];` is an interesting way of looping through the array and I'll be sure to keep this in mind next time! Much appreciated." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T04:33:38.097", "Id": "236271", "ParentId": "236241", "Score": "4" } } ]
{ "AcceptedAnswerId": "236271", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T17:21:20.017", "Id": "236241", "Score": "3", "Tags": [ "java" ], "Title": "How could this Java CLABE control digit calculation be enhanced" }
236241
<p>I was playing around with ASP.NET Core <strong>3.1</strong> and tried to implement Dependency Injection flavor called <a href="https://blog.ploeh.dk/2014/06/10/pure-di/" rel="nofollow noreferrer">Pure DI</a>, i.e. without dependency container (even the built in one) to instantiate Controllers. You can see entire code <a href="https://github.com/Caleb9/AspNetCorePureDiApi/tree/fcf0fe9a518c3c3ae5366514e5fce255bb5f78d8" rel="nofollow noreferrer">here</a>, but here's the rundown: I know I have to replace the default <code>IControllerActivator</code> but the main issue concerns singleton <code>IDisposable</code> dependencies, which have to be held by the Composition Root for entire application lifetime and disposed when the application shuts down (I know it's not <em>strictly</em> necessary, but it's a good practice - I've seen some funky implementations of database bulk-inserts which flush data in the <code>Dispose</code> method :S). My idea then is based on implementing a custom <code>ControllerActivator</code> (the Composition Root) with a Singleton pattern, so I can access it and dispose of it when the application shuts down. Here's the <code>Program.cs</code> (I trimmed some comments and namespace imports to save space):</p> <pre class="lang-cs prettyprint-override"><code> public class Program { public static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); try { await host.RunAsync(); } finally { /* Dispose singletons held in ControllerActivator when application shuts down. */ ControllerActivator.Singleton.Dispose(); } } public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder =&gt; { webBuilder.UseStartup&lt;Startup&gt;(); }); } } </code></pre> <p>And here's the <code>ControllerActivator</code>:</p> <pre class="lang-cs prettyprint-override"><code> public sealed class ControllerActivator : IControllerActivator, IDisposable { internal static readonly ControllerActivator Singleton = new ControllerActivator(); private readonly List&lt;IDisposable&gt; _singletonDisposables = new List&lt;IDisposable&gt;(); /// &lt;summary&gt; /// An example of a singleton, disposable object used in controller's dependency graph. /// &lt;/summary&gt; private readonly DisposableDependency _singletonDisposableDependency; public ControllerActivator() { _singletonDisposableDependency = RegisterSingletonForDispose(new DisposableDependency()); } object IControllerActivator.Create(ControllerContext context) { if (GetControllerType(context) == typeof(HelloController)) { var scopedDependency = RegisterForDispose(context, new DisposableDependency()); return new HelloController( _singletonDisposableDependency, scopedDependency); } throw new InvalidOperationException("Unknown Controller Type"); } void IControllerActivator.Release(ControllerContext context, object controller) { } public void Dispose() { foreach (var disposable in _singletonDisposables) { disposable.Dispose(); } } private T RegisterSingletonForDispose&lt;T&gt;(T disposableSingleton) where T : IDisposable { _singletonDisposables.Add(disposableSingleton); return disposableSingleton; } private Type GetControllerType(ControllerContext context) { return context.ActionDescriptor.ControllerTypeInfo.AsType(); } private T RegisterForDispose&lt;T&gt;(ActionContext context, T scopedDisposable) where T : IDisposable { context.HttpContext.Response.RegisterForDispose(scopedDisposable); return scopedDisposable; } } </code></pre> <p>Please take a look in the linked GitHub repo to get the full picture.</p> <p>Now to my questions: Can you see any potential problems with such implementation? Is there a better, more "standard" way to do this?</p> <p>Note: plugging into <code>IApplicationLifetime</code> in <code>Startup</code> is deprecated in ASP.NET Core 3.1, that's why I utilized Program's finally clause to dispose <code>ControllerActivator</code>.</p> <p>TIA</p>
[]
[ { "body": "<p>After some time I realized the main problem with usage of Singleton pattern for this purpose: <strong>it is the inability to replace dependencies with test doubles in tests</strong>. It is because the <code>CompositionRoot</code> instance, which implements both <code>IMiddlewareFactory</code> and <code>IControllerActivator</code>, is static. Maybe it would be possible to set specific dependencies in tests using <em>Ambient Context</em> [anti]pattern but that brings its own set of problems.</p>\n<p>I updated <a href=\"https://github.com/Caleb9/AspNetCorePureDiApi\" rel=\"nofollow noreferrer\">the linked repository</a> with alternative (I think better) solution.</p>\n<p>(Note that I expanded the example to cover resolving middlewares as well as controllers, which was not mentioned in the original question - this also demonstrates an <strong>unresolved flaw in this solution, i.e. that request scoped dependencies are not shared between middlewares and controllers</strong>.)</p>\n<p>It basically boils down to utilization of the built-in DI container (i.e. the <code>IServiceCollection</code>) in <code>Startup.cs</code> a bit more, like so:</p>\n<pre><code> public void ConfigureServices(\n IServiceCollection services)\n {\n services\n .AddSingleton&lt;CompositionRoot&gt;()\n .AddSingleton&lt;IMiddlewareFactory&gt;(s =&gt; s.GetRequiredService&lt;CompositionRoot&gt;())\n .AddSingleton&lt;IControllerActivator&gt;(s =&gt; s.GetRequiredService&lt;CompositionRoot&gt;())\n .AddControllers();\n }\n</code></pre>\n<p>This leaves open a possibility to replace <code>CompositionRoot</code> registration in test code.</p>\n<p>Usage of factory method in <code>IMiddlewareFactory</code> and <code>IControllerActivator</code> registrations (instead of e.g. <code>services.AddSingleton&lt;IMiddlewareFactory, CompositionRoot&gt;</code>) is necessary to avoid creating two separate instances of <code>CompositionRoot</code> - we resolve an instance from the first registration as both <code>IMiddlewareFactory</code> and <code>IControllerActivator</code>.</p>\n<p><code>Program.cs</code> can then be reduced to its standard form:</p>\n<pre class=\"lang-cs prettyprint-override\"><code> public static class Program\n {\n public static async Task Main(string[] args)\n {\n using var host = CreateHostBuilder(args).Build();\n await host.RunAsync();\n }\n\n private static IHostBuilder CreateHostBuilder(string[] args)\n {\n return Host\n .CreateDefaultBuilder(args)\n .ConfigureWebHostDefaults(builder =&gt; builder.UseStartup&lt;Startup&gt;());\n }\n }\n</code></pre>\n<p>This way the <code>CompositionRoot</code> gets disposed along with <code>IServiceCollection</code> when application shuts down, and that gives us a chance to dispose singleton dependencies it created.</p>\n<p>In summary I have to say it would be quite cumbersome to follow this pattern in a large code-base - ASP.NET Core seems to really push for usage of the built-in container. But it is possible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-15T12:47:44.927", "Id": "252144", "ParentId": "236245", "Score": "0" } }, { "body": "<p>You might want to check out the <a href=\"https://github.com/DependencyInjection-2nd-edition/codesamples/\" rel=\"nofollow noreferrer\">code samples</a> repository of the book <a href=\"https://mng.bz/BYNl\" rel=\"nofollow noreferrer\">Dependency Injection Principles, Practices, and Patterns</a>. I co-authored this book. It contains a <a href=\"https://github.com/DependencyInjection-2nd-edition/codesamples/tree/master/AopECommerce/src/Commerce.Web.PureDI\" rel=\"nofollow noreferrer\">Pure DI example for an ASP.NET Core web application</a>.</p>\n<p>This example implements a <a href=\"https://github.com/DependencyInjection-2nd-edition/codesamples/blob/master/AopECommerce/src/Commerce.Web.PureDI/CommerceControllerActivator.cs\" rel=\"nofollow noreferrer\">custom</a> <code>IControllerActivator</code> that acts as <a href=\"https://freecontent.manning.com/dependency-injection-in-net-2nd-edition-understanding-the-composition-root/\" rel=\"nofollow noreferrer\">Composition Root</a>. This activator implements <code>IDisposable</code> to implement deterministic cleanup of Singleton dependencies on application shutdown. Its <code>Dispose</code> method is called by the ASP.NET Core framework on shutdown. This is achieved by <a href=\"https://github.com/DependencyInjection-2nd-edition/codesamples/blob/master/AopECommerce/src/Commerce.Web.PureDI/Startup.cs#L29\" rel=\"nofollow noreferrer\">adding</a> the customer activator to ASP.NET Core's infrastructure.</p>\n<p>Section 7.3.2 of <a href=\"https://mng.bz/BYNl\" rel=\"nofollow noreferrer\">the book</a> contains an example that adds custom middleware using Pure DI. This example is reflected in the code samples <a href=\"https://github.com/DependencyInjection-2nd-edition/codesamples/blob/master/AopECommerce/src/Commerce.Web.PureDI/Startup.cs#L49-L58\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>For creation of middlewhere that shares the same Singleton, you can add extra methods (e.g. <code>CreateMyMiddleware()</code>) on your custom controller activator (which is different than the example in section 7.3.2) and make sure they are added to the ASP.NET Core pipeline during startup.</p>\n<p>This, however, will not immediately solve the problem of sharing scoped dependencies between controllers and middleware, but since middleware is resolved from the same class, this shouldn't be that hard to implement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-15T16:44:32.247", "Id": "496665", "Score": "1", "body": "Hi Steven. I've read your and Mark's book (it's beyond great! :)) - I'll take another look at the examples and try to see if I can resolve the shared scoped dependencies issue somehow. Thank you! :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-15T16:23:34.597", "Id": "252149", "ParentId": "236245", "Score": "3" } } ]
{ "AcceptedAnswerId": "252144", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T17:56:59.430", "Id": "236245", "Score": "6", "Tags": [ "c#", "dependency-injection", "asp.net-core", "asp.net-core-webapi", "asp.net-core-3.0" ], "Title": "ASP.NET Core Web API + Pure DI" }
236245
<p>I am writing a function inside of a React component to hide/show columns in a table. The table is generated from an imported config object containing objects which model the column data. We render by simply mapping over the table content and rendering cells based on the columns. The method I'm writing exists in the table component and accepts a string corresponding to the <code>targetProp</code> property inside of a column object. Additionally, the table needs to render a child component which serves as an actual toggle menu.</p> <pre><code> toggleTableColumn(targetProp: string) { const allColumns = tableConfigMap[this.configName].columns; //an array of all column objects available for display const targetColumnIndex = _.findIndex(allColumns, { targetProp }); // original index of target column, used for re-inserting in correct order const targetColumn = allColumns[targetColumnIndex]; const displayedColumns = [...this.tableConfig.columns]; const columnShown = !_.isUndefined(_.find(displayedColumns, { ...targetColumn })); if (columnShown) { const adjustedColumns = _.without(this.tableConfig.columns, targetColumn); this.tableConfig = { ...this.tableConfig, columns: adjustedColumns }; } else { const adjustedColumns = displayedColumns; adjustedColumns.splice(targetColumnIndex, 0, targetColumn); this.tableConfig = { ...this.tableConfig, columns: adjustedColumns }; } } </code></pre> <p>I'm feeling like there must be a more elegant way to do this. I'm attempting not to add some kind of <code>isVisible</code> prop to the table column objects as it seems wrong to put this kind of view logic into the data model. </p> <p>The child component menu will contain a dropdown list of all the columns with checkboxes corresponding to visible/invisible columns. It seems to me like not only would I have to pass this toggle function to the menu component, I'd also have to pass the list of all columns AND the list of selected columns as props to the menu component in order to properly render the checkbox styles (checked or unchecked).</p> <p>This feels very sloppy, there must be a more elegant way. I hope this makes sense.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T19:09:49.693", "Id": "236247", "Score": "2", "Tags": [ "react.js", "typescript", "jsx" ], "Title": "Method to hide/show table columns with React/JSX" }
236247
<p>I have been programming for a while, but I've only made games and less serious stuff. I want to get more serious. I would like some feedback on this class that defines a person. Structure, readability, use of static variables, etc. Please point out everything that can be improved.</p> <pre><code>public class Person { private String firstName, lastName, address; private int age; private boolean hasAddress = false; private boolean hasAge = false; private static final String NO_ADDRESS = "No address defined"; //Constructors //Minimum information required public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } //All possible info public Person(String firstName, String lastName, int age, String address) { this(firstName, lastName); this.age = age; this.address = address; hasAge = true; hasAddress = true; } //No address defined public Person(String firstName, String lastName, int age) { this(firstName, lastName); this.age = age; hasAge = true; } //No age defined public Person(String firstName, String lastName, String address) { this(firstName, lastName); this.address = address; hasAddress = true; } //Methods //Get-methods public String getName() { return firstName + lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { if (hasAge) return age; else return 0; //Return 0 if no age is defined } public String getAddress() { if (hasAddress) return address; else return NO_ADDRESS; } //Set-methods public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setAge(int age) { this.age = age; } public void setAddress(String address) { this.address = address; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T20:46:40.927", "Id": "462880", "Score": "8", "body": "You didn't test your code thoroughly before posting it here. If you had done that, you would have noticed that `getName()` just squashes together the first name and the last name, without a space in-between. This is probably not what you intended." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T12:10:06.293", "Id": "462943", "Score": "9", "body": "@RolandIllig For the purpose of getting a username, it actually could be. Anyways, I wouldn't consider the code as \"not working\" simply for that minor issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T13:23:17.187", "Id": "462954", "Score": "0", "body": "As designed you have a bug in your setAge and setAddress methods, you neglect to set your hasAge and hasAddress fields. if you start with a Person without a specified age and then call setAge subsequent calls to getAge will still return 0." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T16:12:12.197", "Id": "462992", "Score": "0", "body": "I wouldn't have age as an attribute, since it depends on the time when it's queried. However, I would have a date of birth field and have a `getAge()` method that calculates the age in runtime and returns it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T20:42:50.040", "Id": "463030", "Score": "1", "body": "Classes are designed for a *purpose*. What is the purpose of modeling a person like this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T10:05:22.367", "Id": "463090", "Score": "0", "body": "That's a lot of code for a 4-tuple. The class seems to allow any combination of possibly-null `firstName`, `lastName`, `address` and `age`. What are you trying to achieve exactly with more code than a class with 4 public fields?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:41:07.047", "Id": "463127", "Score": "0", "body": "I would suggest, that you check the values going in. For example, age has to be a positive number. (0-200) or so. Name has to be at least one char long. And so on." } ]
[ { "body": "<p>Instead of adding a boolean to check if the value is set, I suggest that you set the values with a default value; so if the value is not set, it will return it.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Person {\n private String firstName;\n private String lastName;\n private String address = \"No address defined\";\n private int age = 0;\n\n//Constructors\n\n //Minimum information required\n public Person(String firstName, String lastName) {\n this.firstName = firstName;\n this.lastName = lastName;\n }\n\n //All possible info\n public Person(String firstName, String lastName, int age, String address) {\n this(firstName, lastName);\n this.age = age;\n this.address = address;\n }\n\n //No address defined\n public Person(String firstName, String lastName, int age) {\n this(firstName, lastName);\n this.age = age;\n }\n\n //No age defined\n public Person(String firstName, String lastName, String address) {\n this(firstName, lastName);\n this.address = address;\n }\n\n//Methods\n\n //Get-methods\n public String getName() {\n return firstName + lastName;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public int getAge() {\n return age;\n }\n\n public String getAddress() {\n return address;\n }\n\n //Set-methods\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public void setAge(int age) {\n this.age = age;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n}\n\n</code></pre>\n\n<p>If you want to keep the same logic, put <code>-1</code> as the <code>age</code> and <code>null</code> to the <code>address</code> and compare the value in the getter.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Person {\n private String firstName;\n private String lastName;\n private String address = null;\n private int age = -1;\n private static final String NO_ADDRESS = \"No address defined\";\n\n//Constructors\n\n //Minimum information required\n public Person(String firstName, String lastName) {\n this.firstName = firstName;\n this.lastName = lastName;\n }\n\n //All possible info\n public Person(String firstName, String lastName, int age, String address) {\n this(firstName, lastName);\n this.age = age;\n this.address = address;\n }\n\n //No address defined\n public Person(String firstName, String lastName, int age) {\n this(firstName, lastName);\n this.age = age;\n }\n\n //No age defined\n public Person(String firstName, String lastName, String address) {\n this(firstName, lastName);\n this.address = address;\n }\n\n//Methods\n\n //Get-methods\n public String getName() {\n return firstName + lastName;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public int getAge() {\n if (age &gt; 0)\n return age;\n else\n return 0; //Return 0 if no age is defined\n }\n\n public String getAddress() {\n if (address != null)\n return address;\n else\n return NO_ADDRESS;\n }\n\n //Set-methods\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public void setAge(int age) {\n this.age = age;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n}\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T13:25:06.310", "Id": "462956", "Score": "0", "body": "one could also use Integer instead of int for age and default it to null as well" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T13:26:27.210", "Id": "462957", "Score": "1", "body": "Don't use sentinel values like `-1`, `\"\"`, `\"No address defined\"`. Arguably, you should even avoid `null`. Optional exists, and it fits the bill perfectly. What are the chances you'll use the age, forgetting that it could \"not be set\" (and poorly encoded as `-1`), and accidentally show a `-1 year old` age on the UI? Plus, what if this wasn't age, but some other value that could be negative? `OptionalInt` is a better choice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T19:13:47.660", "Id": "463173", "Score": "1", "body": "I have to disagree with Alexander — Use sentinels or unset values (null) when needed, but deal with them internally, and don't return them from getters. `getAge()` then could be `public OptionalInt getAge()` where if `age < 0` then return OptionalInt.empty() and that leaves no chance of a caller accidentally using the sentinel values. I would tend to use `null`, so would have `private Integer age = null;` and getAge would `return age == null ? OptionalInt.empty() : OptionalInt.of(age)`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T23:09:54.267", "Id": "236260", "ParentId": "236249", "Score": "3" } }, { "body": "<p><strong>Design</strong></p>\n\n<p>The problem with <code>getName</code> is already mentioned in the comments. <code>firstName + lastName</code> is at least missing a space. Note that there are multiple ways of creating a full name - you may want to leave the construction of a full name to the caller. For instance, Germans are a bit more formal and may prefer \"lastname, firstname\". Usually initials are also an important part of a name (and then there is title, junior/senior etc.). </p>\n\n<p>Second is the age. An age is a property of a person, but it is not one that keeps constant in time. You generally store the birthday of a person. Usually the precise <em>day</em> is stored (YYYY-MM-DD), or in more complex systems just the month (YYYY-MM) or even just the year (YYYY) if the other information is unknown. This may seem strange, but not everybody knows their exact birthday. The <em>age</em> can then be calculated from that using comparison with the current date.</p>\n\n<p>Related, using <code>0</code> to signify that no age is known is choosing a bad <em>magic value</em> (or sentinel). Magic values are already not recommended, but choosing a <em>valid age for a baby</em> as magic value is not a good idea at all. </p>\n\n<p>Returning <code>return NO_ADDRESS;</code> is dangerous, especially if you don't have any method to indicate that <code>NO_ADDRESS</code> is indeed <strong>not an address</strong>. It is generally up to the caller to choose what to insert as string if no address is known, otherwise you may get packages posted to <code>NO_ADDRESS</code>. A <code>hasAddress</code> method would solve this. If you have an unknown address then you may use an <code>Optional</code> value instead. Accepting and returning an <code>Optional&lt;String&gt;</code> would remove the issue altogether and may bring down the number of methods and constructors. Storing the address as optional is not recommended because it cannot be serialized; probably best to use <code>null</code>, but make sure that you don't return <code>null</code>.</p>\n\n<p>As you may notice, currently your <code>Person</code> instances can change completely by calling the setters. That's no good if you want to keep track of a person. This is why almost all organizations will create a unique ID for each person. That way any property can change without them becoming someone else. The ID can then represent the person in e.g. a transaction system.</p>\n\n<p><strong>Code</strong></p>\n\n<p>The code is generally well formed.</p>\n\n<p>However there are some remarks to be made:</p>\n\n<ul>\n<li>fields default to <code>false</code> so there is no need to initialize them to that value; it might be a good idea to set all fields in the various constructors so that they are not forgotten;</li>\n<li>the <code>if</code> statement does not use braces; <strong>always</strong> use braces to subsequent changes do not result in unmaintainable code;</li>\n<li>similarly, you will probably use class instances in collections, so you need to implement the <code>hashCode</code> and <code>equals</code> methods;</li>\n<li>implementing <code>toString</code> is recommended for any class really.</li>\n</ul>\n\n<p><strong>Ideas</strong></p>\n\n<p>Using <code>set</code> methods is generally not a good idea. Having immutable objects often makes more sense. Other variants you may consider is having a <code>Map</code> of properties or having a factory / factory methods to create <code>Person</code> instances.</p>\n\n<p>In Java, you may want to implement <code>Serializable</code> for data classes (and the static serializable UID - Eclipse will warn you about this) - that way you can more easily communicate data over a binary connection / stream. This is contended in the comments. In general, I would however try and keep in mind that you may want to be able to serialize a class in the future and - therefore - try and use serializable fields.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T05:43:41.897", "Id": "462905", "Score": "5", "body": "`Optional` is not meant to be used in fields." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T05:46:55.633", "Id": "462906", "Score": "2", "body": "Why should data classes be serializable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T08:31:01.403", "Id": "462926", "Score": "4", "body": "And better than `Optional<Integer>`: `OptionalInt`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T13:21:41.060", "Id": "462952", "Score": "1", "body": "The only arg I've heard for optionals not being stored in fields is that they aren't serialization by Java's jank serialization mechanism. But the serialization mechanism has been so fraught with security vulnerabilities, it's better to just pretend it doesn't exist." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T13:24:14.680", "Id": "462955", "Score": "0", "body": "\"always use braces to subsequent changes do not result in unmaintainable code;\" You can solve the same problem by just prohibiting multi-line `if` statements without blocks. `if (condition) return;` is totally fine IMO. You only get into dangerous [`goto fail`](https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/) land when you let the body go on a second line. Just don't do that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T15:59:50.293", "Id": "462987", "Score": "0", "body": "I don't agree with some of the points you made (serializable, avoid setters... huh?), but I feel like I should upvote this answer, just for the \"_**always** use braces_\" alone." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T16:54:47.933", "Id": "462998", "Score": "0", "body": "@RolandIllig Looked up issues with `Optional` in field, which is generally not recommended as it messes up serialization. Serialization - the representation of the class in binary - is commonly useful for classes that represent data. I've however moved that into the comments and changed the recommendation to make sure that the class *can* be made `Serializable` in the future (which kind of automatically means a clean class design without additional references). Thanks for the comments!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T20:12:24.163", "Id": "463024", "Score": "0", "body": "Please don't implement `Serializable` just because. Effective Java (a great Java book, BTW) [explains this in detail](https://learning.oreilly.com/library/view/effective-java-3rd/9780134686097/ch12.xhtml)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T15:16:39.547", "Id": "463138", "Score": "0", "body": "@MaartenBodewes To quote my comment from another thread: \"[Java's serialization mechanism]'s fundamentally broken, and a consistent fountain of security vulnerabilities, so I would argue it shouldn't be used at all, ever, under any circumstances. So I don't think that's a good reason not to use Optional in args/fields. \"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T17:17:40.990", "Id": "463149", "Score": "0", "body": "I don't completely agree with that. I think it is fine for (otherwise secured) internal communication / short storage etc., just not for outside interface specifications. I don't know why people think it is prudent to be used for that. I would not however frown too much if anybody used `Optional` in a field - you can always refactor when serialization is required. And in the end it is the best way of indicating the condition." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T09:36:21.090", "Id": "463280", "Score": "0", "body": "Using Optional in a field is abusing it's purpose, which is \"code level static typing of possible null in method return value\". Having the field be optional is pointless waste of an object allocation, since the field is internal to the class and the class knows what it stores in the field. And let me repeat this again: there is nothing evil in null checks. The evil is not knowing if a return value can be null and Optional was created to fight that evil." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T09:39:33.313", "Id": "463281", "Score": "0", "body": "Needing a field to be Optional is maybe a signal from things gone wrong elsewhere. The field is accessed from too many places? The class is too big to be easily understood by the developer? So I think it's a cure to the symptom, not the disease." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T23:10:06.760", "Id": "236261", "ParentId": "236249", "Score": "13" } }, { "body": "<p>Something the other answer(s) haven't touched on.</p>\n\n<hr>\n\n<h1>Ternary Operators</h1>\n\n<p><code>getAge()</code> and <code>getAddress()</code> can both be simplified using ternary operators:</p>\n\n<pre><code>public int getAge() {\n return age &gt; 0 ? age : 0;\n}\n\npublic String getAddress() {\n return address != null ? address : NO_ADDRESS;\n}\n</code></pre>\n\n<p>Ternary works as following (in this case):</p>\n\n<pre><code>return (boolean condition) ? (value if true) : (value if false);\n</code></pre>\n\n<p>It's a shorter way to write the same code, and it looks a bit neater. </p>\n\n<p>Also, <em>always</em> use brackets, even in a one line <code>if/else</code>. It made everything easier to read and understand, especially since you switch between the two in multiple places in your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T17:54:50.087", "Id": "463007", "Score": "1", "body": "Note that ternary operators are very contentious, many people would rather see them gone from the language and some style guides disallow them. The bigger problem is to leave the \"sentinel\" values `0` and `NO_ADDRESS` in there in the first place, without warning." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T05:43:35.063", "Id": "463066", "Score": "0", "body": "@MaartenBodewes What do you recommend to denote a field as empty? ([Java's Optional isn't meant to be used for class fields](https://stackoverflow.com/a/24564612/507629))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T11:44:11.620", "Id": "463098", "Score": "0", "body": "We can simplify `getAge()` further to `max(age, 0)`. In some languages, such as C# (but sadly [Java's apparently not one of them](https://stackoverflow.com/questions/5223044/is-there-a-java-equivalent-to-null-coalescing-operator-in-c)), we could simplify `getAddress()` to `address ?? NO_ADDRESS`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T11:45:41.457", "Id": "463099", "Score": "0", "body": "@MaartenBodewes Interesting. Is this Java-specific, or do lots of languages' communities have a debate like this? I mostly work in Python, where ternary operators are more legible, which might be part of why I'm unfamiliar with opposition to them. (The order of the arguments is different, which is annoying when transitioning languages, but that's another story.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:46:23.677", "Id": "463129", "Score": "0", "body": "Yeah, it is all about legibility. I'll try and find some pointers later..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T02:42:20.240", "Id": "236270", "ParentId": "236249", "Score": "0" } }, { "body": "<p>Someone else already discussed this, but I would get rid of the boolean members <code>hasAge</code> and <code>hasAddress</code>. They don't really provide any information that the fields themselves don't provide.</p>\n\n<p>An issue regarding the boolean flags is that you never update them, so they will be invalid once you use the setters. This is just a good demonstration of why you would be better off without them: they will eventually become inconsistent from the actual field state. </p>\n\n<p>Instead of setting the address to a string saying no address available, just set it to an empty string or null and let the caller decide how to handle it. You could also add a <code>hasAddress</code> method that checks if the string is empty/null. An empty age could be signified as -1, assigned to a constant.</p>\n\n<p>Also, instead of several different constructors, you could use the fluent builder pattern:</p>\n\n<pre><code>public class Person {\n\n private static final int EMPTY_AGE = -1;\n private static final String EMPTY_ADDRESS = \"\";\n\n private String firstName, lastName, address;\n private int age;\n\n public static class PersonBuilder {\n private String firstName = null, lastName = null, address = EMPTY_ADDRESS;\n private int age = EMPTY_AGE;\n public PersonBuilder firstName(String firstName) {\n this.firstName = firstName;\n return this;\n }\n public PersonBuilder lastName(String lastName) {\n this.lastName = lastName;\n return this;\n }\n public PersonBuilder address(String address) {\n this.address = address;\n return this;\n }\n public PersonBuilder age(int age) {\n this.age = age;\n return this;\n }\n public Person build() {\n Objects.requireNonNull(firstName);\n Objects.requireNonNull(lastName);\n return new Person(firstName, lastName, address, age);\n }\n }\n\n public static PersonBuilder builder() {\n return new PersonBuilder();\n }\n\n private Person(String firstName, String lastName, String address, int age) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.age = age;\n this.address = address;\n }\n\n public String getName() {\n return firstName + lastName;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public int getAge() {\n return age;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public void setAge(int age) {\n this.age = age;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n}\n</code></pre>\n\n<p>Now, you can build a Person like this:</p>\n\n<pre><code>Person.builder().firstName(\"John\").lastName(\"Doe\").age(25).address(\"1234 Some Road\").build();\n</code></pre>\n\n<p>This is especially helpful when the class has more fields.</p>\n\n<p>Besides being easier to read when constructing it, the builder pattern</p>\n\n<ul>\n<li>Removes the possibility of mixing up constructor fields</li>\n<li>Allows specifying the fields in any order </li>\n<li>Guarantees the Person object returned will be valid. The <code>build</code> method will refuse to construct the object when required fields are missing. (This checking could alternatively be done in Person's constructor.)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T13:26:53.280", "Id": "462958", "Score": "0", "body": "Don't use sentinel values like `-1`, `\"\"`. Arguably, you should even avoid `null`. Optional exists, and it fits the bill perfectly. What are the chances you'll use the age, forgetting that it could \"not be set\" (and poorly encoded as `-1`), and accidentally show a `-1 year old` age on the UI? Plus, what if this wasn't age, but some other value that could be negative? `OptionalInt` is a better choice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T05:02:45.067", "Id": "463059", "Score": "0", "body": "@Alexander-ReinstateMonica I completely agree, but apparently [Java's Optional is not meant to be used for class fields](https://stackoverflow.com/a/24564612/507629). It also does not implement Serializable (unlike Guava's Optional which does). I think this was a poor choice on Java's part, but it is what it is. What would you suggest to denote the field is \"empty\" given that Optional isn't meant to be used for fields?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T05:10:09.203", "Id": "463060", "Score": "0", "body": "I guess in this case, the getters could return OptionalInt or Optional<String> and that would fit in with Optional's original intended use case. Though it still feels wrong to use sentinel values at all, as you pointed out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T15:14:39.037", "Id": "463137", "Score": "0", "body": "Java's serialization mechanism was a poor choice on Java's part. It's fundamentally broken, and a consistent fountain of security vulnerabilities, so I would argue it shouldn't be used at all, ever, under any circumstances. So I don't think that's a good reason not to use Optional in args/fields." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T19:01:11.257", "Id": "463171", "Score": "0", "body": "@Alexander-ReinstateMonica you mention the Serialization problem more than once, but in some cases serialization is _required_ — clustering / load-balancing under a Tomcat application server, for example, [requires](https://tomcat.apache.org/tomcat-9.0-doc/cluster-howto.html#Cluster_Basics) all session attributes to be Serializable, and you may have reason to have a Person in the Session object… saying that serialization _\"shouldn't be used at all, ever, **under any circumstances**\"_ is a non-starter, as there exist circumstances which _require_ it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T19:03:37.757", "Id": "463172", "Score": "0", "body": "@StephanP I've never worked with Tomcat, but that seems no different from any other dependency. Isolate it, and play by its rules at the interface. Don't let an exception at your software boundary dictate your code style in the entire middle part." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T08:28:00.953", "Id": "236276", "ParentId": "236249", "Score": "7" } }, { "body": "<p>As well as a missing separator, there's a missing null check here:</p>\n\n<blockquote>\n<pre><code>public String getName() {\n return firstName + lastName;\n}\n</code></pre>\n</blockquote>\n\n<p>Don't fall into the trap of assuming that all people have a first name and a last name; some have only one of those. And some have different names in different contexts (e.g. pen-name/stage-name as well as a formal (passport) name).</p>\n\n<p>Other code may be making assumptions that first name (or last name) is a \"family name\", but that's not certain either - read <em><a href=\"https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/\" rel=\"nofollow noreferrer\">Falsehoods Programmers Believe About Names</a></em> to pick up some other assumptions that might not be true.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T17:57:21.293", "Id": "463008", "Score": "0", "body": "That's a good point. If you do assume that a first name / last name always need to be present, then create a guard within the constructor to make sure they are not `null`. And yes, Java has terrible `null` handling, this class would be much neater in Kotlin." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T20:45:34.313", "Id": "463031", "Score": "0", "body": "This is a good start but you can go a lot farther. What is Ludwig van Beethoven's last name? Is it \"van Beethoven\"? Would searching by last name for \"Beethoven\" then not find it? Is it \"Beethoven\"? If it is \"Beethoven\" then where does the \"van\" go? This notion that people have a first name and a last name that can then be concatenated to form a full name is simply false." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T20:48:17.870", "Id": "463032", "Score": "0", "body": "And what about Kim Jong-un? Kim is his first name, and also his family name; in Korea, the family name is the first name, not the last name. Is that reflected in the model? Bizarrely enough, an official of the US government referred to him as \"Chairman Un\" recently." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T17:01:25.647", "Id": "463146", "Score": "2", "body": "Yes, I ought to have linked to the [falsehoods programmers believe about names](https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/) from this answer (I complacently assumed that everybody is familiar with it, but that's obviously a falsehood itself)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T13:42:47.000", "Id": "236294", "ParentId": "236249", "Score": "1" } }, { "body": "<p>I'm adding just some thoughts to explain how I would solve the problem: assuming in the simplest scenario you have two fields <code>firstName</code> and <code>lastName</code> that must be always compiled when you create a <code>Person</code> object then the simplest way is have to have a constructor that takes them as parameters:</p>\n\n<pre><code>public class Person {\n private String firstName;\n private String lastName; \n\n public Person(String firstName, String lastName) {\n this.firstName = firstName;\n this.lastName = lastName;\n }\n //getters and setters omitted for brevity\n}\n</code></pre>\n\n<p>After you have two fields <code>address</code> and <code>age</code> that in one or more moments of the life of your objects can be null, to signal this situation to the user of your <code>Person</code> class you chose to return the values <code>\"No address defined\"</code> and 0 like the code below:</p>\n\n<blockquote>\n<pre><code>private static final String NO_ADDRESS = \"No address defined\";\npublic int getAge() {\n if (hasAge)\n return age;\n else\n return 0; //Return 0 if no age is defined\n}\npublic String getAddress() {\n if (hasAddress)\n return address;\n else\n return NO_ADDRESS;\n}\n</code></pre>\n</blockquote>\n\n<p>I disagree with your choice because the user of your class <code>Person</code> is obliged to know the value of String <code>\"No address defined\"</code> to identify which address is valid and which not with <code>String.equals</code> method and for me 0 is a valid value for <code>age</code>.\nMy possible solution is the use of <code>Optional</code> and <code>OptionalInt</code> for address and age like my code below:</p>\n\n<pre><code>public class Person {\n private String firstName;\n private String lastName; \n private String address;\n private Integer age; //&lt;-- better use int age, see note for details\n\n public Person(String firstName, String lastName) {\n this.firstName = firstName;\n this.lastName = lastName;\n }\n\n public Optional&lt;String&gt; getAddress() {\n return Optional.ofNullable(address);\n }\n\n public OptionalInt getAge() {\n return OptionalInt.of(age);\n }\n\n //others setters and getters omitted for brevity\n}\n</code></pre>\n\n<p>In this way the user of your class <code>Person</code> is forced to check if the fields address and age are set before using them:</p>\n\n<pre><code>Person person = new Person(\"firstName\", \"lastName\");\nperson.setAddress(\"address\");\nperson.setAge(10);\nOptional&lt;String&gt; optAddress = person.getAddress();\nif (optAddress.isPresent()) {\n System.out.println(optAddress.get());\n}\nOptionalInt optAge = person.getAge();\nif (optAge.isPresent()) {\n System.out.println(optAge.getAsInt());\n}\n</code></pre>\n\n<p>Note: following @Nathan's comment below, instead of use Integer for age field it is better to use directly int to avoid boxing and unboxing operations.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T05:46:20.403", "Id": "463067", "Score": "1", "body": "OptionalInt is meant to be used with a primitive int to avoid autoboxing and unboxing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T09:17:39.673", "Id": "463084", "Score": "0", "body": "@Nathan Thanks, I included your comment in my answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T17:15:32.800", "Id": "236304", "ParentId": "236249", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T19:38:58.023", "Id": "236249", "Score": "8", "Tags": [ "java", "object-oriented" ], "Title": "Class that defines a person" }
236249
<p>This code maps a function over a dataset in parallel <em>in a monitored fashion</em>, and returns the result in the variable out.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np from tqdm import tqdm, trange from joblib import Parallel, delayed import multiprocessing import math n_jobs = multiprocessing.cpu_count() df = pd.DataFrame(np.random.randn(10000, 200)) chunk_size = 32 n_chunks = min(len(df), int(math.ceil(len(df) / chunk_size))) def func(x): # do something return x+1 out = Parallel(n_jobs=n_jobs, verbose=0)( delayed(func)( df[i * chunk_size: (i + 1) * chunk_size] ) for i in trange(n_chunks)) </code></pre> <p>What are the pros and cons of this approach? Are there better approaches? What if I needed to map in-place?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T20:37:54.110", "Id": "236250", "Score": "4", "Tags": [ "python", "python-3.x", "pandas", "multiprocessing" ], "Title": "Monitored parallel mapping across a Pandas dataframe" }
236250
<p>I've written a MP3 tag editor, using Kivy and Python but since last virtual environment build my code ui is working very poorly. The UI responds very slowly (almost 10 seconds to reflect any action) which makes the app unusable. I've tried previous build of the app but it is also not working properly. I'm using latest version of Python and Kivy.</p> <p>I'm not able to find the issue here. Please help finding the issue and rectifying it.</p> <pre><code>#!/usr/bin/python3 """ Python: Created by Naman Jain on 12-01-2018 File: music_file_tag_editor GUI Tag editor for MP3 file. It supports Tag editing using mutagen library, renaming the file based on its ID3 attributes, changing album art using local file system or using Internet search or removing it completely. It also supports changing cover art of all MP3 files with same album and album artist as the opened file. """ # ## PyLint custom options: ## # # pylint: disable=too-many-instance-attributes # pylint: disable=c-extension-no-member # pylint: disable=no-name-in-module import os import pathlib import shutil import tempfile from contextlib import suppress, contextmanager from functools import partial from glob import glob from typing import AnyStr, Tuple from urllib.parse import urlunparse, quote, urlencode import win32con import win32gui # noinspection PyProtectedMember from kivy.app import App from kivy.core.window import Window from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.checkbox import CheckBox from kivy.uix.image import Image from kivy.uix.label import Label from kivy.uix.popup import Popup from kivy.uix.switch import Switch from kivy.uix.textinput import TextInput from kivy.uix.widget import Widget from mutagen import id3, File from mutagen.easyid3 import EasyID3 # noinspection PyProtectedMember from mutagen.id3 import APIC, ID3 from mutagen.mp3 import MP3 from win32ui import CreateFileDialog from helper_classes import Constants, PymLabel, CustomSpinner class TagEditor(App, BoxLayout): """ Class for tag editor app """ # class attributes FILE_OPENED = False # to store state of the opened file def __init__(self, **kwargs): """ :param kwargs: :type kwargs: """ kwargs['orientation'] = 'vertical' super().__init__(**kwargs) self.constants = Constants() self.title = self.constants.window_title self.icon = os.path.join('extras', 'images', 'app_icon.ico') # layouts self.main_layout = BoxLayout(orientation='horizontal') self.music_file_info_layout = BoxLayout(orientation='vertical', size_hint=(0.5, 1), pos_hint={'top': True, 'center_x': True}) self.music_file_tag_layout = BoxLayout(orientation='vertical', size_hint=(0.5, 1)) self.image_cover_art = Image(source=self.constants.default_tag_cover) self.label_file_name = PymLabel('Open A File') self.button_album_art_change = Button(text="Options", size_hint=(0.25, 0.1), pos_hint={'center_x': 0.5}, background_color=(255, 0, 0, 0.4), background_normal='') for widget in (self.image_cover_art, self.button_album_art_change, self.label_file_name): self.music_file_info_layout.add_widget(widget) self.text_input_dict = {key: TextInput(hint_text_color=[26, 12, 232, 1], hint_text=self.constants[key], multiline=False, font_size='20sp', background_color=(0, 0, 255, 0.8)) for key in self.constants} # checkbox function which will be called when checkbox is selected def _on_checkbox_select(_widget: Widget, _): if not TagEditor.FILE_OPENED: self._return_popup(title="No File opened", content=Label(text="No File Opened"), ) \ .open() self.checkbox_layout = BoxLayout(orientation='horizontal') self.switch_layout = BoxLayout(orientation='horizontal') self.checkbox_all_albums_art = CheckBox(active=False, color=[0, 0, 0, 1]) self.checkbox_all_albums_art.bind(active=_on_checkbox_select) self.checkbox_all_albums_art.disabled = True # switch for toggling full screen def _on_switch_select(_widget: Switch, _): if _widget.active: win32gui.ShowWindow(win32gui.FindWindow(None, self.title), win32con.SW_MAXIMIZE) else: win32gui.ShowWindow(win32gui.FindWindow(None, self.title), win32con.SW_NORMAL) # switch for applying album art to all songs of the same album def _label_select(_widget: Widget, _): self.checkbox_all_albums_art.active = not self.checkbox_all_albums_art.active label_all = PymLabel(text="Apply this album art to all songs in the album", markup=True) label_all.bind(on_ref_press=_label_select) for widget in label_all, self.checkbox_all_albums_art: self.checkbox_layout.add_widget(widget) self.button_open = Button(text='Open', background_color=(255, 0, 0, 1), background_normal='') self.button_save = Button(text='Save', background_color=(255, 0, 0, 1), background_normal='') self.button_reset = Button(text='Reset', background_color=(255, 0, 0, 1), background_normal='') self.naming_opt = "no-rename" def _naming_option_selector(_, selected_text): """ binding function for the spinner, which assign the selected text to 'self.naming_option' :param _: :type _: :param selected_text: the option selected by the user in the Spinner :type selected_text: str """ self.naming_opt = selected_text self.naming_option_spinner = CustomSpinner(text=self.constants.rename[self.naming_opt], values=[self.constants.rename[key] for key in self.constants.rename]) self.naming_option_spinner.bind(text=_naming_option_selector) # Button's Layout self.layout_button = BoxLayout(orientation='horizontal') for widget in self.button_open, self.button_save, self.button_reset: self.layout_button.add_widget(widget) # button bindings for button, binding in zip((self.button_open, self.button_save, self.button_reset, self.button_album_art_change), (self.file_open, self.save_file, self.reset_widgets, self.album_art_manager)): button.bind(on_press=binding) self.file_name, self.file_path, self.file_extension = str(), list(), str() self.to_delete = tempfile.TemporaryDirectory() def __repr__(self) -&gt; str: return "TagEditor Class" @staticmethod @contextmanager def saving(file: File): """ calls save method on the object :param file: file to be saved :type file: File """ yield file file.save(v2_version=3, v1=2) def _return_popup(self, title: AnyStr, content: Widget, size: Tuple = (500, 100), size_hint=(None, None)) -&gt; Popup: """ This method is for creating a unified Popup which will have a similar design throughout the application :param title: Title of the popup :type title: str :param content: content to be put in the popup :type content: Widget :param size: size of the Popup :type size: tuple :param size_hint: size hint of the Popup wrt to the parent :type size_hint: tuple; default=(500, 100) :return: the generated Popup :rtype: Popup """ popup = Popup(title=f"{self.constants.name} - {title}", content=content, size=size, size_hint=size_hint, title_align='center') # popup_background = ModalView() # popup_background.add_widget(Image(source=self.constants.rocket_image)) # popup.background = self.constants.rocket_image popup.background_color = [0, 255, 220, 0.9] popup.title_size = 18 # size in sp 255 0 120 popup.title_color = [1, 255, 0, 1] # rgba (pink) popup.separator_color = [1, 0, 255, 255] # rgba (cyan) popup.separator_height = 5 return popup def _on_file_drop(self, _, file_path: bytes): """ :param _: :type _: kivy.core.window.window_sdl2.WindowSDL :param file_path: :type file_path: bytes """ self.file_open(None, file_path=file_path.decode()) def build(self): """ building the App :return: the created window :rtype: TagEditor """ # adding support for drag and drop file Window.bind(on_dropfile=self._on_file_drop) self.icon = self.constants.default_tag_cover # window background color # noinspection SpellCheckingInspection Window.clearcolor = (255, 215, 0, 1) for key in self.text_input_dict: self.music_file_tag_layout.add_widget(widget=self.text_input_dict[key]) for widget in self.naming_option_spinner, self.checkbox_layout, self.layout_button: self.music_file_tag_layout.add_widget(widget) for widget in self.music_file_info_layout, self.music_file_tag_layout: self.main_layout.add_widget(widget) self.add_widget(self.main_layout) return self def reset_widgets(self, _): """ Reset all field to original state """ self.label_file_name.pretty_text = 'Open A File' self.title = self.constants.window_title for key in self.text_input_dict: self.text_input_dict[key].text = '' if os.path.exists(os.path.join(os.getcwd(), self.constants.default_tag_cover)): self.image_cover_art.source = self.constants.default_tag_cover self.image_cover_art.reload() else: self.image_cover_art.clear_widgets() TagEditor.FILE_OPENED = False self.checkbox_all_albums_art.disabled = True self.to_delete.cleanup() self.to_delete = tempfile.TemporaryDirectory() def file_open(self, _, file_path=None) -&gt; None: """ Opens a Windows file open dialog. It will use '.mp3' extension for file types :param file_path: :type file_path: :param _: :type _: :return: :rtype: """ self.reset_widgets(None) self.checkbox_all_albums_art.disabled = False # True, None for fileopen and False, File_Name for file save dialog if not file_path: file_dialog = CreateFileDialog(True, ".mp3", None, 0, "MP3 Files (*.mp3)|*.mp3", None) file_dialog.DoModal() self.file_name, self.file_path, self.file_extension = \ file_dialog.GetFileName(), file_dialog.GetPathNames()[0], file_dialog.GetFileExt() else: file_path = file_path self.file_name, self.file_path, self.file_extension = \ os.path.basename(file_path), os.path.dirname(file_path), \ os.path.splitext(file_path)[-1] # if no file is selected or cancel button is pressed if any([self.file_name == '', self.file_path == [], self.file_extension == '']): # if file open operation is cancelled return try: audio_file, mp3_file = EasyID3(self.file_path), MP3(self.file_path) except id3.ID3NoHeaderError: # adding id3 header tags if the file has none with self.saving(File(self.file_path, easy=True)) as file: file.add_tags() audio_file, mp3_file = EasyID3(self.file_path), MP3(self.file_path) if any(['APIC:Cover' in mp3_file, 'APIC:' in mp3_file]): with open(os.path.join(self.to_delete.name, 'image.jpeg'), 'wb') as img: img.write(mp3_file['APIC:' if 'APIC:' in mp3_file else 'APIC:Cover'].data) self.image_cover_art.source = os.path.join(self.to_delete.name, 'image.jpeg') self.image_cover_art.reload() self.title += f" -&gt; {self.file_path}" self.label_file_name.pretty_text = self.file_name # filling the text field with the metadata of the song with suppress(KeyError): for key in self.text_input_dict: if not audio_file.get(key, self.text_input_dict[key].text) == "": self.text_input_dict[key].text = \ audio_file.get(key, self.text_input_dict[key].text)[0] TagEditor.FILE_OPENED = True def save_file(self, _: Button) -&gt; None: """ Save file and rename it according to the option selected by the user. :param _: :type _: :return: :rtype: """ if not TagEditor.FILE_OPENED: self._return_popup(title='No file opened', content=Label(text="Please open a file..."), ).open() return file = None to_return = False save_file_content = f"Saving {self.text_input_dict['title']}" saving_file = self._return_popup(title="Saving File", content=Label(text=save_file_content)) try: file = MP3(self.file_path, ID3=ID3) except IndexError: self._return_popup(title="Error", content=Label(text='Please Open a file....'), size=(200, 200)).open() to_return = True with self.saving(file) as file: if to_return: return saving_file.open() with suppress(id3.error): file.delete() file.add_tags() if not self.image_cover_art.source == self.constants.default_tag_cover: with open(self.image_cover_art.source, 'rb') as album_art_file: file.tags.add(APIC(mime=f"image/{pathlib.Path(self.image_cover_art.source).suffix.strip('.')}", type=3, desc=u'Cover', encoding=1, data=album_art_file.read())) else: with suppress(KeyError): if 'APIC:' in file: file.tags.pop('APIC:') else: file.tags.pop('APIC:Cover') self.checkbox_all_albums_art.active = False with self.saving(EasyID3(self.file_path)) as music_file: # adding tags to the file for tag in self.text_input_dict: music_file[tag] = self.text_input_dict[tag].text if not self.image_cover_art.source == self.constants.default_tag_cover: with open(self.image_cover_art.source, 'rb') as album_art_file: file.tags.add(APIC(mime=f"image/{pathlib.Path(self.image_cover_art.source).suffix.strip('.')}", type=3, desc=u'Cover', encoding=1, data=album_art_file.read())) else: with suppress(KeyError): if 'APIC:' in file: file.tags.pop('APIC:') else: file.tags.pop('APIC:Cover') self.checkbox_all_albums_art.active = False self.file_name = self.file_path # if the option is not "no-rename": "Don't Rename" if self.naming_opt != list(self.constants.rename.keys())[0]: artist = music_file['albumartist'][0] album = music_file['album'][0] title = music_file['title'][0] # renaming the modified file with name according to the chosen option by the user self.file_name = self.naming_opt.format(Artist=artist, Album=album, Title=title) self.file_name = rf"{os.path.dirname(self.file_path)}\{self.file_name}.mp3" try: os.rename(self.file_path, self.file_name) except FileExistsError: os.remove(self.file_name) os.rename(self.file_path, self.file_name) self.file_path = self.file_name saving_file.dismiss() self._return_popup(title='MP3 File Saved', content=Label(text=f'{self.file_name} Saved'), size=(800, 200)).open() self.label_file_name.pretty_text = os.path.basename(self.file_name) TagEditor.FILE_OPENED = True if self.checkbox_all_albums_art.active: try: self.album_art_all_songs(self.text_input_dict['album'].text, self.text_input_dict['albumartist'].text) except AssertionError: self._return_popup("Missing Fields", content=PymLabel(text="Album and Album Artist is Missing")) # resetting the widgets after saving the file self.reset_widgets(None) def album_art_manager(self, _: Button) -&gt; None: """ Function to grab the album art; it will offer three choice, Download from Internet or Pick from local filesystem or Remove the cover art :param _: :type _: :return: :rtype: """ if not TagEditor.FILE_OPENED: self._return_popup(title='No file opened', content=Label(text="Please open a file...")).open() return # button for the popup button_local_picker = Button(text='Local Filesystem', background_color=(255, 0, 0, 1), background_normal='') button_google_search = Button(text='Search With Google', background_color=(255, 0, 0, 1), background_normal='') button_art_remove = Button(text='Remove Album Art', background_color=(255, 0, 0, 1), background_normal='') button_extract_art = Button(text='Extract The Album Art', background_color=(255, 0, 0, 1), background_normal='') art_button_layout = BoxLayout(orientation='vertical') art_picker = self._return_popup(title='Select Album Art', content=art_button_layout, size=(200, 200)) # binding function to buttons in the popup for widget, callback in zip((button_google_search, button_local_picker, button_art_remove, button_extract_art), (self.album_art_google, self.album_art_local, self.album_art_remove, self.album_art_extract)): widget.bind(on_press=partial(callback, art_picker=art_picker)) art_button_layout.add_widget(widget) art_picker.open() def album_art_local(self, _: Button, art_picker: Popup, downloaded=False) -&gt; None: """ Allows to selected the album art from the local file system. Opens the file dialog for selecting jpeg or png or jpg file It will open user's default Downloads folder in case the file is downloaded from the internet :param art_picker: :type art_picker: Popup :param _: :type _: :param downloaded: this parameter decides open dialog in last opened folder if 'False' otherwise opens in User's Download folder :type downloaded: Boolean """ art_picker.dismiss() file_types = "JPEG File, jpg File, PNG File | *.jpg; *.jpeg; *.png; | GIF File | *.gif; |" # True for fileopen and False for filesave dialog # opening file dialog in Downloads folder if the image was searched online file_dialog = CreateFileDialog(True, os.path.join(os.getenv('USERPROFILE', 'Downloads')) if downloaded else None, None, 0, file_types, None) file_dialog.DoModal() # assigning the mp3 cover art widget's source to selected image path if not file_dialog.GetPathNames()[0] == "": self.image_cover_art.source = file_dialog.GetPathNames()[0] self.image_cover_art.reload() def album_art_google(self, _: Button, art_picker: Popup) -&gt; None: """ this method will open the browser (default Google Chrome) and search for the album art... :param art_picker: :type art_picker: Popup :param _: :type _: Button """ art_picker.dismiss() if self.text_input_dict["album"].text == "": self._return_popup(title='Empty Fields', content=Label(text="Please fill Album and Artist field to perform " "an auto search of album art")).open() return # Google as_q -&gt; advance search query; tbm=isch -&gt; image search; image size = 500*500 search_url = urlunparse(('https', 'www.google.co.in', quote('search'), '', urlencode({'tbm': 'isch', 'tbs': 'isz:ex,iszw:500,iszh:500', 'as_q': f"{self.text_input_dict['albumartist'].text} " f"{self.text_input_dict['album'].text} " f"album art"}), '')) # open the default web browser to let the user download the image manually import webbrowser webbrowser.open(search_url) self.album_art_local(_, downloaded=True, art_picker=art_picker) def album_art_remove(self, _: Button, art_picker: Popup) -&gt; None: """ Function for removing the album art from the MP3 File :param art_picker: :type art_picker: Popup :param _: :type _: Button """ art_picker.dismiss() file = MP3(self.file_path, ID3=ID3) self.image_cover_art.source = self.constants.default_tag_cover try: file.pop('APIC:Cover') except KeyError: with suppress(KeyError): file.pop('APIC:') finally: self.image_cover_art.reload() def album_art_extract(self, _: Button, art_picker: Popup) -&gt; None: """ Extracting Album art and saving to disc :param art_picker: :type art_picker: Popup :param _: :type _: Button """ art_picker.dismiss() file_dialog = CreateFileDialog(False, None, "album_art.jpeg", 0, "*.jpeg| JPEG File", None) file_dialog.DoModal() file_path = file_dialog.GetPathNames() shutil.copy(self.image_cover_art.source, file_path[0]) def album_art_all_songs(self, album: AnyStr, album_artist: AnyStr) -&gt; None: """ Apply album art to all songs of the same album and artist :param album: the album name which album art has to be changed :type album: str :param album_artist: the album artist name which album art has to be changed :type album_artist: str """ assert not album == "" and not album_artist == "" for file_name in glob(f"{os.path.dirname(self.file_path[0])}/*.mp3"): music_file = EasyID3(file_name) if music_file['album'][0] == album and music_file['albumartist'][0] == album_artist: with self.saving(MP3(file_name)) as mp3_file: with open(self.image_cover_art.source, 'rb') as alb_art: mp3_file.tags.add(APIC(mime=f'image/{pathlib.Path(self.image_cover_art.source).suffix}', type=3, desc=u'Cover', data=alb_art.read(), encoding=1)) def on_stop(self): """ this will be called when the app will exit and it will delete any temporary directory created """ if self.to_delete is not None: self.to_delete.cleanup() super().on_stop() def main(): """ Main Function """ TagEditor().run() </code></pre> <p>Please visit the app github repo as it is divided into four file as I cannot paste the whole code here.</p> <p><a href="https://github.com/24Naman/PyMTag" rel="nofollow noreferrer">https://github.com/24Naman/PyMTag</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T21:18:18.857", "Id": "236252", "Score": "1", "Tags": [ "python", "python-3.x", "gui", "kivy" ], "Title": "Python Kivy code working Poorly" }
236252
<p>I am trying to build a generic query handler using the <a href="https://github.com/jbogard/MediatR" rel="nofollow noreferrer">MediatR</a> (v8) library. Let's jump to the code: First of all I have an abstract query class like this:</p> <pre><code>public abstract class Query&lt;TQueryResult&gt; : IRequest&lt;TQueryResult&gt; { public Guid Id { get; } = Guid.NewGuid(); public DateTime Timestamp { get; } protected Query() { Timestamp = DateTime.Now; } } </code></pre> <p>From the corresponding query handler I would like to return a <code>Result</code> wrapper object, which looks as the following:</p> <pre><code>public class Result&lt;T&gt; { public T Payload { get; } public string FailureReason { get; } public bool IsSuccess =&gt; FailureReason == null; public Result(T payload) { Payload = payload; } public Result(string failureReason) { FailureReason = failureReason; } public static Result&lt;T&gt; Success(T payload) =&gt; new Result&lt;T&gt;(payload); public static Result&lt;T&gt; Failure(string reason) =&gt; new Result&lt;T&gt;(reason); public static implicit operator bool(Result&lt;T&gt; result) =&gt; result.IsSuccess; } </code></pre> <p>And last but not least, lets see the query handler:</p> <pre><code>public abstract class AbstractQueryHandler&lt;TQuery, TQueryResult, TResultValue&gt; : IRequestHandler&lt;TQuery, TQueryResult&gt; where TQuery : Query&lt;TQueryResult&gt; where TQueryResult : class { public Task&lt;TQueryResult&gt; Handle(TQuery request, CancellationToken cancellationToken) { try { return HandleQuery(request); } catch (Exception e) { return Task.FromResult(Result&lt;TResultValue&gt;.Failure(GetFailureMessage(e)) as TQueryResult); } } public abstract Task&lt;TQueryResult&gt; HandleQuery(TQuery request); private static string GetFailureMessage(Exception e) { return "There was an error while executing query: \r\n" + e.Message; } } </code></pre> <p>To be honest I am not pleased with this solution due to the three type parameters I have in the query handler. It might be possible to extract one from another using reflection but I think that is not the proper and right approach for this. I introduced <code>TResultValue</code> in order to make the catch part of the code working so use it as a generic type in my created error <code>Result</code> wrapper object. Let's see some corresponding tests to reveal my concerns regarding. First lets see the Query and the query handler in the production code:</p> <pre><code>public class GetAllProductsQuery : Query&lt;Result&lt;IEnumerable&lt;ProductDto&gt;&gt;&gt; { } public class GetAllProductsQueryHandler : AbstractQueryHandler&lt;GetAllProductsQuery, Result&lt;IEnumerable&lt;ProductDto&gt;&gt;, IEnumerable&lt;ProductDto&gt;&gt; { private readonly IProductEntityDao _productEntityDao; public GetAllProductsQueryHandler(IProductEntityDao productEntityDao) { _productEntityDao = productEntityDao; } public override async Task&lt;Result&lt;IEnumerable&lt;ProductDto&gt;&gt;&gt; HandleQuery(GetAllProductsQuery request) { var products = await _productEntityDao.GetAllAsync(); return Result&lt;IEnumerable&lt;ProductDto&gt;&gt;.Success(products); } } </code></pre> <p>And then the test:</p> <pre><code> [Fact] public async Task GivenSingleProduct_thenGetAllProductsQuerySend_thenReturnsSingleProduct() { await AddToDbContextAsync(ProductFakes.ProductWithAllPropsFilled1); var result = await SendAsync(new GetAllProductsQuery()); Check.That(result.IsSuccess).IsTrue(); Check.That(result.Payload).CountIs(1); } </code></pre> <p>where <code>SendAsync&lt;T&gt;</code> looks as the following:</p> <pre><code>public Task&lt;TResponse&gt; SendAsync&lt;TResponse&gt;(IRequest&lt;TResponse&gt; request) { var mediator = Provider.GetService&lt;IMediator&gt;(); return mediator.Send(request); } </code></pre> <p>As you can see in the <code>GetAllProductsQueryHandler</code> there is some kind of duplication when declaring the three types, namely <code>&lt;GetAllProductsQuery, Result&lt;IEnumerable&lt;ProductDto&gt;&gt;, IEnumerable&lt;ProductDto&gt;&gt;</code>. It seems really fishy to me. I also tried many other possibilities, checking articles and SO questions/answers on the internet but could not come up with a cleaner solution. I also tried using dynamic object instead of generic but I would like to have the strong type check in compiler time. So my question is: Is it possible to reduce the number of type parameters of <code>AbstractQueryHandler</code>handler to 2, resulting in a cleaner solution? Do you see any other code improvement? Thanks in advance for you help!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T21:21:24.733", "Id": "236254", "Score": "3", "Tags": [ "c#", ".net", "generics", "mediator" ], "Title": "Generic CQRS Query handler with custom return type" }
236254
<p>I recently worked on this problem that converts numbers to words. I was wondering if there is a better way to do it than mine, And I will really appreciate any reviews to my version of the solution and on how to make it better</p> <pre><code>/** * Converts a given number into words * @param {integer} , num, the number to be converted into words * @return {string} , the coverted number in words */ function numToEng(num){ let numInWords = ''; // will be using this as a number that will be reduced by 1000 let tempNum = num; const wordsForConstruction = { 0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'elleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'fourty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety', } const wordsToAdd = [ 'thousand', 'million', 'trillion', ] if(num &gt;= 0 &amp;&amp; num &lt;= 19){ return `${wordsForConstruction[num]}`; } let hundreds; let tens; let ones; for(let i = 0; tempNum; i++){ hundreds = tempNum % 1000; tempNum = (tempNum-hundreds)/1000; // construct words for hundred only if it is not a zero if(hundreds){ // If the loop runs the second time, this will add the words // thousand, million, trillion, and so on, depending on the num // of words in the wordsToAdd[] Array if(i){ numInWords = wordsToAdd[i-1] + " " + numInWords; } tens = hundreds % 100; hundreds = (hundreds - tens)/100; // construct words for tens only if it is not a zero if(tens){ // is tens is a property of the wordsforconstruction then // just pull the word from the object if(wordsForConstruction.hasOwnProperty(tens)){ numInWords = wordsForConstruction[tens] + " " + numInWords; }else{ ones = tens%10; tens = tens-ones; if(ones){ numInWords = wordsForConstruction[ones] + " " + numInWords; } numInWords = wordsForConstruction[tens] + " " + numInWords; } } if(hundreds){ numInWords = wordsForConstruction[hundreds] + " hundred " + numInWords; } } } return numInWords; } /** * Initiates the program and runs the test cases */ function main(){ const testCases = [ 0, 101, 100234, 909, 1000000, 1000, 9999999, 90909090, ] testCases.map(tCase =&gt; { console.log(); console.log(`numToEng(${tCase}) ➞ ${numToEng(tCase)}`); }) } main(); </code></pre> <p>Also if you find any bugs or issues with the solution please feel free to reply to this thanks in advance. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T22:34:59.693", "Id": "462888", "Score": "0", "body": "Well, I don't have a *billion* remarks yet, but you can consider this one maybe. Also note the differences between [short and long scales](https://en.wikipedia.org/wiki/Long_and_short_scales) (you may want to document that you are using the short scale at the very least)." } ]
[ { "body": "<p>I like how you've reduced all of the words to lists, that's the right start. </p>\n\n<p>Let's get into it: </p>\n\n<pre><code> for(let i = 0; tempNum; i++){\n</code></pre>\n\n<p>I have no idea what you've doing here, I assume when <code>tempNum===0</code> then the loop stops? </p>\n\n<p>Don't do this, it's confusing as hell.</p>\n\n<p>I'm going to suggest that you rewrite the entire thing as a recursive function or a reducing function, but if you insist on using a loop, then just make it a <code>while(true)</code> loop and add a return or a break statement to it to exit it. </p>\n\n<p>You have a lot of branching logic: </p>\n\n<pre><code> for(let i = 0; tempNum; i++){\n if(hundreds){\n if(i){\n }\n if(tens){\n if(wordsForConstruction.hasOwnProperty(tens)){\n\n }else{\n if(ones){\n }\n }\n }\n\n if(hundreds){\n }\n }\n }\n</code></pre>\n\n<p>The term to think about here is <a href=\"https://en.wikipedia.org/wiki/Cyclomatic_complexity\" rel=\"nofollow noreferrer\">cyclomatic complexity</a> keeping track of which branch the code is currently in involves holding a lot of information in your head, and then you have to run through it again for the next number etc. If you code is looking like a lot of these nested if statements, that's a code smell, and you should be doing something else. </p>\n\n<p>The real issue you have, is that you are manually writing the code to do the 'detect how many hundreds, thousands, millions', instead you you could abstract this to a map. </p>\n\n<p>What I would do is: </p>\n\n<pre><code>const powerMap = {\n \"million\": 1000000, \n \"thousand\": 1000, \n \"hundred\" : 100, \n \"rest\": 1, \n}; //And ofcourse you can extend this to billions, trillions, etc. \n</code></pre>\n\n<p>And then you can create a general abstraction to to count how many of each there are: </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const powerMap = {\n \"million\": 1000000, \n \"thousand\": 1000, \n \"hundred\" : 100, \n \"rest\": 1, \n}; //And ofcourse you can extend this to billions, trillions, etc. \n\n\nfunction getUnitCounts(value) {\n const data = Object.entries(powerMap).reduce(({value, result}, [unitName, power]) =&gt; {\n const nCount = Math.floor(value/power); \n const nRemainder = value%power; \n \n return {\n value: nRemainder, \n result: {\n ...result, \n [unitName]: nCount\n }\n } \n \n }, {\n value, \n result: {}\n }); \n \n return data.result; \n \n}\n\n\nconsole.log(getUnitCounts(20020000)); \nconsole.log(getUnitCounts(1100)); \nconsole.log(getUnitCounts(201110)); </code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Now - if you're not familar with spread syntax and Array.reduce this might seem confusing. But notice how I don't use a single <code>if</code> statement - all I'm doing is looping over a list and returning an accumulator. Once you've familiar with the odd syntax, this is easier to keep in your head. </p>\n\n<p>From the answer I've given here, it would now be a matter of converting the count of each unit into the words, and then also applying the words for 0-100 like you have. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T05:31:17.740", "Id": "236272", "ParentId": "236255", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T21:37:55.953", "Id": "236255", "Score": "4", "Tags": [ "javascript", "algorithm" ], "Title": "Converting numbers to words - JavaScript" }
236255
<p>I have designed a basic interface for a smart mirror I made. I coded it to include the time, date, and several phrases that refresh every 24 hours. The phrases are just some random quotes as examples.</p> <p>I was wondering if there were anyways I could streamline this code or even improve the layout of the interface.</p> <pre class="lang-py prettyprint-override"><code> import tkinter as tk import sys import time import calendar import random import datetime as dt from tkinter import * # Root is the name of the Tkinter Window. This is important to remember. root=tk.Tk() """ DICTIONARY PHRASES """ phrases = [" I never had a policy; I have just tried to do my very best each and every day. -- Abraham Lincoln", " There are some things you learn best in calm, and some in storm. -- Willa Cather", " If a man does his best, what else is there? -- George S. Patton"] class Clock(tk.Label): """ Class that contains the clock widget and clock refresh """ def __init__(self, parent=None, seconds=True, colon=False): """ Create and place the clock widget into the parent element It's an ordinary Label element with two additional features. """ tk.Label.__init__(self, parent) self.display_seconds = seconds if self.display_seconds: self.time = time.strftime('%I:%M:%S %p') else: self.time = time.strftime('%I:%M:%S %p').lstrip('0') self.display_time = self.time self.configure(text=self.display_time, width=11) if colon: self.blink_colon() self.after(200, self.tick) def tick(self): """ Updates the display clock every 200 milliseconds """ if self.display_seconds: new_time = time.strftime('%I:%M:%S %p') else: new_time = time.strftime('%I:%M:%S %p').lstrip('0') if new_time != self.time: self.time = new_time self.display_time = self.time self.config(text=self.display_time) self.after(200, self.tick) def blink_colon(self): """ Blink the colon every second """ if ':' in self.display_time: self.display_time = self.display_time.replace(':',' ') else: self.display_time = self.display_time.replace(' ',':',1) self.config(text=self.display_time) self.after(1000, self.blink_colon) class FullScreenApp(object): def __init__(self, master, **kwargs): self.master=master pad=3 self._geom='200x200+0+0' master.geometry("{0}x{1}+0+0".format( master.winfo_screenwidth()-pad, master.winfo_screenheight()-pad)) master.bind('&lt;Escape&gt;',self.toggle_geom) def toggle_geom(self,event): geom=self.master.winfo_geometry() print(geom,self._geom) self.master.geometry(self._geom) self._geom=geom def phrase_refresh(): new_phrase = random.choice(phrases) e.configure(text=new_phrase, wrap=650) # e is your label root.after(86400, phrase_refresh) # Delay measured in milliseconds. Currently set to 24 hours. (There are 86400 milliseconds in a day) return new_phrase # Sets background color to black root.configure(bg="black") # Removes the window bar at the top creating a truely fullscreen root.wm_attributes('-fullscreen','true') tk.Button(root, text="", bg="black", fg="black", command=lambda root=root:quit(root)).pack() #Spacer v = Label(root, text="", fg="white", bg="black") v.pack(anchor=NW) # this displays the clock known as clock1 clock1 = Clock(root) clock1.pack(anchor=NW) # This gives the clock format. clock1.configure(bg='black',fg='white',font=("helvetica",60)) # Add the date to the tkinter window w = Label(root, text=f"{dt.datetime.now():%a, %b %d %Y}", fg="white", bg="black", font=("helvetica", 30), width=16) w.pack(anchor=NW) #Spacer s = Label(root, text="", fg="white", bg="black") s.pack(anchor=NW) #Spacer p = Label(root, text="", fg="white", bg="black") p.pack(anchor=NW) # Add the phrase to the tkinter window e = Label(root, fg="white", bg="black", font=("helvetica", 17)) phrase_refresh() e.pack(anchor=NW) root.mainloop() </code></pre>
[]
[ { "body": "<p>Here are a few comments:</p>\n\n<p>Eliminate extra/unused imports</p>\n\n<p>Might be better to load quotes from a file (or from a \"Quote of the Day\" web site (RSS feed). That way you don't have to edit the source to add new ones.</p>\n\n<p>It's not necessary to make a separate Clock class. It seems to complicate things. The code below has one function on a callback timer. It \"over samples\" the time 5x per second. When the second or day (could be anything) changes, a function is called to update the time/date/phrase.</p>\n\n<p>Time format displays seconds whether display_seconds is True or False.</p>\n\n<p>class FullScreenApp isn't used.</p>\n\n<p>Here's my take on the display part. Getting quotes from a file or URL is an exercise for the reader:</p>\n\n<pre><code>import datetime\nimport random\n\nimport tkinter as tk\n\nMESSAGE_WIDTH = 400\nSHOW_SECONDS = False\nBLINK_COLON = True\n\n\"\"\" DICTIONARY PHRASES \"\"\"\nphrases = [\n \"I never had a policy; I have just tried to do my very best each and every day. -- Abraham Lincoln\",\n \"There are some things you learn best in calm, and some in storm. -- Willa Cather\",\n \"If a man does his best,\\n what else is there? -- George S. Patton\",\n \"Better to write for yourself and have no public, than to write for the public and have no self. -- Cyril Connolly\",\n \"Life is far too important a thing ever to talk seriously about. -- Oscar Wilde\",\n \"Indeed, history is nothing more than a tableau of crimes and misfortunes. -- Voltaire\",\n \"In great affairs men show themselves as they wish to be seen; in small things they show themselves as they are. -- Nicholas Chamfort\",\n \"The first step to getting the things you want out of life is this: Decide what you want. -- Ben Stein\",\n \"Life is what happens to you while you're busy making other plans. -- John Lennon\",\n \"For four-fifths of our history, our planet was populated by pond scum. -- J. W. Schopf\",\n \"History will be kind to me for I intend to write it. -- Sir Winston Churchill\",\n \"History is the version of past events that people have decided to agree upon. -- Napoleon Bonaparte\",\n \"You create your opportunities by asking for them. -- Patty Hensen\",\n \"If everyone had a dad like mine, no one would have sex tapes. -- Tina Fey\"\n ]\n\nroot = tk.Tk()\nroot.configure(bg=\"black\")\n\nprev_time = datetime.datetime(1,1,1)\n\ntime_display = tk.StringVar(root, \" \"*len(\" HH:MM:SS PM \"))\ndate_display = tk.StringVar(root, \" \"*len(\"aaa, bbb dd, YYYY\"))\nphrase_display = tk.StringVar(root, \" \"*len(max(phrases, key=len)))\nauthor_display = tk.StringVar(root, \" \"*MESSAGE_WIDTH)\n\ndef tick():\n global prev_time\n\n curr_time = datetime.datetime.now()\n\n if curr_time.second != prev_time.second:\n update_time(curr_time)\n\n if curr_time.second//15 != prev_time.second//15: # this is for testing, it makes the quote update every 15 seconds\n# if curr_time.day != prev_time.day: # normally use this one to update quote every day\n update_phrase()\n\n if curr_time.day != prev_time.day:\n update_date(curr_time)\n\n prev_time = curr_time\n\n root.after(200, tick)\n\n\ndef update_date(curr_time):\n date_display.set(f\"{curr_time:%a, %b %d, %Y}\")\n\n\ndef update_phrase():\n phrase, author = random.choice(phrases).split('--') \n phrase_display.set(phrase.strip())\n author_display.set(f\"-- {author.strip()}\")\n\n\ndef update_time(curr_time):\n # colon no colon \n fmt=[[\" %H:%M %p \", \" %H %M %p \"], # without seconds\n [\" %H:%M:%S %p \", \" %H %M %S %p \"] # with seconds\n ][SHOW_SECONDS][BLINK_COLON and curr_time.second % 2]\n\n time_display.set(f\"{curr_time:{fmt}}\")\n\n\n# Removes the window bar at the top creating a truely fullscreen\n#root.wm_attributes('-fullscreen','true')\ntk.Button(root, text=\"quit\", bg=\"black\", fg=\"red\", command=root.quit).pack()\n\n#Spacer\ntk.Label(root, text=\"\", fg=\"white\", bg=\"black\").pack()\n\n# this displays the clock known as clock\nclock = tk.Label(root, textvariable=time_display, bg='black',fg='white',font=(\"helvetica\",60))\nclock.pack()\n\n# Add the date to the tkinter window\ndate = tk.Label(root, textvariable=date_display, fg=\"white\", bg=\"black\", font=(\"helvetica\", 30), width=16)\ndate.pack()\n\n#double height Spacer\ntk.Label(root, text=\"\\n\\n\", fg=\"white\", bg=\"black\").pack()\n\n# Add the phrase to the tkinter window\ntext = tk.Message(root, textvariable=phrase_display, fg=\"white\", bg=\"black\", font=(\"helvetica\", 17), width=400, justify=\"left\")\ntext.pack()\n\nauthor = tk.Message(root, textvariable=author_display, fg=\"white\", bg=\"black\", font=(\"helvetica\", 17), width=400, justify='right', anchor='e')\nauthor.pack()\n\n#Spacer\ntk.Label(root, text=\"\", fg=\"white\", bg=\"black\").pack()\n\n# starts the clock\ntick()\n\nroot.mainloop()\n\n# In some developement environments root.quit doesn't fully destroy the application; hence\n# the call to root.destroy(). But clicking the close button (the 'X') on a window does destroy\n# the application, so calling root.destroy() raises a TclError for trying to destroy it a\n# second time. This quiets the error message. \ntry:\n root.destroy()\nexcept tk.TclError:\n pass\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T12:54:12.877", "Id": "463604", "Score": "0", "body": "Sweet! Thank you for the suggestion! I will definitely look into it " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T16:32:04.873", "Id": "463635", "Score": "0", "body": "Didn't know the format specifier gets passed along to the datetime object like this. This is shorter (and more readable) than writing `curr_time.strftime(\"%a, %b %d, %Y\")`, nice!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T18:36:23.620", "Id": "463646", "Score": "0", "body": "@Graipher, f-strings call the `__format__(self, format_spec)` method. So it works with anything that defines that method. User defined classes can define their own format_spec." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T19:10:14.263", "Id": "463649", "Score": "0", "body": "@RootTwo: Yeah, and I even read somewhere recently that `datetime` just implements `__format__`, I just never connected the dots and realized that this means I can get rid of that `strfmt`..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T06:41:57.363", "Id": "236485", "ParentId": "236257", "Score": "3" } }, { "body": "<p>Congratulations on writing a tk program. They can be hard.</p>\n\n<p>Moving code out of the top level is an improvement you can in any program. Top level code creates global variables, makes it unclear what might be used below, and so on. You could just do this:</p>\n\n<pre><code>def main():\n # Sets background color to black\n root.configure(bg=\"black\")\n ...\n except tk.TclError:\n pass\n\nmain()\n</code></pre>\n\n<p>It may seem minor, but it makes it easier to see that <code>root</code>, <code>time_display</code> and others are global, but that <code>author</code> is not.</p>\n\n<p>One fix at a time. Keep hacking! Keep notes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T12:55:29.343", "Id": "463605", "Score": "0", "body": "Okay, I will definitely be trying that! Anything to make my code better and more efficient." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T02:36:08.527", "Id": "236508", "ParentId": "236257", "Score": "3" } }, { "body": "<p>Good start but a few things should be cleaned up.</p>\n\n<p>Try to follow a standard. Preferably PEP8. You have extra spacing between <code>=</code> and no spacing between <code>,</code> in places and its messy.</p>\n\n<ol>\n<li><p>delete <code>from tkinter import *</code> this is for 2 reason. The first is you are already doing <code>import tkinter as tk</code> so you do not need a 2nd import of tkinter. Two <code>import *</code> can cause problems if imported names overlap and get overwritten.</p></li>\n<li><p>Remove imports you are not using. IE: calenddar, sys</p></li>\n<li><p>Fix clean up formatting to follow PEP8. Single spaces between methods double spaces between functions/class and so on.</p></li>\n<li><p>Remove unneeded/redundant comments. Comments should be reserver for explaining things that are not obvious in the code. </p></li>\n<li><p>You write you <code>tick</code> code twice. One in <code>__init__</code> and once in <code>tick</code>. You can remove the instance in <code>__init__</code> and simply call tick right away while adding a default value for <code>self.time</code> and <code>self.display_time</code> in the init.</p></li>\n<li><p>You use <code>200</code> milliseconds in your after statement. This is 5 times more than you need. 1 second intervals will suffice. There is no need to call the function 5 times more than is needed.</p></li>\n<li><p>The class <code>FullScreenApp</code> is never used. So either implement it somewhere or remove it.</p></li>\n<li><p>Your <code>return</code> in <code>phrase_refresher</code> does nothing for you. Its returning to a call with no variable assignment and then its returning to itself forever after that. You can remove the return.</p></li>\n<li><p>Your quit button does not need a lambda. You can save a reference to quit.</p></li>\n<li><p>Your quit button has no word and is the same color as background. This will make it very had for someone to click it :D</p></li>\n<li><p>You are already inheriting from <code>tk.Label</code> so why not do the same for the root window?</p></li>\n<li><p>Lastly you do not need spacer labels. You can use <code>padx</code> and <code>pady</code> to determine spacing between widgets.</p></li>\n</ol>\n\n<p>See below reworked example. Let me know if you have any questions.</p>\n\n<pre><code>import tkinter as tk\nimport datetime as dt\nimport random\nimport time\n\nphrases = [\" I never had a policy; I have just tried to do my very best each and every day. -- Abraham Lincoln\",\n \" There are some things you learn best in calm, and some in storm. -- Willa Cather\",\n \" If a man does his best, what else is there? -- George S. Patton\"]\n\n\nclass Clock(tk.Label):\n \"\"\" Class that contains the clock widget and clock refresh \"\"\"\n\n def __init__(self, parent=None, seconds=True, colon=False):\n \"\"\"\n Create and place the clock widget into the parent element\n It's an ordinary Label element with two additional features.\n \"\"\"\n tk.Label.__init__(self, parent, width=11)\n self.display_seconds = seconds\n self.time = None\n if colon:\n self.blink_colon()\n self.tick()\n\n def tick(self):\n \"\"\" Updates the display clock every 200 milliseconds \"\"\"\n if self.display_seconds:\n new_time = time.strftime('%I:%M:%S %p')\n else:\n new_time = time.strftime('%I:%M:%S %p').lstrip('0')\n print(new_time)\n if self.time is not None:\n if new_time != self.time:\n self.time = new_time\n self.display_time = self.time\n self.config(text=self.display_time)\n else:\n self.time = new_time\n self.after(1000, self.tick)\n\n def blink_colon(self):\n \"\"\" Blink the colon every second \"\"\"\n if ':' in self.display_time:\n self.display_time = self.display_time.replace(':', ' ')\n else:\n self.display_time = self.display_time.replace(' ', ':', 1)\n self.config(text=self.display_time)\n self.after(1000, self.blink_colon)\n\n\nclass App(tk.Tk):\n def __init__(self):\n super().__init__()\n self.configure(bg=\"black\")\n self.wm_attributes('-fullscreen', 'true')\n tk.Button(self, text=\"Quit\", bg=\"black\", fg=\"white\", command=self.quit).pack()\n\n clock1 = Clock(self)\n clock1.configure(bg='black', fg='white', font=(\"helvetica\", 60))\n\n w = tk.Label(self, text=f\"{dt.datetime.now():%a, %b %d %Y}\",\n fg=\"white\", bg=\"black\", font=(\"helvetica\", 30), width=16)\n clock1.pack(anchor='nw', pady=(25, 0))\n w.pack(anchor='nw', pady=(0, 30))\n\n self.e = tk.Label(self, fg=\"white\", bg=\"black\", font=(\"helvetica\", 17))\n self.phrase_refresh()\n self.e.pack(anchor='nw')\n\n def phrase_refresh(self):\n new_phrase = random.choice(phrases)\n self.e.configure(text=new_phrase, wrap=650)\n self.after(86400, self.phrase_refresh)\n\n\nApp().mainloop()\n</code></pre>\n\n<p>Lastly I am not sure if you wanted to have the timer at the top left. Judging by the fact you fullscreen I am guessing you want it centered. For this I would prefer to use <code>grid()</code> over <code>pack()</code> as grid allows us to set weights for rows and columns making it IMO easier to center everything.</p>\n\n<p>See this example:</p>\n\n<pre><code>import tkinter as tk\nimport datetime as dt\nimport random\nimport time\n\n\nphrases = [\"I never had a policy; I have just tried to do my very best each and every day. -- Abraham Lincoln\",\n \"There are some things you learn best in calm, and some in storm. -- Willa Cather\",\n \"If a man does his best, what else is there? -- George S. Patton\"]\n\n\nclass Clock(tk.Label):\n \"\"\" Class that contains the clock widget and clock refresh \"\"\"\n def __init__(self, parent=None, seconds=True, colon=False):\n \"\"\"\n Create and place the clock widget into the parent element\n It's an ordinary Label element with two additional features.\n \"\"\"\n tk.Label.__init__(self, parent, width=11)\n self.display_seconds = seconds\n self.time = None\n if colon:\n self.blink_colon()\n self.tick()\n\n def tick(self):\n \"\"\" Updates the display clock every 200 milliseconds \"\"\"\n if self.display_seconds:\n new_time = time.strftime('%I:%M:%S %p')\n else:\n new_time = time.strftime('%I:%M:%S %p').lstrip('0')\n print(new_time)\n if self.time is not None:\n if new_time != self.time:\n self.time = new_time\n self.display_time = self.time\n self.config(text=self.display_time)\n else:\n self.time = new_time\n self.after(1000, self.tick)\n\n def blink_colon(self):\n \"\"\" Blink the colon every second \"\"\"\n if ':' in self.display_time:\n self.display_time = self.display_time.replace(':', ' ')\n else:\n self.display_time = self.display_time.replace(' ', ':', 1)\n self.config(text=self.display_time)\n self.after(1000, self.blink_colon)\n\n\nclass App(tk.Tk):\n def __init__(self):\n super().__init__()\n self.configure(bg=\"black\")\n self.wm_attributes('-fullscreen', 'true')\n self.columnconfigure(0, weight=1)\n self.rowconfigure(1, weight=1)\n\n tk.Button(self, text=\"Quit\", bg=\"black\", fg=\"white\", command=self.quit).grid(row=0, column=0)\n\n frame = tk.Frame(self, bg=\"black\")\n frame.grid(row=1, column=0)\n\n clock1 = Clock(frame)\n clock1.configure(bg='black', fg='white', font=(\"helvetica\", 60))\n\n w = tk.Label(frame, text=f\"{dt.datetime.now():%a, %b %d %Y}\",\n fg=\"white\", bg=\"black\", font=(\"helvetica\", 30), width=16)\n clock1.grid(row=2, column=0, pady=(25, 0))\n w.grid(row=3, column=0, pady=(0, 30))\n\n self.e = tk.Label(frame, fg=\"white\", bg=\"black\", font=(\"helvetica\", 17))\n self.phrase_refresh()\n self.e.grid(row=6, column=0)\n\n def phrase_refresh(self):\n new_phrase = random.choice(phrases)\n self.e.configure(text=new_phrase, wrap=650)\n self.after(86400, self.phrase_refresh)\n\n\nApp().mainloop()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T22:10:21.533", "Id": "466326", "Score": "1", "body": "Okay, cool! Thanks for the feedback " } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T15:12:56.607", "Id": "237705", "ParentId": "236257", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T22:37:41.197", "Id": "236257", "Score": "6", "Tags": [ "python", "python-3.x", "tkinter" ], "Title": "Python Display Streamlining" }
236257
<p>I have the following setup code for my .NET Core 3.1 console application/microservice app and I want to learn and improve what I have - I have a feeling I could be utilizing the core Microsoft .NET APIs better (including the way I have implemented my logging with Serilog)</p> <pre><code>public class Program { private static ILogger&lt;Program&gt; _logger; public static async Task Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; AppDomain.CurrentDomain.ProcessExit += OnCurrentDomainProcessExit; BuildLogger(); var serviceProvider = BuildServiceProvider(); _logger = serviceProvider.GetService&lt;ILoggerFactory&gt;().CreateLogger&lt;Program&gt;(); _logger?.LogInformation("╔═╗┌┬┐┌─┐┬─┐┌┬┐┬┌┐┌┌─┐ ╔╗ ╦ ╦ ╦╔╗╔╔╦╗╔═╗╦═╗╔═╗╔═╗╔╦╗ "); _logger?.LogInformation("╚═╗ │ ├─┤├┬┘ │ │││││ ┬ ╠╩╗║ ║ ║║║║ ║║║╣ ╠╦╝║ ╦╠═╣ ║ "); _logger?.LogInformation("╚═╝ ┴ ┴ ┴┴└─ ┴ ┴┘└┘└─┘ ╚═╝╩═╝╚═╝╝╚╝═╩╝╚═╝╩╚═╚═╝╩ ╩ ╩ooo"); CancellationTokenSource cts = new CancellationTokenSource(); await serviceProvider.GetService&lt;IHostedService&gt;().StartAsync(cts.Token); } private static ServiceProvider BuildServiceProvider() { return new ServiceCollection() .AddSingleton&lt;IHostedService, CoreHostingService&gt;() .AddSingleton&lt;ISolverManagementService, SolverManagementService&gt;() .AddSingleton&lt;IDepthMapToPointCloudAdapter, DepthMapToPointCloudAdapter&gt;() .AddSingleton&lt;IPointCloudGenerator, PointCloudGenerator&gt;() .AddSingleton&lt;IPointCloudPairCollectionGenerator, PointCloudPairCollectionGenerator&gt;() .AddSingleton&lt;IIcpBatchSolverService, IcpBatchSolverService&gt;() .AddSingleton&lt;IMeshGenerator, MeshGeneratorBase&gt;(serviceProvider =&gt; { var meshingMethod = DefaultSettingsProvider.Instance.SolverSettings.MeshingSettings.MeshingMethod; return MeshGeneratorFactory.GetMeshGenerator(meshingMethod); }) .AddSingleton&lt;ISettingsProvider&gt;(DefaultSettingsProvider.Instance) .AddLogging(builder =&gt; { builder.SetMinimumLevel(LogLevel.Trace); builder.AddSerilog(Log.Logger); }) .BuildServiceProvider(); } private static void BuildLogger() { var settingsProvider = DefaultSettingsProvider.Instance; if (settingsProvider.AppSettings.OptimizeLogging) { Log.Logger = new LoggerConfiguration() .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day) .Enrich.With(new LoggerThreadIdEnricher()) .WriteTo.Console( outputTemplate: "[{Timestamp:HH:mm:ss.fff} {Level:u3}] [{ThreadId:00}] {Message}{NewLine}{Exception}", theme: AnsiConsoleTheme.Code) .CreateLogger(); } else { Log.Logger = new LoggerConfiguration() .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day) .Enrich.With(new LoggerCallerEnricher()) .Enrich.With(new LoggerThreadIdEnricher()) .WriteTo.Console( outputTemplate: "[{Timestamp:HH:mm:ss.fff} {Level:u3}] [{ThreadId:00}] [{Caller}] {Message}{NewLine}{Exception}", theme: AnsiConsoleTheme.Code) .CreateLogger(); } } private static void OnCurrentDomainProcessExit(object sender, EventArgs e) { DefaultSettingsProvider.Instance.Save(); _logger.LogWarning("Close requested, Blundergat shutting down..."); Thread.Sleep(500); } private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { _logger?.LogCritical(e.ExceptionObject.ToString()); _logger?.LogCritical("FATAL ERROR OCCURRED, Blundergat must shutdown, press any key to close"); Console.ReadLine(); Environment.Exit(1); } } </code></pre> <p>I thin have the <code>IHostedService</code> as </p> <pre><code>public class CoreHostingService : BackgroundService, ICoreHostedService { private readonly ISolverManagementService _solverManagementService; private readonly ISettingsProvider _settingsProvider; private readonly ILogger&lt;CoreHostingService&gt; _logger; private bool _shouldExit; public CoreHostingService( ISolverManagementService solverManagementService, ISettingsProvider settingsProvider, ILogger&lt;CoreHostingService&gt; logger) { _solverManagementService = solverManagementService ?? throw new ArgumentNullException($"{nameof(solverManagementService)}"); _settingsProvider = (DefaultSettingsProvider)settingsProvider; _logger = logger; InitializeSettingsForFirstUse(); InitializeApiCallbacks(); } private void InitializeSettingsForFirstUse() { if (String.IsNullOrEmpty(_settingsProvider.DataSettings.BaseDirectory)) { _shouldExit = true; _settingsProvider.Save(); _logger.LogWarning( $"Some default settings have been written to \"{_settingsProvider.GetSerializedFilePath()}\". " + "Please ensure you ammend the path to the target data directory before restarting the Blundergat service."); } } private void InitializeApiCallbacks() { Callbacks.ProgressCallback = (message) =&gt; _logger?.LogInformation(message); Callbacks.WarningCallback = (message) =&gt; _logger?.LogWarning(message); Callbacks.ErrorCallback = (message) =&gt; _logger?.LogError(message); _logger?.LogDebug("C++ API cross-platform callbacks initialized"); } public override async Task StartAsync(CancellationToken cancellationToken) { await ExecuteAsync(cancellationToken); } protected override async Task ExecuteAsync(CancellationToken token) { try { if (ExitRequested()) return; await _solverManagementService.ExecuteProcessPipeline(token); } catch (Exception ex) { _logger.LogError(ex, "PointCloud merge process failed"); } } private bool ExitRequested() { if (_shouldExit) { _logger.LogWarning("Blundergat is exiting... Good day!"); return true; } return false; } } </code></pre> <p>How can I improve upon this architecture? </p> <p>I am aware that I can use a <code>IHostedServiceAccessor</code> for a scalable microservice architecture, I have code this up, but I am note sure how to use this outside of a ASP.NET app which seems to have better setup capabilities. </p> <pre><code>public interface IHostedServiceAccessor&lt;out T&gt; where T : IHostedService { T Service { get; } } public class HostedServiceAccessor&lt;T&gt; : IHostedServiceAccessor&lt;T&gt; where T : IHostedService { public HostedServiceAccessor(IEnumerable&lt;IHostedService&gt; hostedServices) { Service = hostedServices.OfType&lt;T&gt;().FirstOrDefault(); } public T Service { get; } } </code></pre> <p>Where I assume I would do something like </p> <pre><code>return new ServiceCollection() .AddSingleton&lt;IHostedServiceAccessor&lt;ICoreHostedService&gt;, HostedServiceAccessor&lt;CoreHostingService&gt;&gt;() .AddSingleton&lt;ISolverManagementService, SolverManagementService&gt;() </code></pre> <p>But how would I then start this hosted service?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T15:09:02.053", "Id": "462982", "Score": "0", "body": "The last part of your question is off-topic. We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T22:47:31.397", "Id": "236258", "Score": "1", "Tags": [ "c#", "console", ".net-core" ], "Title": ".NET Core Service/Console App Architecture" }
236258
<p>I've been building this program for around a week or two on my spare time because I'm slowly starting to figure out how to code better. This program generates a yearly 5/3/1 cycle that is exported to a CSV file so you can easily print it off if you want. </p> <p>Below is my code: </p> <pre><code>/** * */ package main; import java.util.Scanner; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; /** * @author Brandon * */ public class Five31 { /** * @param args */ public static void main(String[] args) throws IOException { //initialize 1RM variables. Also generate arrays that are constant every month. double squat = 0, bench = 0, dl = 0, ohp = 0; double week1[] = {.65, .75, .85}; double week2[] = {.70, .80, .90}; double week3[] = {.75, .85, .95}; double week4[] = {.40, .50, .60}; welcome(); Scanner input = new Scanner(System.in); exercisee a = new exercisee(); //get user input and validate user responses. //validation by ensuring that user can't enter less than 45 lbs. System.out.println("What's your name?"); String b = input.next(); a.setName(b); System.out.println("Nice to meet you, " + a.getName()); System.out.println("What's your max squat?"); while(squat &lt; 45){ squat = input.nextDouble(); if(squat &lt; 1) { System.out.println("Please input a value greater than 45 lbs."); } } squat = roundTo5(squat); a.setMaxSquat(squat); System.out.println("Your max squat is " + a.getMaxSquat()); System.out.println("What's your max bench?"); while(bench &lt; 45) { bench = input.nextDouble(); if (bench &lt; 1) { System.out.println("Please input a value greater than 45 lbs."); } } bench = roundTo5(bench); a.setMaxBench(bench); System.out.println("Your max bench is " + a.getMaxBench()); System.out.println("What's your max deadlift?"); while(dl &lt; 45) { dl = input.nextDouble(); if(dl &lt; 1) { System.out.println("Please input a value greater than 45 lbs."); } } dl = roundTo5(dl); a.setMaxDL(dl); System.out.println("Your max deadlift is " + a.getMaxDL()); System.out.println("What's your max overhead press?"); while(ohp &lt; 45) { ohp = input.nextDouble(); if(ohp &lt; 1) { System.out.println("Please input a value greater than 45 lbs."); } } ohp = roundTo5(ohp); a.setMaxOHP(ohp); System.out.println("Your max overhead press is " + a.getMaxOHP()); System.out.println(""); System.out.println("Calculating training maxes for the cycles..."); System.out.println(""); //declare training max variables and calculate training maxes. double tSquat=0, tBench = 0, tDL = 0, tOHP = 0; tSquat = (.9 * a.getMaxSquat()); tBench = (.9 * a.getMaxBench()); tDL = (.9 * a.getMaxDL()); tOHP = (.9 * a.getMaxOHP()); //round those calculations to the nearest 5 lbs and cast them into integers. tSquat = roundTo5(tSquat); tBench = roundTo5(tBench); tDL = roundTo5(tDL); tOHP = roundTo5(tOHP); //store values into array. double trainingMax[] = {tSquat, tBench, tDL, tOHP}; String exerciseList[] = {"Squat", "Bench", "Deadlift", "Overhead Press"}; //set training maxes for the object. a.setTrainingSquat(tSquat); a.setTrainingBench(tBench); a.setTrainingDL(tDL); a.setTrainingOHP(tOHP); //display training maxes for various exercises. System.out.println("Your training max for squat is " + a.getTSquat()); System.out.println("Your training max for bench is " + a.getTBench()); System.out.println("Your training max for deadlift is " + a.getTDL()); System.out.println("Your training max for overhead press is " + a.getTOHP()); System.out.println(""); //Generate data for the month. System.out.println("Week 1 (3x5) at 65%, 75%, 85%"); System.out.println("Week 2 (3x3) at 70%, 80%, 90%"); System.out.println("Week 3 (1x5, 1x3, 1x1) at 75%, 85%, 95%"); System.out.println("Week 4: Deload(Optional) 3x5 at 40%, 50%, 60%"); System.out.println(""); //need to have this for generating data for year. String months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; //create buffered writer obj with filewriter object. allows use of newLine that buffered writer has. String csvFile = "/Users/Brandon/Desktop/results.csv"; BufferedWriter bw = new BufferedWriter(new FileWriter(csvFile)); /* This loop can be confusing * the most confusing part is following it. * var i is used for months * if you follow i, at the bottom, this program automatically adjusts training maxes by 5 per week. * conservative, but fair. this will stop people from jumping into heavier workloads for no reason and potentially injuring themselves. * var l is used for weeks * var j is used for tracking exercise * var k is used for generating workout sets. */ //Generates data for an entire year. 4 for loops. days + weeks + months + sets. for(int i = 0; i &lt; 12; i++) { bw.write(months[i]); bw.write(","); bw.write("Exercise"); bw.write(","); bw.write("Set 1"); bw.write(","); bw.write("Set 2"); bw.write(","); bw.write("Set 3"); bw.newLine(); //week for(int l = 0; l &lt; 4; l++) { bw.write("Week " + Integer.toString(l+1)); System.out.println("Week " + (l+1) + ":"); System.out.println(""); if(l == 3) { System.out.println("Easy week"); } // for(int j = 0; j &lt; 4; j++) { System.out.println((j+1) + " day: ("+exerciseList[j]+")"); bw.write(","); bw.write(exerciseList[j]); bw.write(","); System.out.println(""); System.out.println("Proposed sets: "); //Generates weights for the exercises for(int k = 0; k &lt; 3; k++) { if(l == 0) { switch(j) { case 0: bw.write(Integer.toString(roundTo5(week1[k] * trainingMax[j]))); bw.write(","); if(k == 2) { bw.newLine(); } break; case 1: bw.write(Integer.toString(roundTo5(week1[k] * trainingMax[j]))); bw.write(","); if(k == 2) { bw.newLine(); } break; case 2: bw.write(Integer.toString(roundTo5(week1[k] * trainingMax[j]))); bw.write(","); if(k == 2) { bw.newLine(); } break; case 3: bw.write(Integer.toString(roundTo5(week1[k] * trainingMax[j]))); bw.write(","); if(k == 2) { bw.newLine(); } break; } System.out.println(roundTo5((week1[k] * trainingMax[j]))); } else if(l == 1) { switch(j) { case 0: bw.write(Integer.toString(roundTo5(week2[k] * trainingMax[j]))); bw.write(","); if(k == 2) { bw.newLine(); } break; case 1: bw.write(Integer.toString(roundTo5(week2[k] * trainingMax[j]))); bw.write(","); if(k == 2) { bw.newLine(); } break; case 2: bw.write(Integer.toString(roundTo5(week2[k] * trainingMax[j]))); bw.write(","); if(k == 2) { bw.newLine(); } break; case 3: bw.write(Integer.toString(roundTo5(week2[k] * trainingMax[j]))); bw.write(","); if(k == 2) { bw.newLine(); } break; } System.out.println(roundTo5((week2[k] * trainingMax[j]))); } else if(l == 2) { switch(j) { case 0: bw.write(Integer.toString(roundTo5(week3[k] * trainingMax[j]))); bw.write(","); if(k == 2) { bw.newLine(); } break; case 1: bw.write(Integer.toString(roundTo5(week3[k] * trainingMax[j]))); bw.write(","); if(k == 2) { bw.newLine(); } break; case 2: bw.write(Integer.toString(roundTo5(week3[k] * trainingMax[j]))); bw.write(","); if(k == 2) { bw.newLine(); } break; case 3: bw.write(Integer.toString(roundTo5(week3[k] * trainingMax[j]))); bw.write(","); if(k == 2) { bw.newLine(); } break; } System.out.println(roundTo5((week3[k] * trainingMax[j]))); } else if(l == 3){ switch(j) { case 0: bw.write(Integer.toString(roundTo5(week4[k] * trainingMax[j]))); bw.write(","); if(k == 2) { bw.newLine(); } break; case 1: bw.write(Integer.toString(roundTo5(week4[k] * trainingMax[j]))); bw.write(","); if(k == 2) { bw.newLine(); } break; case 2: bw.write(Integer.toString(roundTo5(week4[k] * trainingMax[j]))); bw.write(","); if(k == 2) { bw.newLine(); } break; case 3: bw.write(Integer.toString(roundTo5(week4[k] * trainingMax[j]))); bw.write(","); if(k == 2) { bw.newLine(); } break; } System.out.println(roundTo5((week4[k] * trainingMax[j]))); } } } System.out.println(""); bw.newLine(); } for(int c = 0; c &lt; 4; c++) { trainingMax[c] = trainingMax[c] + 5; } } bw.close(); exit(); } //this is necessary because there is no such thing as a 2.3 lb weight at the gym. //all weight numbers are integers, at least in my gym. public static int roundTo5(double t) { return (int) (5*(Math.round(t/5))); } public static void welcome() { System.out.println("*******************************************"); System.out.println("* *"); System.out.println("* Welcome to the 5/3/1 calculator *"); System.out.println("* *"); System.out.println("*******************************************"); } public static void exit() { System.out.println("Thanks for using my program! -Brandon"); } } </code></pre> <p>I'm looking for any suggestions on how I could've improved it or what I did wrong because I thought I did a pretty good job, but I know this community is going to roast my entire code. I could have probably added a few try and catch statements in where the CSV file operation begins just to start off.</p> <p>Edit: I just wanted to show you guys how the program looks in the CSV file as well. Less work for you guys.</p> <p><a href="https://i.stack.imgur.com/zlEZq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zlEZq.png" alt="how it looks"></a></p>
[]
[ { "body": "<p>There's a lot of duplicated code here which makes your logic here more difficult than it needs to be. As a first step, consider extracting some of the functionality into into reusable chunks. For example:</p>\n\n<p>A method:</p>\n\n<pre><code>private static double promptForMax(Scanner input, String activity) {\n double max = 0;\n System.out.println(\"What's your max \" + activity + \"?\");\n while (max &lt; 45) {\n max = input.nextDouble();\n if (max &lt; 1) {\n System.out.println(\"Please input a value greater than 45 lbs.\");\n }\n }\n max = roundTo5(max);\n return max;\n}\n</code></pre>\n\n<p>Could be reused for each of the activity inputs. By removing the unnecessary temporary variables, the input fetching would then look more like:</p>\n\n<pre><code>a.setMaxSquat(promptForMax(input, \"squat\"));\nSystem.out.println(\"Your max squat is \" + a.getMaxSquat());\na.setMaxBench(promptForMax(input, \"bench\"));\nSystem.out.println(\"Your max bench is \" + a.getMaxBench());\na.setMaxDL(promptForMax( input, \"deadlift\"));\nSystem.out.println(\"Your max deadlift is \" + a.getMaxDL());\na.setMaxOHP(promptForMax(input, \"overhead press\"));\nSystem.out.println(\"Your max overhead press is \" + a.getMaxOHP());\n</code></pre>\n\n<p>Which is a lot more concise.</p>\n\n<p>There's other sections where you seem to be executing exactly the same code for different values. Consider this <code>switch</code>:</p>\n\n<blockquote>\n<pre><code>switch (j) {\n case 0:\n bw.write(Integer.toString(roundTo5(week2[k] * trainingMax[j])));\n bw.write(\",\");\n if (k == 2) {\n bw.newLine();\n }\n break;\n case 1:\n bw.write(Integer.toString(roundTo5(week2[k] * trainingMax[j])));\n bw.write(\",\");\n if (k == 2) {\n bw.newLine();\n }\n break;\n case 2:\n bw.write(Integer.toString(roundTo5(week2[k] * trainingMax[j])));\n bw.write(\",\");\n if (k == 2) {\n bw.newLine();\n }\n break;\n case 3:\n bw.write(Integer.toString(roundTo5(week2[k] * trainingMax[j])));\n bw.write(\",\");\n if (k == 2) {\n bw.newLine();\n }\n break;\n</code></pre>\n</blockquote>\n\n<p>Every <code>case</code> does the same exact thing. It seems like it's the equivalent of:</p>\n\n<pre><code>if(j &gt;= 0 &amp;&amp; j &lt;= 3) {\n bw.write(Integer.toString(roundTo5(week2[k] * trainingMax[j])));\n bw.write(\",\");\n if (k == 2) {\n bw.newLine();\n }\n} \n</code></pre>\n\n<p>You do the same thing for week3. Reducing this duplication, through extracting meaningfully named methods, looking for different branching logic / variable, will go a long way to making the program more approachable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T09:52:47.020", "Id": "236281", "ParentId": "236264", "Score": "2" } }, { "body": "<p>Your code contains a lot of duplicate code and is hard to read. </p>\n\n<p>In this code, I tried to get rid of duplicated code. I got rid of the object \"exercisee\" that is unnecessary in my opinion.\nGot rid of a lot of nesting in methods. And he made sure that all the information was first collected in the StringBuilder and then completely displayed in the csv file.</p>\n\n<pre><code> import java.util.Scanner;\n import java.io.BufferedWriter;\n import java.io.FileWriter;\n import java.io.IOException;\n /**\n * @author Brandon\n *\n */\npublic class Five31 {\n\npublic static void main(String[] args) throws IOException {\n welcome();\n Scanner input = new Scanner(System.in);\n\n System.out.println(\"What's your name?\");\n String youName = input.next();\n System.out.println(\"Nice to meet you, \" + youName);\n\n double squat = issue( input, \"squat\" );\n double trainingSquat = calc( squat );\n double bench = issue( input, \"bench\" );\n double trainingBench = calc( bench);\n double deadlift = issue( input, \"deadlift\" );\n double trainingDeadlift = calc( deadlift );\n double ohp = issue( input, \"overhead press\" );\n double trainingOPH = calc( ohp );\n\n\n double[] trainingMax = {trainingSquat, trainingBench,trainingDeadlift,trainingOPH};\n\n System.out.println(\"Report file path?\");\n String reportFilePath = input.next();\n\n printToCsv( createReport( trainingMax ), reportFilePath );\n\n exit();\n}\n\n\nprivate static StringBuilder createReport(double[] trainingMax){\n StringBuilder sb = new StringBuilder();\n iteratorMonths(sb, trainingMax);\n return sb;\n}\n\n\npublic static int roundTo5(double t) {\n return (int) (5*(Math.round(t/5)));\n}\n\n\npublic static void welcome() {\n System.out.println(\"*******************************************\");\n System.out.println(\"* *\");\n System.out.println(\"* Welcome to the 5/3/1 calculator *\");\n System.out.println(\"* *\");\n System.out.println(\"*******************************************\");\n}\n\npublic static void exit() {\n System.out.println(\"Thanks for using my program! -Brandon\");\n}\n\n\n\nprivate static double issue( Scanner input, String p ){\n System.out.println(\"What's your max \" + p + \"?\");\n double val;\n do{\n val = input.nextDouble();\n if(val &lt; 1) {\n System.out.println(\"Please input a value greater than 45 lbs.\");\n }\n }while(val &lt; 45);\n val = roundTo5(val);\n System.out.println(\"Your max \" + p + \" is \" + val);\n return val;\n}\n\nprivate static double calc(double val){\n return roundTo5(0.9 * val);\n}\n\nprivate static void printToCsv( StringBuilder sb, String filePath){\n try(BufferedWriter bw = new BufferedWriter( new FileWriter(filePath) ) ){\n\n bw.write( sb.toString() );\n }catch( IOException e ){\n e.printStackTrace();\n }\n}\n\n\nprivate static void iteratorMonths( StringBuilder sb, double[] trainingMax){\n\n String[] months = {\"January\", \"February\", \"March\", \"April\", \"May\",\n \"June\", \"July\", \"August\",\n \"September\", \"October\", \"November\", \"December\"\n };\n\n\n for( String month : months ){\n sb.append( month ).append( \",Exercise,Set 1,Set 2,Set 3\\r\\n\" );\n iteratorWeeks( sb, trainingMax );\n trainingMaxPlus( trainingMax );\n }\n}\n\n\nprivate static void trainingMaxPlus( double[] trainingMax ){\n for( int i = 0; i &lt; trainingMax.length; i++ ){\n trainingMax[i] = trainingMax[i] + 5;\n }\n}\n\n\nprivate static void iteratorWeeks( StringBuilder sb, double[] trainingMax){\n\n double[][] weeksKoeffs={\n {.65, .75, .85},\n {.70, .80, .90},\n {.75, .85, .95},\n {.40, .50, .60}\n };\n\n for( int i = 1; i &lt;= weeksKoeffs.length; i++ ){\n sb.append( \"Week \").append( i );\n System.out.println( \"Week \" + i + \":\\r\\n\" );\n if( i == weeksKoeffs.length ){\n System.out.println( \"Easy week\" );\n }\n iteratorDays(sb, weeksKoeffs[i-1], trainingMax);\n System.out.println();\n sb.append( \"\\r\\n\" );\n }\n}\n\n\nprivate static void iteratorDays( StringBuilder sb, double[] weekKoeffs, double[] trainingMax){\n String[] exerciseList = { \"Squat\", \"Bench\", \"Deadlift\", \"Overhead Press\"};\n String exercise;\n for( int j = 0; j &lt; exerciseList.length; j++ ){\n exercise = exerciseList[j];\n System.out.println( ( j + 1 ) + \" day: (\" + exercise + \")\" );\n sb.append(\",\").append( exercise).append( \",\" );\n System.out.println();\n iteratorProposedSets(sb, weekKoeffs, trainingMax[j]);\n sb.append( \"\\r\\n\" );\n }\n}\n\n\nprivate static void iteratorProposedSets( StringBuilder sb, double[] weekKoeffs, double trainingMax){\n System.out.println( \"Proposed sets: \" );\n for( double weekKoeff : weekKoeffs ){\n iteratorProposedSet( sb, weekKoeff, trainingMax );\n\n }\n}\n\n\nprivate static void iteratorProposedSet( StringBuilder sb, double weekKoeff, double trainingMax){\n int val = roundTo5( weekKoeff * trainingMax );\n sb.append( val).append( \",\" );\n System.out.println(val);\n}\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T14:12:16.477", "Id": "462970", "Score": "0", "body": "You present a lot of code. Can you please argue how changes are an improvement, or is *duplicate code and hard to read* the gist of it? Does it add insight about the code presented in the question beyond [forsvarir's review](https://codereview.stackexchange.com/a/236281/93149)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T14:23:57.150", "Id": "462971", "Score": "0", "body": "In this code, I tried to get rid of duplicated code. I got rid of the object \"exercisee\" that is unnecessary in my opinion. Got rid of a lot of nesting in methods. And he made sure that all the information was first collected in the StringBuilder and then completely displayed in the csv file." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T14:04:22.123", "Id": "236296", "ParentId": "236264", "Score": "2" } }, { "body": "<p>It seems clear that you haven't split up the functionality in methods. That makes the code hard to maintain, more error prone, more likely to contain duplicate code fragments.</p>\n\n<p>It is very clear that you mix input / output and functionality: the calculations. Those are normally split into separate classes. Classes should be relatively small, maybe a hundred lines max; some persons even like much smaller classes than that - but it is possible to overdo it, in my opinion.</p>\n\n<p>The architecture is already addressed, so I'll just talk about the code / Java specific issues that I see:</p>\n\n<pre><code>/**\n * \n */\npackage main;\n</code></pre>\n\n<p>That's not a good name for a package at all. Use a reversed web address or at least something that reflects the contents of the code.</p>\n\n<p>The JavaDoc comment should not be there at all (you can create your own <code>package-info.java</code> if you want to document the package; we cannot have classes within the package redefine the package description after all.</p>\n\n<pre><code>public class Five31 {\n</code></pre>\n\n<p>That's a good name if the rest of the community understands it. However, if the class only contains static methods then the class should be <code>final</code> and there should be a private zero argument constructor to avoid instantiation.</p>\n\n<pre><code> /**\n * @param args\n */\n</code></pre>\n\n<p>Either remove it, put a TODO in it or describe it, but don't leave it hanging.</p>\n\n<pre><code> public static void main(String[] args) throws IOException {\n</code></pre>\n\n<p>Maybe your users won't be all that happy to have to deal with <code>IOException</code> themselves.</p>\n\n<pre><code> //initialize 1RM variables. Also generate arrays that are constant every month.\n</code></pre>\n\n<p>1RM, oh, right. Why not use full words? Same for your variable definitions. Not everybody will get these acronyms. Expect programmers, not athletes.</p>\n\n<pre><code> double squat = 0, bench = 0, dl = 0, ohp = 0;\n</code></pre>\n\n<p>Variable definitions should be defined where they occur in Java, and they should not be filled with default values such as <code>0</code>. A compiler error is better than forgetting to assign them a value after all.</p>\n\n<pre><code> double week1[] = {.65, .75, .85};\n ...\n</code></pre>\n\n<p>These should be defined as <code>private static final double[] WEEK1 = {.65, .75, .85}</code>, the Java equivalent of constant values. In Java, prefer to put the brackets after the type, so that it is clear that the type is <code>double[]</code>.</p>\n\n<pre><code> welcome();\n</code></pre>\n\n<p>Thank you, but what about <code>printWelcome</code>?</p>\n\n<pre><code> exercisee a = new exercisee();\n</code></pre>\n\n<p>Bad class name, should start with an uppercase character. And the excercisee should probably have some defining characteristics (such as a name or ID) right from the start? And calling the excercisee <code>a</code> is just lazy. I'd expect something like <code>Exercisee exercisee = new Exercisee(name);</code>.</p>\n\n<pre><code> while(squat &lt; 45){\n squat = input.nextDouble();\n if(squat &lt; 1) {\n System.out.println(\"Please input a value greater than 45 lbs.\");\n }\n }\n</code></pre>\n\n<p>Now the <code>if</code> statement looks for values <code>&lt; 1</code> and the <code>while</code> looks for values <code>&lt; 45</code>. That's weird, isn't it? And note that you are now assigning the value already; you can simply put <code>double squat</code> right in front of the <code>while</code> loop and everything will run fine.</p>\n\n<pre><code> squat = roundTo5(squat);\n</code></pre>\n\n<p>If you would retrieve <code>squat</code> in a function <code>double maxSquat = retrieveMaxSquat()</code> then you'd just have a single line left, and squat would not have to be assigned a value multiple times.</p>\n\n<pre><code> System.out.println(\"Calculating training maxes for the cycles...\");\n</code></pre>\n\n<p>Are you expecting this to take weeks?</p>\n\n<pre><code> double tSquat=0, tBench = 0, tDL = 0, tOHP = 0;\n</code></pre>\n\n<p>Ah, forgetting to call it <code>maxSquat</code> is biting you now, right? Same as before, declare variables where they are needed.</p>\n\n<pre><code> tSquat = (.9 * a.getMaxSquat());\n</code></pre>\n\n<p>Ah, <code>0.9</code>, the ultimate magic value. This should be constant (<code>private static final double SOMETHING = 0.9</code>).</p>\n\n<hr>\n\n<p>... uh, now I ran out of time and steam, there is plenty that can be enhanced, but it would take another day for me to pick this apart. Maybe I'll refactor later.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T01:01:44.177", "Id": "463044", "Score": "0", "body": "Added an answer where I refactored..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T17:43:35.683", "Id": "236308", "ParentId": "236264", "Score": "2" } }, { "body": "<p>OK, let's do the ultimate refactoring to classes. Beware that there won't be much left of the original code, but your ideas are of course still in there.</p>\n\n<p>Start with <code>package-info.java</code> (I called the package <code>pressing</code>) as you can see:</p>\n\n<pre><code>/**\n * This is the package for FiveThreeOne, an application to calculate training exercises given your maximum\n * weight for a specific exercise.\n */\npackage com.stackexchange.codereview.pressing;\n</code></pre>\n\n<p>The other files that I show are in that package, under <code>&lt;classname&gt;.java</code>.</p>\n\n<p>Here is what is left of your main <code>Five31</code> class:</p>\n\n<pre><code>import java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.PrintStream;\n\npublic class FiveThreeOne {\n\n /**\n * Performs the FiveThreeOne operation for a specific person.\n * \n * @param args no arguments required\n * \n * @throws FileNotFoundException \n */\n public static void main(String[] args) throws FileNotFoundException {\n var calc = new TrainingCalculator();\n\n var console = new ConsoleUI(System.in, System.out, calc);\n console.printWelcome();\n\n var name = console.requestName();\n var gymnast = new Gymnast(name);\n\n for (Exercise exercise : Exercise.values()) {\n int max = console.requestMax(exercise);\n gymnast.setMax(exercise, max);\n }\n\n // DEBUG print out exercisee using Exercisee.toString()\n System.out.println();\n System.out.println(gymnast);\n // and some training maximum stuff\n System.out.printf(\"Max training for squat: %d%n\", calc.calculateTrainingMaximum(gymnast.getMax(Exercise.SQUAT).getAsInt()));\n\n System.out.println();\n System.out.printf(\"Results are being written to file %s.csv...%n\", name);\n System.out.println();\n\n // want it on the screen instead? Pass System.out to TrainingCreator as first argument!\n try (PrintStream bw = new PrintStream(new FileOutputStream(name + \".csv\"))) {\n var creator = new TrainingCreator(bw, calc);\n creator.createTraining(gymnast);\n }\n\n console.printGoodbye();\n }\n\n}\n</code></pre>\n\n<p>Then there is the <code>Exercise</code> enum:</p>\n\n<pre><code>public enum Exercise {\n SQUAT, BENCH, DEADLIFT;\n\n @Override\n public String toString() {\n return this.name().toLowerCase();\n }\n}\n</code></pre>\n\n<p>the <code>Gymnast</code> class, which replaces the <code>exercisee</code> class, as I generally keep to words defined in the dictionary...</p>\n\n<pre><code>import java.util.Map;\nimport java.util.OptionalInt;\nimport java.util.Set;\nimport java.util.TreeMap;\n\npublic final class Gymnast {\n // no setter for name to avoid confusion, use a static ID otherwise\n private String name;\n\n // the tree-based map keeps the keys (i.e. exercises) in order\n private Map&lt;Exercise, Integer&gt; maxForExercises = new TreeMap&lt;&gt;();\n\n public Gymnast(String name) {\n // guard to avoid invalid state\n if (name == null) {\n throw new NullPointerException(\"Name is null\");\n }\n\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n public void setMax(Exercise exercise, int max) {\n maxForExercises.put(exercise, max);\n }\n\n public Set&lt;Exercise&gt; getExercises() {\n return maxForExercises.keySet();\n }\n\n public OptionalInt getMax(Exercise exercise) {\n return OptionalInt.of(maxForExercises.get(exercise));\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof Gymnast)) {\n return false;\n }\n\n final Gymnast that = (Gymnast) obj;\n return name.equalsIgnoreCase(that.name);\n }\n\n @Override\n public int hashCode() {\n return name.hashCode();\n }\n\n @Override\n public String toString() {\n return String.format(\"%s %s\", name, maxForExercises);\n }\n}\n</code></pre>\n\n<p>The all important <code>TrainingCalculator</code> contains your calculations:</p>\n\n<pre><code>public final class TrainingCalculator {\n private static final int MINIMUM_WEIGHT = 45;\n private static final double MAX_TO_TRAINING_MAX_COEFFICIENT = 0.9;\n private static final int ADJUSTMENT_TO_TRAINING_MAXIMUM = 5;\n private static double WEEKLY_EFFORT[][] = {{ .65, .75, .85 }, { .70, .80, .90 }, { .75, .85, .95 },\n { .40, .50, .60 } };\n\n public TrainingCalculator() {\n // actually auto-generated by Java, but I prefer it being there\n }\n\n /**\n * This automatically adjusts training maximums by 5 per week which is\n * conservative, but fair.\n * This will stop people from jumping into heavier\n * workloads for no reason and potentially injuring themselves.\n * \n * @param trainingMax an array of training maximums to be adjusted\n */\n public void adjustTrainingMaximum(int[] trainingMax) {\n for (int i = 0; i &lt; trainingMax.length; i++) {\n trainingMax[i] = trainingMax[i] + ADJUSTMENT_TO_TRAINING_MAXIMUM;\n }\n }\n\n public int calculateTrainingForSet(int week, int workoutSet, int maxTraining) {\n return roundTo5(WEEKLY_EFFORT[week - 1][workoutSet] * maxTraining);\n }\n\n public int calculateTrainingMaximum(int max) {\n return roundTo5(MAX_TO_TRAINING_MAX_COEFFICIENT * max);\n }\n\n /**\n * This method is necessary because there is no such thing as a 2.3 lb weight at the\n * gym;\n * All weight numbers are integers, at least in my gym.\n * \n * @param weight the weight to round\n * @return the weight rounded to the closest multiple of 5 as integer\n */\n public int roundTo5(double weight) {\n return 5 * (int) (Math.round((double) weight / 5));\n }\n\n public boolean hasMinimumWeight(int max) {\n return max &gt;= MINIMUM_WEIGHT;\n }\n}\n</code></pre>\n\n<p>Then come the I/O classes, starting with the UI class, now split from the calculation and output functionality:</p>\n\n<pre><code>import java.io.InputStream;\nimport java.io.PrintStream;\nimport java.util.Scanner;\n\npublic class ConsoleUI {\n\n private Scanner scanner;\n private PrintStream out;\n private TrainingCalculator calc;\n\n public ConsoleUI(InputStream in, PrintStream out, TrainingCalculator calc) {\n this.out = out;\n this.scanner = new Scanner(in);\n this.calc = calc;\n }\n\n public void printWelcome() {\n out.println(\"*******************************************\");\n out.println(\"* *\");\n out.println(\"* Welcome to the 5/3/1 calculator *\");\n out.println(\"* *\");\n out.println(\"*******************************************\");\n out.println();\n }\n\n public String requestName() {\n out.println(\"What's your name?\");\n var name = scanner.next();\n out.printf(\"Nice to meet you, %s!%n\", name);\n out.println();\n return name;\n }\n\n public int requestMax(Exercise exercise) {\n int max;\n while (true) {\n out.printf(\"What's your max for %s?%n\", exercise);\n int inputMaxSquat = scanner.nextInt();\n max = calc.roundTo5(inputMaxSquat);\n if (calc.hasMinimumWeight(max)) {\n break;\n }\n\n out.println(\"Input a value greater than 45 (values in lbs) - please try again.\");\n }\n out.printf(\"Your max for %s is (rounded to multiples of five): %d%n\", exercise, max);\n out.println();\n return max;\n }\n\n public void printGoodbye() {\n // we need symmetry, so box the goodbye!\n out.println(\"*******************************************\");\n out.println(\"* *\");\n out.println(\"* Thanks for using my program! - Brandon *\");\n out.println(\"* *\");\n out.println(\"*******************************************\");\n }\n\n}\n</code></pre>\n\n<p>and finally, the <code>TrainingCreator</code> creates your CSV output:</p>\n\n<pre><code>import java.io.PrintStream;\nimport java.time.Month;\nimport java.time.format.TextStyle;\nimport java.util.Locale;\n\npublic class TrainingCreator {\n private static int WEEK_COUNT = 4;\n private static final int WORKOUT_SETS = 3;\n\n private PrintStream out;\n private TrainingCalculator calc;\n\n public TrainingCreator(PrintStream out, TrainingCalculator calc) {\n this.out = out;\n this.calc = calc;\n }\n\n public void createTraining(Gymnast gymnast) {\n int[] trainingMax = new int[gymnast.getExercises().size()];\n int exerciseIndex = 0;\n for (Exercise exercise : gymnast.getExercises()) {\n trainingMax[exerciseIndex++] = calc.calculateTrainingMaximum(gymnast.getMax(exercise).getAsInt());\n }\n\n // generates data for an entire year: days + weeks + months + sets\n for (int month = 1; month &lt;= 12; month++) {\n writeHeaderForMonth(month, 3);\n for (int week = 1; week &lt;= WEEK_COUNT; week++) {\n writeWeek(gymnast, week, trainingMax);\n }\n out.println();\n\n calc.adjustTrainingMaximum(trainingMax);\n }\n }\n\n private void writeHeaderForMonth(int month, int sets) {\n String monthStr = Month.of(month).getDisplayName(TextStyle.FULL_STANDALONE, Locale.US);\n out.print(monthStr);\n out.print(\",\");\n out.print(\"Exercise\");\n for (int set = 0; set &lt; sets; set++) {\n out.printf(\", Set %d\", set);\n }\n out.println();\n }\n\n private void writeWeek(Gymnast gymnast, int week, int[] trainingMax) {\n out.printf(\"Week %d\", week);\n for (Exercise exercise : gymnast.getExercises() ) {\n out.print(\",\");\n writeExersize(week, exercise, trainingMax);\n }\n }\n\n private void writeExersize(int week, Exercise exercise, int[] trainingMax) {\n out.print(capitalize(exercise.toString()));\n out.print(\",\");\n // Generates weights for the exercises\n int maxTraining = trainingMax[exercise.ordinal()];\n for (int workoutSet = 0; workoutSet &lt; WORKOUT_SETS; workoutSet++) {\n int training = calc.calculateTrainingForSet(week, workoutSet, maxTraining);\n out.print(Integer.toString(training));\n if (workoutSet &lt; WORKOUT_SETS -1) {\n out.print(\",\");\n } else {\n out.println();\n }\n }\n }\n\n private String capitalize(String name) {\n return name.substring(0, 1).toUpperCase() + name.substring(1);\n }\n}\n</code></pre>\n\n<p>Now if you run this all then you should get about what you created yourself - the CSV output should not differ. However, I do print less to screen. The problem is that putting <code>System.out.println</code> statement all through the code gets messy fast. Rather than doing that you can copy <code>TrainingCreator</code> to <code>TrainingCreatorForConsole</code> or something and then make the necessary changes. Then you can just run both...</p>\n\n<p>Adding any exercises or changing the calculations should be uber-simple with this class design. Actually, one exercise is missing: try and add it to the enum, and you'll understand the strength of a well thought out class design.</p>\n\n<p>Personally, I would try and get the <code>TrainingCreator</code> to output a <code>TrainingTable</code> representing the data now in the CSV. Then you can convert that data to both the CSV file and an onscreen text. However, that is certainly still a lot of work, and figuring out the design of the table is pretty tough (but doable). Probably not entirely worth it for this standalone application.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T00:53:46.687", "Id": "463043", "Score": "0", "body": "And I thought \"exercise\" was written incorrectly. Oh well, refactor at will.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:20:22.217", "Id": "463122", "Score": "0", "body": "Most of your fields can be final, you might want to update them for consistency. Is there any particular reason why you've overridden `equals` and `hashCode`? At first glance, it seems like these aren't needed/used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:48:11.530", "Id": "463130", "Score": "0", "body": "@forsvarir I took name as the main identifier, by a lack of better. I generally implement these for data classes with setters, because they tend to get stored into lists and whatnot (in iteration x of the program)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T00:46:07.240", "Id": "236322", "ParentId": "236264", "Score": "2" } }, { "body": "<p>My two cents: you could build the month array using</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>String[] months = Stream.of(Month.values()).map(month-&gt;month.getDisplayName(TextStyle.FULL, Locale.ENGLISH)).toArray(String[]::new)\n</code></pre>\n\n<p>This allows you to control the way months are displayed (like using a different <code>TextStyle</code> for abbreviated names, or changing the language). Not a big improvement for your program, but it ensures you don't make any typo.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-04T12:24:33.497", "Id": "236640", "ParentId": "236264", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T00:02:33.180", "Id": "236264", "Score": "1", "Tags": [ "java" ], "Title": "My program generates a yearly workout program in the variation of 5/3/1" }
236264
<p>This code is used to select K for a K-nearest neighbor graph [KNNG] from a dataset with an unknown number of centroids (which is not the same as K-means clustering).</p> <p>Suppose that you have a dataset of observations stored in a data matrix <code>X[n_samples, n_features]</code> with each row being an observation or feature vector and each column being a feature. Now suppose you want to compute the (weighted) <a href="https://en.wikipedia.org/wiki/Nearest_neighbor_graph" rel="nofollow noreferrer">k-Neighbors graph</a> for points in X using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.kneighbors_graph.html" rel="nofollow noreferrer">sklearn.neighbors.kneighbors_graph</a>. The first step is to pick <code>k</code>.</p> <p>This brute force method to pick <code>k</code> below is very slow when the sample dataset size becomes large (ie <code>n_neighbors_max = 10000</code>). The <code>FOR</code> loop is very slow. Any tips for how to speed it up?</p> <pre><code>def autoselect_K(X, n_neighbors_max, threshold): # get the pairwise euclidean distance between every observation D = sklearn.metrics.pairwise.euclidean_distances(X, X) chosen_k = n_neighbors_max for k in range(2, n_neighbors_max): k_avg = [] # loop over each row in the distance matrix for row in D: # sort the row from smallest distance to largest distance sorted_row = numpy.sort(row) # calculate the mean of the smallest k+1 distances k_avg.append(numpy.mean(sorted_row[0:k])) # find the median of the averages kmedian_dist = numpy.median(k_avg) if kmedian_dist &gt;= threshold: chosen_k = k break # return the number of nearest neighbors to use return chosen_k </code></pre>
[]
[ { "body": "<ul>\n<li><p>Without thinking too hard about what you are actually doing (i.e., by trying to find a considerable more efficient algorithm), you could get a decent speedup by using list comprehension. Doing <code>append</code>s inside an explicit <code>for</code> loop doesn't usually lead to high performance.</p></li>\n<li><p>Another observation is that you are doing too much work in sorting the whole row, when you just want the first k elements in sorted order. For that, there's a more suitable function like <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.argpartition.html\" rel=\"nofollow noreferrer\"><code>numpy.argpartition</code></a> or <a href=\"https://docs.python.org/2/library/heapq.html#heapq.nsmallest\" rel=\"nofollow noreferrer\"><code>heapq.nsmallest</code></a>. </p></li>\n</ul>\n\n<p>I don't have a test program for correctness, but I wrote a simple check for performance. But even then, I have no idea about your actual use case and parameters, so take it with a grain of salt:</p>\n\n<pre><code>import numpy as np\nfrom sklearn.metrics.pairwise import euclidean_distances\nfrom time import time\n\ndef autoselect_K_orig(X, n_neighbors_max, threshold):\n # get the pairwise euclidean distance between every observation\n D = euclidean_distances(X, X)\n chosen_k = n_neighbors_max\n for k in range(2, n_neighbors_max):\n k_avg = []\n # loop over each row in the distance matrix\n for row in D:\n # sort the row from smallest distance to largest distance\n sorted_row = np.sort(row)\n # calculate the mean of the smallest k+1 distances\n k_avg.append(np.mean(sorted_row[0:k]))\n # find the median of the averages\n kmedian_dist = np.median(k_avg)\n if kmedian_dist &gt;= threshold:\n chosen_k = k\n break\n # return the number of nearest neighbors to use\n return chosen_k\n\ndef autoselect_K_other(X, n_neighbors_max, threshold):\n D = euclidean_distances(X, X)\n for k in range(2, n_neighbors_max):\n kmedian_dist = np.median([np.mean(row[np.argpartition(row, k)]) for row in D])\n if kmedian_dist &gt;= threshold:\n return k\n\n return n_neighbors_max\n\n# Rudimentary performance check\nX = np.random.randint(5, size=(10000, 10))\n\nstart = time()\nresult = autoselect_K_orig(X, 20, 4)\nend = time()\ntotal_orig = end - start\nprint('Original: ', total_orig)\n\nstart = time()\nresult = autoselect_K_other(X, 20, 4)\nend = time()\ntotal_other = end - start\nprint('Other: ', total_other)\n\nprint('Speedup: ', total_orig / total_other)\n</code></pre>\n\n<p>On my outdated hardware, a typical output is:</p>\n\n<pre><code>Original: 57.56129217147827\nOther: 2.257129192352295\nSpeedup: 25.501992693422242\n</code></pre>\n\n<p>Meaning speedups of <strong>more than 25x</strong>. Not surprisingly, this speedup is strongly linked to the value of <code>n_neighbors_max</code>; if you make it very small, the speedup tends to go as low as 2x, but as you can see, it grows quite considerably for larger values, which is probably exactly what you want.</p>\n\n<ul>\n<li><p>I think further optimization even with your current approach is still possible. For instance, notice that everytime that you increment k, you are essentially duplicating work you have already done by <em>again</em> taking the first (k-1) elements, taking their mean, and so on. Instead, for step k, you should have stored the mean of step (k-1), and then you simply update this mean with a new element that now comes in, reducing the amount of computation you need to do.</p></li>\n<li><p>Even without such an optimization, you could still get some gains by getting rid of the explicit <code>for</code> loop that goes from 2 to <code>n_neighbors_max</code> by using a suitable generator expression that asks for more elements for as long as we've not extracted an element of at least the threshold.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T09:28:47.817", "Id": "236279", "ParentId": "236265", "Score": "3" } } ]
{ "AcceptedAnswerId": "236279", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T00:35:13.817", "Id": "236265", "Score": "3", "Tags": [ "python", "performance", "machine-learning" ], "Title": "Slow python code that automatically selects k for KNNG" }
236265
<p>I have created a Modal, at the bottom of my CV to show various different resources and content creators that I have used to learn how to code, I have nearly finished this project and will be sending it out to companies maybe in the next few months. This modal animates in and out of the page by sliding down and blurring aswell as changing the opacity and using a filter with a hue rotate. This code works fully as I intend it to Although I have still not tested it on Chrome, opera or Safari(seeing as I don't have a Mac or IPhone). I have a couple of concerns which I thought I'd add to the post as thats what the 'How to ask a good question' guide said could be included.</p> <p>My Html is here:</p> <pre><code>&lt;section id="Mentors"&gt; &lt;p&gt;Mentors, Teachers &amp; External Resources.&lt;/p&gt; &lt;img class="close_btn_png" src="Resources/imgs/Pngs/Close.png" width="600" height="600" type="image/png"&gt; &lt;div class="circ_con"&gt;&lt;br&gt;&lt;br&gt;&lt;/div&gt; &lt;p&gt;Without these peoples contributions and Tutorials,&lt;br&gt; I would not have been able to learn How to Code,&lt;br&gt; or at-least it would have taken me about 20x longer.&lt;/p&gt; &lt;/section&gt; &lt;img class="btm_help_ico" src="Resources/imgs/Pngs/help.png" width="16" height="16"&gt; </code></pre> <p>I've not included my full html as that would be far to long. My Css is Here:</p> <pre><code> #Mentors{ display:block; position:absolute; width:100vw; height:18vh; font-family:'Fondamento',cursive; bottom:0 !important; left:0px; border-top:dotted 4.8px yellow; background-image:linear-gradient(-33deg, rgba(16, 227, 223,1), rgba(5, 158, 158,1), rgba(2,59,42,1), rgba(2,59,42,1)); z-index:5000; will-change:auto; } #Mentors::before{ content:""; display:block; position:absolute; width:100vw; height:18vh; filter:opacity(0.5) hue-rotate(22deg) blur(0.8px); bottom:0 !important; left:-2.875px; border-top:dotted 4.8px yellow; background-image:linear-gradient(-123deg, blue, rgba(16, 227, 223,1), rgba(5, 158, 158,1), rgba(2,59,42,1), rgba(2,59,42,1), green); z-index:5001; } #Mentors p{ z-index:5002; transform:translateZ(200px); filter:blur(0.44px); text-shadow:1px 1px 1px teal; } .close_btn_png{ position:absolute; cursor: pointer; transform:scale(0.07); top:-275px; right:-268px; filter:blur(9.77px); z-index:5002; } .btm_help_ico{ position:absolute; bottom:8px; right:8px; z-index:5555; } </code></pre> <p>My Javascript is here:</p> <pre><code>const Ment = document.getElementById("Mentors"); const CloseBtn = document.getElementsByClassName("close_btn_png")[0]; const BtmHelpBtn = document.getElementsByClassName("btm_help_ico")[0]; BtmHelpBtn.addEventListener("click",(function(){ Ment.animate({ transform: ['translateY(300px)', 'translateY(0px)'], filter: ['blur(2.2px) hue-rotate(180deg) opacity(0.74)', 'blur(0px) hue-rotate(0deg) opacity(1)'] },{ duration: 2333.3333333333333333333333333333, easing: 'ease-in-out', iterations: 1, }).then(setTimeout(()=&gt;{ Ment.style.display = "block"; BtmHelpBtn.style.display = "none"; }, 2748)); })) CloseBtn.addEventListener("click",(function(){ // let MenState = `Clicked`; Ment.animate({ transform: ['translateY(0px)', 'translateY(300px)'], filter: ['blur(0px) hue-rotate(0deg) opacity(1)', 'blur(2.2px) hue-rotate(180deg) opacity(0.74)'] },{ duration: 2746, easing: 'ease-in-out', iterations: 1, }).then(setTimeout(()=&gt;{ Ment.style.display = "none"; BtmHelpBtn.style.display = "block"; }, 2748)); })); </code></pre> <p>My Concerns Are:</p> <p>1) although the code is working, Firefox is giving an error in the console saying:<br> ....TypeError: Ment.animate(...).then is not a function. Although its giving an error its still doing exactly what I asked it to do which is remove the help Icon after the animation has completed. So I'm a bit confused. I tried Chaneing the .then() on there sometime last week &amp; it did not work, then I retried it again Today &amp; it started working. So is this Valid Syntax or is it not very good practice? is there a better way to do this.</p> <p>2) Can this code be optimized, I included Will-Change:auto; into my Css and it seemed to make it run a bit smoother, but when viewing the performance tab in Firefox developer edition there is still alot of paints and re-calculating Styles. Not sure if its worth me posting a screen shot of the performance tree if that would help anyone viewing this post.</p> <p>3) is more of a question than a concern, do animations run smoother if you keep to multiples of 16ms? as 1000ms(1s) / 60 = 16.6SumNumberofSix'sThenA7 Was just wondering if perfomance wise(Wther there a good rule of thumb) or is it totally arbitrary and doesn't matter in the slightest? </p> <p>I would ask if this code can be shorter but since I'm almost a complete novice or beginner I'm guessing the answer to this is most definately yes.</p> <p>Can anyone suggest any edits or ways to improve this code. Currently runs at between 22fps and 60fps, 20 being when You click multiple buttons. considering my last project the worst was like 4fps I think the .animate() api is a step forward, in the right direction. I think Another Aspect that is affecting the fps at there lowest is the fact that the page has a rotating Carousel animation which is constant and two hd marble gifs which are animating also. these will be optimized on there own when I get round to it.</p> <p>One optimization I can think of myself is to resize the Close Button Png myself, in Gimp Photo manipulation instead of having the page do this via transform Scale its currently (600x600px) which is huge, scaling down to about 40px &amp; then maybe Convert it to a WebP image. </p> <p>Can Anyone suggest some good references or articles/tutorials about Vanilla Javascript .animate() API, there doesn't seem to be a whole lot of documentation on this[When I first Searched], mainly the JQuery version &amp; the MDN article does not cover much about hover effect glitches, timing or optimizations. If I do find any resources regarding this I will add them at the bottom here for other peoples reference. I have been switching all of my Css Animations over to .animate() but the timings of the hover states are being very difficult to get right, If your an expert at these please make a youtube tutorial series.</p> <p><a href="https://drafts.csswg.org/web-animations/#use-cases" rel="nofollow noreferrer">Csswg.com ~ web Animations Api</a><br> Just Found this which might solve some of my issues or concerns.<br> <a href="https://docs.w3cub.com/haxe~javascript/html/animationplaystate/" rel="nofollow noreferrer">docs.w3cub.com ~ animationPlayState</a></p> <p>Any other pointers would be greatly appreciated. </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T00:37:18.090", "Id": "236266", "Score": "2", "Tags": [ "javascript", "css", "html5" ], "Title": "Code to Animate A modal at the Bottom of the page using .animate() api" }
236266
<p>Based on <a href="https://www.thebiccountant.com/2019/10/03/parent-child-hierarchies-with-multiple-parents-in-power-bi-with-power-query/" rel="nofollow noreferrer">this article</a></p> <p>And this question posted on the <a href="https://community.powerbi.com/t5/Power-Query/Add-index-to-hierarchy-leves-for-later-sorting/m-p/851839" rel="nofollow noreferrer">power bi forums</a></p> <h2>Objectives:</h2> <p>Resolve a hierarchy (parent - child relationship) in <em>Power Query</em> adding levels and their corresponding sorting columns.</p> <p>The final result can be used in a Power Pivot table and use it to generate a dynamic P&amp;L.</p> <p>Key point was to add the sorting levels, so you can in <em>Power Pivot</em> use the <code>Sort by column</code> feature</p> <p>One can achieve this with <em>DAX</em> formulas.</p> <hr> <p><a href="https://i.stack.imgur.com/zcGZ1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zcGZ1.png" alt="Source table"></a></p> <hr> <p><a href="https://i.stack.imgur.com/7jnQu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7jnQu.png" alt="Results"></a></p> <hr> <h2><strong>Code</strong></h2> <pre><code>let func = (SourceTable as table, NodeKey as text, ParentKey as text, LabelColumn as text, Prefix as text, CompleteOutput as logical) =&gt; let /* //Debug Parameters //Debug Parameters SourceTable = TableSample, NodeKey = "Account", ParentKey = "AccountParent", LabelColumn = "Name", CompleteOutput = true, Prefix = "C", */ SelectRelevantColumns = Table.SelectColumns(SourceTable, {NodeKey,ParentKey,LabelColumn}), ChangeType = Table.TransformColumnTypes(SelectRelevantColumns, { {NodeKey,type text}, {ParentKey,type text} }), ReplaceNulls = Table.ReplaceValue(ChangeType, null, "", Replacer.ReplaceValue, {ParentKey}), MissingParents = List.Buffer(List.Select(List.Difference(List.Distinct(Table.Column(ReplaceNulls, ParentKey)), List.Distinct(Table.Column(ReplaceNulls, NodeKey))), each _ &lt;&gt; "")), AddMissingParents = Table.Buffer(Table.Combine({ ReplaceNulls, #table({ NodeKey, LabelColumn, ParentKey }, List.Transform(MissingParents, each { _, "Unknown TopLevel" &amp; Text.From(List.PositionOf(MissingParents, _)), "" })) })), MergeQueriesMissingParents = Table.NestedJoin(AddMissingParents, {NodeKey}, AddMissingParents, {ParentKey}, "SelectRelevantColumns", JoinKind.LeftOuter), CheckIfIsLeaf = Table.AddColumn(MergeQueriesMissingParents, "IsLeaf", each if Table.IsEmpty([SelectRelevantColumns]) then "yes" else "no", type logical), ReplaceNullsParentLabelCols = Table.ReplaceValue(CheckIfIsLeaf, null, "", Replacer.ReplaceValue, { ParentKey, LabelColumn }), AddStartPath = Table.AddColumn(ReplaceNullsParentLabelCols, "Path", each Text.Trim(Record.Field(_, NodeKey) &amp; "|" &amp; Record.Field(_, ParentKey), "|")), AddTempLabelColumn = Table.DuplicateColumn(AddStartPath, LabelColumn, "TempLabelColumn"), AddTempParentKeyColumn = Table.DuplicateColumn(AddTempLabelColumn, ParentKey, "TempParentKey"), // Retrieve all parents per row fnRetrieveAllParents = List.Generate(() =&gt; [Result = AddTempParentKeyColumn, Level = 1], each Table.RowCount([Result]) &gt; 0 and[Level] &lt;= 7, each [Result = let MergeQueries = Table.NestedJoin([Result], { ParentKey }, AddMissingParents, { NodeKey }, "Added Custom", JoinKind.Inner), RemoveColumns1 = Table.RemoveColumns(MergeQueries, { ParentKey }), ExpandAddedCustom = Table.ExpandTableColumn(RemoveColumns1, "Added Custom", { ParentKey, LabelColumn }, { "ParentKey.1", "Name.1" }), DuplicateColumn = Table.DuplicateColumn(ExpandAddedCustom, "ParentKey.1", ParentKey), MergeColumns = Table.CombineColumns(DuplicateColumn, { "Path", "ParentKey.1" }, Combiner.CombineTextByDelimiter("|", QuoteStyle.None), "Path"), MergeColumns2 = Table.CombineColumns(MergeColumns, { LabelColumn, "Name.1" }, Combiner.CombineTextByDelimiter("|", QuoteStyle.None), LabelColumn) in MergeColumns2, Level = [Level] + 1 ]), ConvertAllParentsToTable = Table.FromList(fnRetrieveAllParents, Splitter.SplitByNothing(), null, null, ExtraValues.Error), ExpandAllParentsLevel = Table.ExpandRecordColumn(ConvertAllParentsToTable, "Column1", {"Result","Level"}, {"Result","Level"}), ExpandAllParentsResult = Table.ExpandTableColumn(ExpandAllParentsLevel, "Result", {LabelColumn,ParentKey,NodeKey,"Path","TempLabelColumn","TempParentKey"}, {"LabelColumn","ParentKey","NodeKey","Path","TempLabelColumn","TempParentKey"}), FilterAllParents = Table.SelectRows(ExpandAllParentsResult, each([ParentKey] = null or [ParentKey] = "")), RemoveParentKeyCol = Table.RemoveColumns(FilterAllParents, { "ParentKey" }), RemoveLastPipeFromPath = Table.TransformColumns(RemoveParentKeyCol, { { "Path", each Text.Trim(_, "|") } }), ReverseOrderLabelColumn = Table.TransformColumns(RemoveLastPipeFromPath, { { "LabelColumn", each Text.Combine(List.Reverse(Text.Split(_, "|")), "|") } }), ReverseOrderPath = Table.TransformColumns(ReverseOrderLabelColumn, { { "Path", each Text.Combine(List.Reverse(Text.Split(_, "|")), "|") } }), ReorderTempCols = Table.ReorderColumns(ReverseOrderPath, { "NodeKey", "TempParentKey", "Path", "TempLabelColumn", "Level", "LabelColumn" }), SplitLabelColByLevel = Table.SplitColumn(ReorderTempCols, "LabelColumn", Splitter.SplitTextByDelimiter("|", QuoteStyle.Csv), List.Transform({ 1..Table.RowCount(ConvertAllParentsToTable) }, each Prefix &amp; " Level " &amp; Text.From(_))), // Fill to the right DemoteHeaders = Table.DemoteHeaders(SplitLabelColByLevel), TransposeTable = Table.Transpose(DemoteHeaders), FillDown = Table.FillDown(TransposeTable, Table.ColumnNames(TransposeTable)), DeTransposeTable = Table.Transpose(FillDown), PromoteHeaders = Table.PromoteHeaders(DeTransposeTable, [PromoteAllScalars = true]), MergeSourceTable = Table.NestedJoin(PromoteHeaders, { "NodeKey", "TempParentKey" }, Table.ReplaceValue(SourceTable, null, "", Replacer.ReplaceValue, {ParentKey}), { NodeKey, ParentKey }, "MergedSourceTable", JoinKind.LeftOuter), ExpandSourceTable = Table.ExpandTableColumn(MergeSourceTable, "MergedSourceTable", List.Difference(Table.ColumnNames(SourceTable), Table.ColumnNames(ReplaceNullsParentLabelCols))), ListParents = List.Buffer(ExpandSourceTable[TempParentKey]), AddColIsLeaf = Table.AddColumn(ExpandSourceTable, "IsLeaf", each not List.Contains(ListParents, [NodeKey])), RenameTempCols = Table.RenameColumns(AddColIsLeaf, { { "Level", "HierarchyDepth" }, { "NodeKey", NodeKey }, { "TempLabelColumn", LabelColumn }, { "TempParentKey", ParentKey } }), AddLevelSorting = Table.AddColumn(RenameTempCols, Prefix &amp; " Sorting", each Text.Combine(List.Transform(Text.Split([Path], "|"), each Text.AfterDelimiter(_, ".", { 0, RelativePosition.FromEnd })), "|")), ExpandLevelSorting = Table.SplitColumn(AddLevelSorting, Prefix &amp; " Sorting", Splitter.SplitTextByDelimiter("|", QuoteStyle.Csv), List.Transform({ 1..Table.RowCount(ConvertAllParentsToTable) }, each Prefix &amp; " Sorting " &amp; Text.From(_))), AddColumnLevel2 = if Table.HasColumns(ExpandLevelSorting, Prefix &amp; " Level 2") then ExpandLevelSorting else Table.AddColumn(ExpandLevelSorting, Prefix &amp; " Level 2", each null, type text), AddColumnLevel3 = if Table.HasColumns(AddColumnLevel2, Prefix &amp; " Level 3") then AddColumnLevel2 else Table.AddColumn(AddColumnLevel2, Prefix &amp; " Level 3", each null, type text), AddColumnLevel4 = if Table.HasColumns(AddColumnLevel3, Prefix &amp; " Level 4") then AddColumnLevel3 else Table.AddColumn(AddColumnLevel3, Prefix &amp; " Level 4", each null, type text), AddColumnLevel5 = if Table.HasColumns(AddColumnLevel4, Prefix &amp; " Level 5") then AddColumnLevel4 else Table.AddColumn(AddColumnLevel4, Prefix &amp; " Level 5", each null, type text), AddColumnLevel6 = if Table.HasColumns(AddColumnLevel5, Prefix &amp; " Level 6") then AddColumnLevel5 else Table.AddColumn(AddColumnLevel5, Prefix &amp; " Level 6", each null, type text), AddColumnLevel7 = if Table.HasColumns(AddColumnLevel6, Prefix &amp; " Level 7") then AddColumnLevel6 else Table.AddColumn(AddColumnLevel6, Prefix &amp; " Level 7", each null, type text), AddColumnSorting2 = if Table.HasColumns(AddColumnLevel7, Prefix &amp; " Sorting 2") then AddColumnLevel7 else Table.AddColumn(AddColumnLevel7, Prefix &amp; " Sorting 2", each null, Int64.Type), AddColumnSorting3 = if Table.HasColumns(AddColumnSorting2, Prefix &amp; " Sorting 3") then AddColumnSorting2 else Table.AddColumn(AddColumnSorting2, Prefix &amp; " Sorting 3", each null, Int64.Type), AddColumnSorting4 = if Table.HasColumns(AddColumnSorting3, Prefix &amp; " Sorting 4") then AddColumnSorting3 else Table.AddColumn(AddColumnSorting3, Prefix &amp; " Sorting 4", each null, Int64.Type), AddColumnSorting5 = if Table.HasColumns(AddColumnSorting4, Prefix &amp; " Sorting 5") then AddColumnSorting4 else Table.AddColumn(AddColumnSorting4, Prefix &amp; " Sorting 5", each null, Int64.Type), AddColumnSorting6 = if Table.HasColumns(AddColumnSorting5, Prefix &amp; " Sorting 6") then AddColumnSorting5 else Table.AddColumn(AddColumnSorting5, Prefix &amp; " Sorting 6", each null, Int64.Type), AddColumnSorting7 = if Table.HasColumns(AddColumnSorting6, Prefix &amp; " Sorting 7") then AddColumnSorting6 else Table.AddColumn(AddColumnSorting6, Prefix &amp; " Sorting 7", each null, Int64.Type), ReorderCols = Table.ReorderColumns(AddColumnSorting7, Table.ColumnNames(SourceTable) &amp; { "Path", "HierarchyDepth", "IsLeaf", Prefix &amp; " Level 1", Prefix &amp; " Level 2", Prefix &amp; " Level 3", Prefix &amp; " Level 4", Prefix &amp; " Level 5", Prefix &amp; " Level 6", Prefix &amp; " Level 7", Prefix &amp; " Sorting 1", Prefix &amp; " Sorting 2", Prefix &amp; " Sorting 3", Prefix &amp; " Sorting 4", Prefix &amp; " Sorting 5", Prefix &amp; " Sorting 6", Prefix &amp; " Sorting 7"}), ChangeColTypes = Table.TransformColumnTypes(ReorderCols, { { NodeKey, type text }, { LabelColumn, type text }, { ParentKey, type text }, { "Path", type text }, { "HierarchyDepth", Int64.Type }, { "IsLeaf", type logical }, { Prefix &amp; " Level 1", type text }, { Prefix &amp; " Level 2", type text }, { Prefix &amp; " Level 3", type text }, { Prefix &amp; " Level 4", type text }, { Prefix &amp; " Level 5", type text }, { Prefix &amp; " Level 6", type text }, { Prefix &amp; " Level 7", type text }, { Prefix &amp; " Sorting 1", Int64.Type }, { Prefix &amp; " Sorting 2", Int64.Type }, { Prefix &amp; " Sorting 3", Int64.Type }, { Prefix &amp; " Sorting 4", Int64.Type }, { Prefix &amp; " Sorting 5", Int64.Type }, { Prefix &amp; " Sorting 6", Int64.Type }, { Prefix &amp; " Sorting 7", Int64.Type } }), SortCols = Table.Sort(ChangeColTypes, { { Prefix &amp; " Sorting 1", Order.Ascending }, { Prefix &amp; " Sorting 2", Order.Ascending }, { Prefix &amp; " Sorting 3", Order.Ascending }, { Prefix &amp; " Sorting 4", Order.Ascending }, { Prefix &amp; " Sorting 5", Order.Ascending }, { Prefix &amp; " Sorting 6", Order.Ascending }, { Prefix &amp; " Sorting 7", Order.Ascending } }), RemoveCols = Table.RemoveColumns(SortCols,{"Path", "HierarchyDepth", "IsLeaf"}), ChooseOutput = if CompleteOutput = true then SortCols else RemoveCols in ChooseOutput , documentation = [ Documentation.Name = " Table.ResolveParentChild", Documentation.Description = " Creates columns for all parents, multiple parents are supported", Documentation.LongDescription = " Creates columns for all parents, multiple parents are supported", Documentation.Category = "Table", Documentation.Source = "local", Documentation.Author = "Imke Feldmann: www.TheBIccountant.com | Adapted by Ricardo Diaz www.ricardodiaz.co", Documentation.Examples = {[Description = "See: http://wp.me/p6lgsG-sl for more details", Code = "", Result = "" ]} ] in Value.ReplaceType(func, Value.ReplaceMetadata(Value.Type(func), documentation)) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T00:45:15.027", "Id": "236267", "Score": "2", "Tags": [ "excel", "dax", "m-code" ], "Title": "Resolve parent child hierarchy in Power Query M code with sorting columns" }
236267
<p>I created this console app that gets some JSON strings from a web request using a <code>Parallel.For</code> loop, </p> <pre><code>class Program { private static readonly object ConsoleLock = new object(); static void Main(string[] args) { //DECLARATION var link = "http://www.mytestrequest.com/id=" int start = 1000; int end = 2000; var requestDid = 0; var requestToDo = end - start; ParallelOptions parallelOptions = new ParallelOptions(); parallelOptions.MaxDegreeOfParallelism = 8; List&lt;string&gt; jsonResponses = new List&lt;string&gt;(); var baseAddress = new Uri("http://www.mytestrequest.com"); var cookieContainer = new CookieContainer(); cookieContainer.Add(baseAddress,new Cookie("JSESSIONID", "xxx")); var handler = new HttpClientHandler() {CookieContainer = cookieContainer}; var client = new HttpClient(handler) {BaseAddress = baseAddress}; //CODE START HERE var task = Parallel.For((long)start, (long)end, parallelOptions, async i =&gt; { lock (ConsoleLock) { Console.SetCursorPosition(0, 0); Console.Write($"Progress {requestDid++}/{requestToDo} "); } jsonResponses.Add(client.GetStringAsync(link + i).Result); }); while (!task.IsCompleted) { Thread.Sleep(1000); } Console.WriteLine("Writing to file"); using (var streamWriter = new StreamWriter("N:/sctest.txt")) { foreach (var sc in jsonResponses) { streamWriter.WriteLine(sc); } } client.Dispose(); handler.Dispose(); } </code></pre> <p>I was trying to achieve the best result performance for this purpose and I thought it was possible to <strong>write to a file what I already got in the list while still downloading other elements</strong> but didn't know how to achieve it, should I use <code>ContinueWith()</code>? But how?</p> <p>I would also like to avoid to make too many requests at the same time, what I've noticed is that if I try to add the await to the <code>GetStringAsync()</code> it seems to make thousands of requests at same time, instead, if I wait the <code>Result</code> this seems to only move over following the <code>MaxDegreeOfParallelism</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T15:06:03.830", "Id": "462980", "Score": "0", "body": "We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T11:39:41.910", "Id": "463293", "Score": "0", "body": "Hi @BCdotWEB how i can make working correctly a code that has access to a session aware web page? Should i simulate request delay with Thread.sleep?" } ]
[ { "body": "<p>You have a lot of interesting things going on in your code. There are many ways to solve your problem, here is an approach utilizing an <code>ActionBlock</code>. I used .NET Core 3.1 to build the sample, but <code>ActionBlock</code> is available in the System.Threading.Tasks.Dataflow NuGet Package if it isn't included in your framework by default.</p>\n\n<p>1) Change your entry point from <code>static void Main(string[] args</code> to <code>static async Task Main(string[] args</code> async main has been available since C#7.1 (<a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-1\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-1</a>). If you can't use C#7.1 or greater, you can still do it with something like <code>DoAsyncWork().GetAwaiter().GetResult()</code></p>\n\n<p>2) <code>List</code> is not guaranteed to be thread safe and I noticed you add to your list outside your lock. I elected to use a <code>ConcurrentDictionary</code> instead since that is guaranteed thread safe. I try to avoid my own locks whenever I can and in this case, if you get rid of the Console writes, you could dump your lock altogether.</p>\n\n<p>3) I elected to use <code>Interlocked.Increment(ref requestDid)</code> instead of <code>{requestDid++}</code> and then read it with an <code>Interlocked.Read</code>. Interlocked operations are thread safe, so you would be okay to use these even if you removed <code>lock (ConsoleLock)</code> (although you are only using those variables to write to the Console anyway)</p>\n\n<p>4) In an async/await world, <code>Thread.Sleep</code> is almost always wrong. You usually want to <code>await Task.Delay</code> instead. <a href=\"https://stackoverflow.com/questions/20082221/when-to-use-task-delay-when-to-use-thread-sleep\">https://stackoverflow.com/questions/20082221/when-to-use-task-delay-when-to-use-thread-sleep</a></p>\n\n<p>5) I didn't <code>Dispose</code> the httpclient or handler because of <a href=\"https://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed\">https://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed</a> (although since the program is terminating anyway, it doesn't really matter in this case)</p>\n\n<p>6) As far as the <code>ActionBlock</code> goes, there are a lot of articles out there on it, but here is an ok start <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/dataflow-task-parallel-library\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/dataflow-task-parallel-library</a>. Note how I set <code>EnsureOrdered</code> to false. If you don't need the items to be processed in order, I find it best to set it to false. In this case, since you are writing the file after you have retrieved ALL the results, you could simply sort the values coming out of the <code>ConcurrentDictionary</code></p>\n\n<p>I set <code>SingleProducerConstrained</code> to true, because in this case post is not being called concurrently. This allows the ActionBlock to make some optimizations. <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.dataflow.executiondataflowblockoptions.singleproducerconstrained?view=netcore-3.1\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.dataflow.executiondataflowblockoptions.singleproducerconstrained?view=netcore-3.1</a></p>\n\n<p><code>MaxDegreesOfParallelism</code> can be a tough choice. I sometimes cringe when I see a hardcode for that in real world applications because the optimal value for this will likely vary based on what hardware or virtualization platform you are running on. However, the optimal value can be hard to come by, especially when running a container. This is a great example of how nuanced the choice can be. <a href=\"https://github.com/dotnet/runtime/issues/622\" rel=\"nofollow noreferrer\">https://github.com/dotnet/runtime/issues/622</a></p>\n\n<p>7) Finally, I have found when testing performance like this, to make sure you do so <strong>WITHOUT a debugger attached</strong>. Attached debuggers can really slow things down. I built this code in release mode and then ran it from the command line.</p>\n\n<pre><code>using System;\nusing System.Collections.Concurrent;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Threading.Tasks.Dataflow;\n\nnamespace RequestTest\n{\n static class Program\n {\n static async Task Main(string[] args)\n {\n var startTime = Stopwatch.GetTimestamp();\n //DECLARATION \n int start = 1000;\n int end = 2000;\n long requestDid = 0;\n var requestToDo = end - start;\n\n object ConsoleLock = new object();\n ConcurrentDictionary&lt;string, string&gt; jsonResponses = new ConcurrentDictionary&lt;string, string&gt;();\n var baseAddress = new Uri(\"https://localhost:5001/\");\n var cookieContainer = new CookieContainer();\n cookieContainer.Add(baseAddress, new Cookie(\"JSESSIONID\", \"xxx\"));\n var handler = new HttpClientHandler() { CookieContainer = cookieContainer };\n var client = new HttpClient(handler) { BaseAddress = baseAddress };\n var actionBlock = new ActionBlock&lt;string&gt;(async x =&gt;\n {\n var response = await client.GetStringAsync(new Uri(baseAddress + x));\n jsonResponses.TryAdd(x, response); //note this actually returns a bool to indictate if it was added successfully, as long as x is unqiue, I can't imagine a scenario where this would return false\n lock (ConsoleLock)\n {\n Console.SetCursorPosition(0, 0);\n Interlocked.Increment(ref requestDid);\n Console.Write($\"Progress {Interlocked.Read(ref requestDid)}/{requestToDo} \");\n }\n\n }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 8, EnsureOrdered = false, SingleProducerConstrained = true }); \n\n for (var counter = start; counter&lt;end; counter++)\n {\n actionBlock.Post(\"api/test?requestid=\"+counter.ToString());\n }\n actionBlock.Complete();\n await actionBlock.Completion;\n var endRequestTime = Stopwatch.GetTimestamp();\n Console.WriteLine();\n Console.WriteLine();\n Console.WriteLine();\n Console.WriteLine();\n Console.WriteLine($\"Executed Requests in {(endRequestTime - startTime)} ticks\");\n Console.WriteLine(\"Writing to file\");\n\n using (var streamWriter = new StreamWriter(\"C:\\\\temp\\\\sctest.txt\"))\n {\n foreach (var sc in jsonResponses.Values)\n {\n streamWriter.WriteLine(sc);\n }\n }\n\n var endFileTime = Stopwatch.GetTimestamp();\n Console.WriteLine($\"Completed File write in {(endFileTime - endRequestTime)} ticks\");\n }\n }\n}\n\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T11:26:13.223", "Id": "463291", "Score": "0", "body": "Hi Nelson, thanks for your complete answer, i tried and in terms of speed it is really efficient and probably, using atomic operation, it's also safe. I want to ask one more thing, isn't there a possibility to handle when an item has been inserted into the collection and automatically write it to file? Maybe creating a sort of queue without waiting the actionblock to complete his cycle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T14:41:31.647", "Id": "463609", "Score": "0", "body": "Yes, there are a bunch of ways to accomplish this. You would have to benchmark which approach worked best. I didn't include it in my answer because the writes to the file take a small fraction of the time compared to the requests (at least with my tests). You could link to another ActionBlock (I think) or perhaps a more elegant TPL Dataflow solution using a different type of dataflow block. I tried an example using https://devblogs.microsoft.com/dotnet/an-introduction-to-system-threading-channels/ and it wasn't any faster than my posted solution, so I am not going to post it here." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T13:06:09.063", "Id": "236291", "ParentId": "236268", "Score": "2" } } ]
{ "AcceptedAnswerId": "236291", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T01:26:20.247", "Id": "236268", "Score": "2", "Tags": [ "c#", "performance", "beginner", "multithreading" ], "Title": "Write strings to a file while downloading new one simultaneous" }
236268
<p>I am very new to PHP coding, hence just wanted to know if my coding is prone to any SQL injection attack or any other kind of threat. Below is the code for adding client to the database:</p> <pre><code>&lt;?php $response = array(); include 'db/db_connect.php'; include 'functions.php'; //Get the input request parameters $inputJSON = file_get_contents('php://input'); $input = json_decode($inputJSON, TRUE); //convert JSON into array //Check for Mandatory parameters if(isset($input['clientName']) &amp;&amp; isset($input['siteName'])){ $clientName = $input['clientName']; $siteName = $input['siteName']; //Check if client already exist if(!clientExists($clientName, $siteName)){ //Query to add new material $insertQuery = "INSERT INTO clients(clientName, siteName) VALUES (?,?)"; if($stmt = $con-&gt;prepare($insertQuery)){ $stmt-&gt;bind_param("ss",$clientName,$siteName); $stmt-&gt;execute(); $response["status"] = 0; $response["message"] = "Client created"; $stmt-&gt;close(); } } else{ $response["status"] = 1; $response["message"] = "Client exists"; } } else{ $response["status"] = 2; $response["message"] = "Missing mandatory parameters"; } echo json_encode($response); ?&gt; </code></pre> <p>Code for clientExists() function is as follows:</p> <pre><code>function clientExists($clientName,$siteName){ $query = "SELECT clientName FROM clients WHERE clientName = ? AND siteName=?"; global $con; if($stmt = $con-&gt;prepare($query)){ $stmt-&gt;bind_param("ss",$clientName,$siteName); $stmt-&gt;execute(); $stmt-&gt;store_result(); $stmt-&gt;fetch(); if($stmt-&gt;num_rows == 1){ $stmt-&gt;close(); return true; } $stmt-&gt;close(); } return false; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T07:24:11.523", "Id": "462910", "Score": "0", "body": "What is your threat model?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T07:40:06.387", "Id": "462911", "Score": "1", "body": "I did not get what you mean by threat model. I am using php to prepare web service for my android app. This app has some menus one of which is to create a client. I'll be grateful if you can elaborate a bit more on this..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T08:00:31.007", "Id": "462916", "Score": "0", "body": "Thank you so much for the information. I will definitely study more about threat model and incorporate things which apply to my code. Once again thank you very much for your quick response..." } ]
[ { "body": "<p>SQL injection should not be a problem, as long as you pass any user input to queries through placeholders, which you do.</p>\n\n<p>I have a few other remarks though</p>\n\n<h1>Single Responsibility Principle</h1>\n\n<p>In the first code snippet you do too much things. You decode request json, you talk to db. you handle the logic, you maintain response structure. It would be wise to separate those things into their own scopes (functions/classes). Of course if this is all you ever intend to have there may be no point. But in general, in future you will want to reuse the individual pieces.</p>\n\n<h1>Global Scope vs. Classes and Dependency Injection</h1>\n\n<p>You may want to avoid definind global variables. It's generaly considered bad practise for several reason which I'm not gonna repeat here as there is plenty of information sources for this already.</p>\n\n<p>You are probably not very familiar with the concept of OOP, but wrapping those function into class scopes and working with objects may be something for you to learn.</p>\n\n<p>If you want to stick with procedural style, maybe at least get rid of the globals by passing the db connection always as function parameter.</p>\n\n<pre><code>if (clientExists($connection, $clientName)) {...}\n</code></pre>\n\n<p>It is annoying but it is still better then globals, in some ways anyway.\nThat where the objects could help if you get used to it.</p>\n\n<pre><code>$users-&gt;exists($clientName)\n</code></pre>\n\n<h1>Data Validation</h1>\n\n<p>You check that $input['clientName'] is set. Is it enough? What if it is empty? What if it is array or number? Is it ok? What if $input is not an array in the first place? All that should be handled.</p>\n\n<p>Validation is btw, yet another responsibility that might be separated to its own function.</p>\n\n<h1>Useless Statements</h1>\n\n<p>In the clientExists() function I think you fetch the row for now reason. It should be able to tell count without fetching it.\nYou can also simplify the select from <code>SELECT clientName</code> to <code>SELECT 1</code> which is, IMO, cleaner as you could actualy select any of the table's column for it to work and if that column ever changes name this would have to change too.</p>\n\n<h1>Public API</h1>\n\n<p>At this point your api is public in whichever network in which it is deployed. As this network is probably going to be the internet (I suppose), anyone will be able to call it. Is it ok if any anonymous client can succesfully call this endpoint and so create db entries? You may want to have some way of authentication, but this depends on your use-case.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T08:03:36.903", "Id": "236274", "ParentId": "236273", "Score": "3" } }, { "body": "<p>in addition to what has already been said, I'd suggest not using <code>clientExists</code> at all. just have a <code>UNIQUE</code> constraint on <code>clientName, siteName</code> and let the database enforce this for you. </p>\n\n<p>the reason is that your current code is both doing more work than is needed (the check for existence) as well not enough (the gap between the existence check and inserting a new row is a race condition). generally the best place to handle this sort of check is the database</p>\n\n<p>see e.g. <a href=\"https://stackoverflow.com/q/3146838/1358308\">https://stackoverflow.com/q/3146838/1358308</a> for how to handle this with MySQL. I've not programmed PHP for a few years so don't know if there are any nice ways to handle this that generalise to other database engines.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-07T16:29:00.983", "Id": "236848", "ParentId": "236273", "Score": "0" } } ]
{ "AcceptedAnswerId": "236274", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T07:08:42.583", "Id": "236273", "Score": "3", "Tags": [ "beginner", "php", "security" ], "Title": "Is the code prone to SQL injection or to any other kind of threat" }
236273
<p>I'm currently trying to learn the basics of the Rust programming language, to do this my first piece of code after the classic 'Hello World' was a simple recursive Factorial function. </p> <p>This is the code:</p> <pre><code>use std::io; fn factorial(num: i64) -&gt; i64 { return if num == 1 { 1 }else{ num * factorial(num - 1) } } fn trim_newline(s: &amp;mut String){ if s.ends_with('\n'){ s.pop(); if s.ends_with('\r'){ s.pop(); } } } fn main() { let mut user_input = String::new(); println!("Welcome to rust-factorial!"); loop { user_input.clear(); println!("Please enter a number:"); match io::stdin().read_line(&amp;mut user_input) { Ok(_) =&gt; (), Err(_e) =&gt; { println!("error: {}", _e); continue; }, }; let num: i64 = match user_input.trim().parse::&lt;i64&gt;() { Ok(n) =&gt; n, Err(_e) =&gt; { trim_newline(&amp;mut user_input); // remove trailing newline println!("'{}' is not a valid number, full error: {}", user_input, _e); continue; }, }; println!("{}! is equal to {}", num, factorial(num)); } } </code></pre> <p>I am aware of one major issue with my current approach which is that the biggest number this program can calculate is the 20th number of the sequence. Asking for a number bigger than 20 results in the following error on my machine:</p> <pre><code>Please enter a number: 24 thread 'main' panicked at 'attempt to multiply with overflow', src\main.rs:7:9 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. error: process didn't exit successfully: `target\debug\rust-factorial.exe` (exit code: 101) </code></pre> <p>I'd like to know a few things:</p> <ul> <li>How can I change this code to be more "rust-like" <ul> <li>(by that I mean 'pythonic' but for rust) </li> </ul></li> <li>What would the rust approach be for solving the overflow that happens with numbers past 20? <ul> <li>(I could either hard-code the limit or something to that effect but I'm curious whether or not there is a guideline about this from a Rust perspective)</li> </ul></li> <li>Any and all comments on code quality, readability and potentially efficiency</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T13:22:14.273", "Id": "462953", "Score": "2", "body": "Please check the connection between title(&description) and the code presented." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T13:57:50.060", "Id": "462966", "Score": "0", "body": "@greybeard my bad, was confused, will edit this now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T21:22:10.873", "Id": "463035", "Score": "1", "body": "`0!=1`. I think your implementation Will go crazy when you input zero." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T06:33:42.410", "Id": "463068", "Score": "0", "body": "oops, nice catch @slepic will add that case to my function too!" } ]
[ { "body": "<h2>Bugs and types</h2>\n\n<p>You should think some about what types you want to have as input and output for <code>factorial</code>. Negative numbers won't ever work as input, and the output won't be negative, so you should consider using an unsigned integer, like <code>u64</code>. Even doing this, though, there's one input that leads to an infinite loop. See if you can find it and fix the function!</p>\n\n<h2>Cleaning up the error handling</h2>\n\n<pre><code>match io::stdin().read_line(&amp;mut user_input) {\n Ok(_) =&gt; (),\n Err(_e) =&gt; {\n println!(\"error: {}\", _e);\n continue;\n }\n};\n</code></pre>\n\n<p>A variable with a leading underscore tells readers (and linters) that the variable isn't going to be used. Since we use it (with the <code>println!</code>), we should just call it <code>e</code>.</p>\n\n<p>This error message should probably be in stderr, rather than stdout. This can be done just by changing it to <code>eprintln!</code> instead.</p>\n\n<p>When only one branch of a match actually does something, <code>if let</code> is both easier to write and understand. So in all, I'd change this part to</p>\n\n<pre><code>if let Err(e) = io::stdin().read_line(&amp;mut user_input) {\n eprintln!(\"error: {}\", e);\n continue;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>let num: i64 = match user_input.trim().parse::&lt;i64&gt;() {\n Ok(n) =&gt; n,\n Err(_e) =&gt; {\n trim_newline(&amp;mut user_input); // remove trailing newline\n println!(\"'{}' is not a valid number, full error: {}\", user_input, _e);\n continue;\n },\n};\n</code></pre>\n\n<p>Same thing with <code>_e</code> vs <code>e</code>. You're using the variable, so it shouldn't start with an underscore. Also the same thing with <code>eprintln!</code>. Errors should be printed to stderr.</p>\n\n<p>Since both branches of the match are used, <code>if let</code> is less useful. However, you might check out the answers to <a href=\"https://stackoverflow.com/questions/49785136/unwrap-or-continue-in-a-loop\">this question</a> for some ideas for making this look better. For a single use like this, you're probably fine, but if you do this \"unwrap or continue\" behavior a lot, it can help to encapsulate it.</p>\n\n<p>The <code>i64</code> annotations are unnecessary. The compiler has enough information to conclude that the type of <code>num</code> is <code>i64</code> since it's fed into <code>factorial</code>. If you want to keep an annotation for explicitness, that's fine, but only one of <code>num: i64</code> and <code>parse::&lt;i64&gt;</code> is needed for that.</p>\n\n<p><code>trim_newline</code> seems to be unnecessary. You're parsing <code>user_input.trim()</code> anyway, so just show that to the user if there's a parsing error.</p>\n\n<pre><code>let num = match user_input.trim().parse() {\n Ok(n) =&gt; n,\n Err(e) =&gt; {\n eprintln!(\"'{}' is not a valid number, full error: {}\", user_input.trim(), e);\n continue;\n }\n};\n</code></pre>\n\n<h2>Using standard tools for formatting and linting</h2>\n\n<p>One thing that goes a long way with making your code more readable and idiomatic is running <code>cargo fmt</code>. You may need to install it with <code>rustup component add rustfmt</code>.</p>\n\n<p>Clippy is another standard tool for catching errors and making your code more idiomatic. It can similarly be installed with <code>rustup</code> using <code>rustup component add clippy</code>. Running it (with <code>cargo clippy</code>) on your program, we get the warning</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>warning: unneeded `return` statement\n --&gt; src/main.rs:4:5\n |\n4 | / return if num == 1 {\n5 | | 1\n6 | | }else{\n7 | | num * factorial(num - 1)\n8 | | }\n | |_____^\n |\n = note: `#[warn(clippy::needless_return)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_return\nhelp: remove `return`\n |\n4 | if num == 1 {\n5 | 1\n6 | }else{\n7 | num * factorial(num - 1)\n8 | }\n |\n</code></pre>\n\n<p>Since the return statement is the last thing in the function, it's not needed since the last expression in the block is always implicitly returned. You can simply remove the <code>return</code>.</p>\n\n<h2>Some advice on overflows</h2>\n\n<p>The factorial function grows superexponentially, so any fixed-width integer type is going to quickly overflow. Even switching to <code>u128</code> only gets you up to an input of 34. The way I see it, you have two choices. Either</p>\n\n<ul>\n<li>Embrace this. Return an <code>Option</code> (or better yet, a <code>Result</code>) to indicate that an overflow occurred. Using something like <code>u64::checked_mul</code> would be helpful for that.</li>\n<li>Avoid overflow completely (barring memory limits) by using some sort of <code>BigInt</code>. The crate <a href=\"https://docs.rs/num-bigint/0.2.6/num_bigint/\" rel=\"nofollow noreferrer\"><code>num_bigint</code></a> has an implementation with everything you'd need here, including parsing, printing, multiplying and subtracting. You should be able to replace <code>i64</code> with <code>BigUint</code> (or <code>BigInt</code>) with only a few conversions from integer literals.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T14:01:03.630", "Id": "462968", "Score": "0", "body": "Thanks a lot for your detailed write-up :) I'll look through it and try to apply it!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T13:54:37.700", "Id": "236295", "ParentId": "236277", "Score": "3" } } ]
{ "AcceptedAnswerId": "236295", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T08:31:02.423", "Id": "236277", "Score": "0", "Tags": [ "beginner", "recursion", "rust" ], "Title": "Factorial number in Rust for learning purposes" }
236277
<p>I have just migrated from Python 2 to Python 3. I have written the following script to fetch all records of a table, ir_attachment, from PostgreSQL. After fetching all the records I check following points:</p> <ol> <li><p>If an attachment record has no value for one of <code>related_model</code>, <code>related_model_id</code> or <code>saved_file_name</code>, then I append it to the useless attachment records.</p> <p>If all exist then check the OS directory to see if there is any file corresponding with this attachment record. If any file found in directory and it was not related to more than one record I deleted that file from directory.</p></li> <li><p>Get the count of all useless attachment records and delete them from table.</p></li> <li>If any attachment record's <code>related_model</code> not found in <code>application_models</code> it is counted as <code>application_delete_models</code> records and it also should be delete from the attachment table.</li> <li>At the end I print all deleted attachment records as total useless attachment records.</li> </ol> <pre class="lang-py prettyprint-override"><code># -*- coding:utf-8 -*- import sys import os import psycopg2 import psycopg2.extras from datetime import datetime class DeleteAttachment: # Class variables to handle counts golobaly attachments_with_file_in_directory = 0 def connect_to_application_database(self): self.params = { "database": "test", "user": "test", "password": "test", "host": "100.100.100.100", "port": "5432" } try: self.application_connection = psycopg2.connect(**self.params) self.application_cursor = self.application_connection.cursor( cursor_factory=psycopg2.extras.RealDictCursor ) psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY) print('++++++++++++++++Connected to application Database++++++++++++++++') except: print("Could not connect to application database", sys.exc_info()[1]) return def get_attachment_with_deleted_relating_record(self): self.application_cursor.execute(""" SELECT model FROM ir_model WHERE model IS NOT NULL; """) application_models = self.application_cursor.fetchall() application_models_names = [model.get('model') for model in application_models] self.application_cursor.execute(""" SELECT id,related_model_id,related_model, saved_file_name FROM ir_attachment; """) attachment_records = self.application_cursor.fetchall() print('==============Checking attachment records started==============') useless_attachment_records = [] application_deleted_models = [] for record in attachment_records: if not record['related_model']: self.check_if_attachmet_record_file_exits_in_directory(record) useless_attachment_records.append(record['id']) continue if not record['related_model_id']: self.check_if_attachmet_record_file_exits_in_directory(record) useless_attachment_records.append(record['id']) continue if not record['saved_file_name']: useless_attachment_records.append(record['id']) continue if record['related_model'] and record['related_model_id']: if record['related_model'] in application_models_names: model_name = str(record['related_model'].replace('.', '_')) self.application_cursor.execute( "SELECT id FROM " + model_name + " WHERE id=%s", (record['related_model_id'],)) model_record = self.application_cursor.fetchall() if not model_record: self.check_if_attachmet_record_file_exits_in_directory(record) useless_attachment_records.append(record['id']) else: application_deleted_models.append(record['id']) print('===========Start deleting useless attachment records===========') # Call method to delete all useless attachment records. if useless_attachment_records: self.delete_attachment_record(useless_attachment_records) print("=====Start deleting Application deleted models' attachment records====") # Call method to delete those files related to unique attachment record # in attachment diectory of the os server. if application_deleted_models: self.delete_attachment_record(application_deleted_models) print('+++++++++++++++++++++++++++Counts++++++++++++++++++++++++++++++') print('Total useless attachment records:', len(application_deleted_models) + len(useless_attachment_records) ) print('Tatal attachment records with attachment file in OS directory: ', self.attachments_with_file_in_directory ) def check_if_attachmet_record_file_exits_in_directory(self, attachment_record): if attachment_record['saved_file_name']: attachment_file = '/application/attachments/application/filestore/application' +\ '/' + attachment_record['saved_file_name'] if os.path.isfile(attachment_file): self.attachments_with_file_in_directory += 1 self.application_cursor.execute("""SELECT id FROM ir_attachment WHERE saved_file_name=%s AND id!=%s """, (attachment_record['saved_file_name'], attachment_record['id'],)) check_attachment_existance_for_another_record = \ self.application_cursor.fetchall() if not check_attachment_existance_for_another_record: self.delete_file_from_directory(attachment_file) def delete_attachment_record(self, attachment): self.application_cursor.execute(""" DELETE FROM ir_attachment WHERE id in %s; """, (tuple(attachment),)) def delete_file_from_directory(self, file_name): os.remove(file_name) def close_datebase_connection(self): self.application_connection.close() self.application_cursor.close() delete_attachment_obj = DeleteAttachment() start_time = datetime.now() delete_attachment_obj.connect_to_application_database() delete_attachment_obj.get_attachment_with_deleted_relating_record() delete_attachment_obj.application_connection.close() delete_attachment_obj.application_cursor.close() print('Script running time:', datetime.now() - start_time) </code></pre> <p>How Pythonic is this structure, naming conventions, using data structures (Python 3 methods), line length and coding style.</p> <p>Also, because I use this script to fetch and process huge amount of records, <strong>how can I make it faster?</strong></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T08:50:00.360", "Id": "236278", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "postgresql" ], "Title": "Interacting with PostgreSQL attachment and the file system" }
236278
<p>I want my input to be any random numbers in any number of elements.<br> Examples:</p> <ol> <li><pre><code>Input: 1 2 3 4 1 Output: 2 3 4 </code></pre></li> <li><pre><code>Input: 4 3 5 2 5 1 3 5 Output: 4 2 1 </code></pre></li> <li><pre><code>Input: 5 5 2 6 7 7 9 9 3 3 4 1 Output: 2 6 4 1 </code></pre></li> </ol> <pre class="lang-py prettyprint-override"><code>from collections import defaultdict n = int(input("")) print("") array = 0 def single_element(array, n): table = defaultdict(lambda: 0) for i in range(0,n): array[i] = int(input("")) table[array[i]] += 1 if table[array[i]] == 1: print(array[i], end="") return "" print(single_element(array,n)) </code></pre> <p>Are there ways to improve this?</p> <p>When I run the program, this appears:</p> <pre><code>line 17, in &lt;module&gt; print(single_element(array,n)) line 10, in single_element array[i] = int(input("")) TypeError: 'int' object does not support item assignment </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T11:08:10.250", "Id": "462939", "Score": "1", "body": "Welcome to Code Review! Code review is a site to seek peer review for working code. If your code is not working correctly, it is unfortunately off-topic for this site. You might try [Stack Overflow](https://stackoverflow.com/help/how-to-ask) if you can word the question in a way that fits the criteria on that page. Once your code works correctly, you're welcome to ask a new question here and we can then help you improve it." } ]
[ { "body": "<p>I'd use <code>cnt = collections.Counter(array)</code> to count the number of occurrences per element. Then return <code>[element for element in array if cnt[element] == 1</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T17:36:09.103", "Id": "463005", "Score": "0", "body": "Nice simple answer. I downvote only to discourage answering off-topic questions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T12:27:04.830", "Id": "236286", "ParentId": "236282", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T10:41:02.993", "Id": "236282", "Score": "-1", "Tags": [ "python" ], "Title": "Finding all non-repeated elements in list" }
236282
<p>My aim is to assign a color to each workday in a week. So if a user enters a day as a <code>str</code>, then I can know which color it should have.</p> <p>Because colors and workdays are fixed, I make them as <code>enum.Enum</code> instance.</p> <ol> <li>Is <code>enum.Enum</code> a proper choice for colors and workdays?</li> <li>To link day and color, I choose dictionary for <code>weekday_color</code>. Is there a better choice?</li> </ol> <pre class="lang-py prettyprint-override"><code>from enum import Enum class WeekDay(Enum): MONDAY = 'Monday' TUESDAY = 'Tuesday' WEDNESDAY = 'Wednesday' THURSDAY = 'Thursday' FRIDAY = 'Friday' class Color(Enum): RED = 'Red' GREEN = 'Green' BLUE = 'Blue' weekday_color = { WeekDay.MONDAY: Color.RED, WeekDay.TUESDAY: Color.GREEN, WeekDay.WEDNESDAY: Color.BLUE, WeekDay.THURSDAY: Color.GREEN, WeekDay.FRIDAY: Color.RED, } def main(): today_input = 'Monday' today = WeekDay(today_input) today_color = weekday_color[today] print(today) print(today_color) if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T05:19:24.777", "Id": "463063", "Score": "0", "body": "`weekday_color` seems to indicate a single element with a single color. `weekday_colorscheme` or `colorscheme_for_weekdays` maybe?" } ]
[ { "body": "<p>Given your example, I don't see much advantage of using <code>enums</code>. I'd keep it simple and do </p>\n\n<p><code>weekday_color = {\"Monday\": \"RED\", \"Tuesday\": \"GREEN\", ...}</code></p>\n\n<p>Now, if you want to keep going down the enum route, you can make them more useful. For example the <code>Color</code> enum, instead of having the strings as values, you can pack information like the code the color has</p>\n\n<pre><code>class Color(Enum):\n RED = 'FF0000'\n GREEN = '00FF00'\n BLUE = '0000FF'\n</code></pre>\n\n<p>Then you reduce duplication and pack more information that could be useful later on.</p>\n\n<p>Concerning the <code>Weekday</code> enum, I'd change it as follows</p>\n\n<pre><code>from enum import IntEnum, auto\n\nclass Weekday(IntEnum):\n MONDAY = auto()\n TUESDAY = auto()\n WEDNESDAY = auto()\n THURSDAY = auto()\n FRIDAY = auto()\n</code></pre>\n\n<p>With this, you get comparison/sorting of the weekdays in a way that feels natural. And by using <code>auto()</code> you don't retype the name of the weekday as value. Although you lose the possibility of doing something like <code>Weekday(\"Monday\")</code>, but then you access it like `Weekday[\"MONDAY\"] to access by name.</p>\n\n<p>Thus</p>\n\n<pre><code>from enum import Enum, IntEnum, auto\n\n\nclass Weekday(IntEnum):\n MONDAY = auto()\n TUESDAY = auto()\n WEDNESDAY = auto()\n THURSDAY = auto()\n FRIDAY = auto()\n\n\nclass Color(Enum):\n RED = 'FF0000'\n GREEN = '00FF00'\n BLUE = '0000FF'\n\n\nweekday_color = {\n Weekday.MONDAY: Color.RED,\n Weekday.TUESDAY: Color.GREEN,\n Weekday.WEDNESDAY: Color.BLUE,\n Weekday.THURSDAY: Color.GREEN,\n Weekday.FRIDAY: Color.RED,\n}\n\n\ndef main():\n today_input = 'Monday'\n today = Weekday[today_input.upper()] # adding uppercasing to be resilient\n today_color = weekday_color[today]\n print(f\"{today.name}'s color is {today_color.name} with code {today_color.value}\") \n\n\nif __name__ == '__main__':\n main() # output: MONDAY's color is RED with code FF0000\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T13:16:30.440", "Id": "236292", "ParentId": "236284", "Score": "4" } }, { "body": "<p>Design-wise, using an <code>Enum</code> is entirely appropriate -- they were added to make \"magic\" constants easier to work with by giving them informative debugging names and easier containment checks.</p>\n\n<p>Using a dictionary to tie the two enums together is unnecessary in this case as it makes more sense, and is easily possible, to have <code>color</code> be an attribute of each <code>Weekday</code>.</p>\n\n<p>Whether <code>Color</code> is itself an enum depends on what you will be doing with the colors:</p>\n\n<ul>\n<li>do you need actual color values?</li>\n<li>is the <code>color</code> value going to be sent to another system, or stay inside your own program?</li>\n</ul>\n\n<p>Whether or not you have a separate <code>Color</code> enum, a good way to combine those two things is like so (shown using <code>aenum</code><sup>1</sup>, but can be done with the stdlib <code>Enum</code><sup>2</sup>:</p>\n\n<pre><code>from aenum import AutoNumberEnum\n\nclass WeekDay(AutoNumberEnum):\n _init_ = 'color'\n #\n MONDAY = 'red'\n TUESDAY = 'green'\n WEDNESDAY = 'blue'\n THURSDAY = 'green'\n FRIDAY = 'red'\n</code></pre>\n\n<p>and in use:</p>\n\n<pre><code>&gt;&gt;&gt; list(WeekDay)\n[&lt;WeekDay.MONDAY: 1&gt;, &lt;WeekDay.TUESDAY: 2&gt;, &lt;WeekDay.WEDNESDAY: 3&gt;, &lt;WeekDay.THURSDAY: 4&gt;, &lt;WeekDay.FRIDAY: 5&gt;]\n\n&gt;&gt;&gt; WeekDay.MONDAY\n&lt;WeekDay.MONDAY: 5&gt;\n\n&gt;&gt;&gt; WeekDay['MONDAY']\n&lt;WeekDay.MONDAY: 5&gt;\n\n&gt;&gt;&gt; WeekDay.MONDAY.color\n'red'\n</code></pre>\n\n<p>If you decide to use an enum for color, simply assign that instead of, for example, <code>'red'</code>.</p>\n\n<hr>\n\n<p><sup>1</sup> Disclosure: I am the author of the <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">Python stdlib <code>Enum</code></a>, the <a href=\"https://pypi.python.org/pypi/enum34\" rel=\"nofollow noreferrer\"><code>enum34</code> backport</a>, and the <a href=\"https://pypi.python.org/pypi/aenum\" rel=\"nofollow noreferrer\">Advanced Enumeration (<code>aenum</code>)</a> library.</p>\n\n<hr>\n\n<p><sup>2</sup> The stdlib version (without the members):</p>\n\n<pre><code>class WeekDay(Enum):\n #\n def __new__(cls, color):\n value = len(cls.__members__) + 1\n obj = object.__new__(cls)\n obj._value_ = value\n obj.color = color\n return obj\n #\n # members here\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T05:16:26.597", "Id": "463062", "Score": "0", "body": "This goes against my sense of correct class design. Weekdays are only assigned colors when they are considered in e.g. a calendar. But even then it is only the decoration of the calendar. Colors are not properties of weekdays. This will quickly become apparent if the weekday also e.g. needs to be displayed in gray tones. Now we have a weekday with 2 colors?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T17:31:36.483", "Id": "236307", "ParentId": "236284", "Score": "5" } } ]
{ "AcceptedAnswerId": "236307", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T11:36:05.443", "Id": "236284", "Score": "6", "Tags": [ "python", "python-3.x", "enum" ], "Title": "Coloring weekdays with enums" }
236284
<p>I made the following wrapper for the <code>mediainfo</code> command line. I did this mainly because mediainfo gives me more information than <code>os.stat</code>, specifically it gives me the <code>Encoded date</code> for .wma files, while the dates in <code>os.stat</code> don't represent the time the files were made, but rather the date the files were compressed (they were delivered to me in a compressed folder).</p> <p>But is it actually a good idea to use a class for this? I needed to do this in bulk, for 20.000 files. Also it feels inefficient to let <code>mediainfo</code> format the information first and then read it again, but I'm not sure how to do that otherwise.</p> <pre><code>from pathlib import Path from subprocess import Popen, PIPE class MediaInfo: """Wrapper class for the mediainfo command line tool.""" # Define the path to the `mediainfo` command line tool. mediainfo = "/usr/bin/mediainfo" def __init__(self, filename): self.file = Path(filename).resolve() self.info = self.readinfo() if not self.file.is_file(): raise OSError(f"File not found: {file}") def __str__(self): """String representation (the same as what mediainfo shows)""" if hasattr(self, "info") and self.info is not None: return self.info.strip() return self.readinfo().strip() def infofield(self, field, postread=None): """Find a given field and return its value. If the `field` is not in the mediainfo metadata, return None. `postread` can be a callable to, for example, cast the returned type. """ val = None for line in self.info.split("\n"): if not line.strip() or not ":" in line: continue key, val = line.strip().split(" : ") key = key.strip() val = val.strip() if key == field: break if postread is None: return val return postread(val) def readinfo(self): # Start the command line process proc = Popen([self.mediainfo, str(self.file)], stdout=PIPE, stderr=PIPE) # Catch the output stdout, stderr = proc.communicate() if stderr: self.info = stderr.decode() raise MediaInfoException("Error in MediaInfo process", self.info) self.info = stdout.decode() return self.info class MediaInfoException(Exception): """Custom exception for MediaInfo.""" pass </code></pre>
[]
[ { "body": "<p>Using a class might be too much. It all depends of how you want to use your script.</p>\n\n<p>But I think you should take a look at mediainfo help. Issuing:</p>\n\n<pre><code>mediainfo --Inform=\"Audio;%Encoded_Date%\" Filename\n</code></pre>\n\n<p>outputs only the encoded date value of your audio file, or an empty line if not applicable. Maybe you won't need your script anymore.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T19:27:46.147", "Id": "236430", "ParentId": "236288", "Score": "1" } } ]
{ "AcceptedAnswerId": "236430", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T12:37:49.603", "Id": "236288", "Score": "4", "Tags": [ "python", "python-3.x", "console", "wrapper" ], "Title": "Wrapper class for mediainfo" }
236288
<p>I'd like feedback on my solution to the outlined (medium level) programming challenge. What might be a more efficient or Pythonic solution?</p> <p>The challenge as outlined by Coderbyte:</p> <blockquote> <p>[Run Length] (<a href="https://www.coderbyte.com/solution/Run%20Length?tblang=german" rel="nofollow noreferrer">https://www.coderbyte.com/solution/Run%20Length?tblang=german</a>)</p> <p>Have the function RunLength(str) take the str parameter being passed and return a compressed version of the string using the Run-length encoding algorithm. This algorithm works by taking the occurrence of each repeating character and outputting that number along with a single character of the repeating sequence. For example: "wwwggopp" would return 3w2g1o2p. The string will not contain any numbers, punctuation, or symbols.</p> </blockquote> <pre><code>import doctest import logging import timeit logging.basicConfig( level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s") # logging.disable(logging.CRITICAL) def compress_string(s: str) -&gt; str: """ Indicate the freq of each char in s, removing repeated, consecutive chars E.g. "aaabbc" outputs '3a2b1c' :param s: the string to compress :type s: str :return: s as a compressed string :rtype: str &gt;&gt;&gt; compress_string(s="wwwggopp") '3w2g1o2p' &gt;&gt;&gt; compress_string(s="aaa") '3a' &gt;&gt;&gt; compress_string(s="") '' &gt;&gt;&gt; compress_string(s="b") '1b' &gt;&gt;&gt; compress_string(s="abcd") '1a1b1c1d' """ if s == "": return "" # indexes of change in characters indexes = [i+1 for i in range(len(s) - 1) if s[i+1] != s[i]] # add start and end index for slicing of s indexes.insert(0, 0) indexes.append(len(s)) # slice string slices = [s[indexes[i]:indexes[i+1]] for i in range(len(indexes)-1)] compressed_str = "".join(f"{len(s)}{s[0]}" for s in slices) return compressed_str if __name__ == "__main__": print(timeit.timeit("compress_string(s='wwwggoppg')", setup="from __main__ import compress_string", number=100000)) doctest.testmod() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T15:06:23.893", "Id": "462981", "Score": "1", "body": "How it should behave (what result) on this input string `aAabcaa` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T19:23:08.300", "Id": "463018", "Score": "0", "body": "@RomanPerekhrest I will make a revision to cover that possibility" } ]
[ { "body": "<ul>\n<li><p>You could just make a new list rather than use <code>list.insert</code> and <code>list.append</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>indexes.insert(0, 0)\nindexes.append(len(s))\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>indexes = [0] + indexes + [len(s)]\n</code></pre></li>\n<li><p>For your \"slice string\" part, I'd make a function called pairwise. As this is a rather well know recipe in Python.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def pairwise(iterable):\n return (\n (iterable[i], iterable[i+1])\n for i in range(len(iterable) - 1)\n )\n</code></pre></li>\n<li><p>You could combine <code>slices</code> and <code>compressed_str</code> into one comprehension. If you do you don't need to use <code>len</code> as <code>indexes[i+1] - indexes[i]</code> is the length of the string.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>return \"\".join(\n f\"{b - a}{s[a]}\"\n for a, b in pairwise(indexes)\n)\n</code></pre></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def pairwise(iterable):\n return (\n (iterable[i], iterable[i+1])\n for i in range(len(iterable) - 1)\n )\n\n\ndef compress_string(s: str) -&gt; str:\n if s == \"\":\n return \"\"\n\n indexes = [\n i+1\n for i in range(len(s) - 1)\n if s[i+1] != s[i]\n ]\n indexes = [0] + indexes + [len(s)]\n return \"\".join(\n f\"{b - a}{s[a]}\"\n for a, b in pairwise(indexes)\n )\n</code></pre>\n\n<h1>Itertools</h1>\n\n<ul>\n<li>The pairwise function could be better described using the <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\"><code>pairwise</code> recipe</a>.</li>\n<li>If you utilize <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a> the challenge is super easy, as it makes <code>slices</code> for you.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def compress_string(s: str) -&gt; str:\n if s == \"\":\n return \"\"\n return \"\".join(\n f\"{sum(1 for _ in g)}{k}\"\n for k, g in itertools.groupby(s)\n )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T19:21:20.470", "Id": "463016", "Score": "0", "body": "To my absolute horror, I timed indexes = '[0] + indexes + [len(s)]' vs my method, and the latter was 165 times slower! If someone could explain why? I originally had used @Peilonrayz's version, but changed it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T19:24:04.793", "Id": "463019", "Score": "1", "body": "@Dave Yeah 165 times slower seems a bit off, since mine are both in the margin of error. How did you test it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T20:13:33.330", "Id": "463025", "Score": "0", "body": "I added my test script to my post. Tell me what I've done wrong :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T20:17:21.877", "Id": "463026", "Score": "1", "body": "@Dave `l.insert` and `l.append` run `100000` times, making `l` in the last test 200000 times larger than at the beginning. You're no longer comparing the same thing. Just remove `setup`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T20:26:02.100", "Id": "463027", "Score": "0", "body": "Got it. I completely misunderstood what setup was for....let me check again. That won't happen again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T20:29:54.843", "Id": "463028", "Score": "1", "body": "@Dave Technically you got it right. It's just it didn't work in the way you expected with mutables." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T17:28:49.890", "Id": "236306", "ParentId": "236289", "Score": "2" } } ]
{ "AcceptedAnswerId": "236306", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T12:49:59.653", "Id": "236289", "Score": "3", "Tags": [ "python", "python-3.x", "programming-challenge", "strings" ], "Title": "Run length encoding of an input string (Coderbyte 'Run Length' challenge)" }
236289
<p>I want to make a camera class with help of the Eigen library. The camera will be used to perform certain calculations or rather the values used to setup the camera will be used later on in multiple matrix calculations. The camera can be defined by the 9D vector and the near/far plane and width/height values alone.<br> Redundant definitions like a and c are just for convenience as those are the mathematical symbols we use for those vectors.</p> <p>Main point to be reviewed:<br> <strong>I am not sure if and how to store dependent values that can be derived from other data but will be accessed frequently.</strong><br> Context:<br> Derived values like position, up vector, forward vector etc will be needed often, so I figured I store them as well. But whenever one wants to change one of those, the others will have to be recalculated. If I don't store them they will have to be constructed every time I need them. In the big picture, there will be an optimization problem to solve, so the camera will change often.<br> <strong>In this case, would it be more efficient to store them or construct them if needed? If stored, might it be better to use pointers?</strong></p> <p>I have programming experience in C# but C++ is something I struggle with, especially when to use a pointer, references or value. I am also not sure how to use the Eigen types in an efficient way. I read a little in the documentation but am still unsure.<br> It currently works as intended but I have concerns it will be either slow or memory consuming if used intensively.</p> <p>I am using g++ 7.4.0, C++11, Eigen (master branch, as I like the new matrix slicing syntax and the 3.4 seems not so far in the future any more)</p> <p>Any general advice and references are appreciated as well. Thanks :)</p> <p>Edit1: Added clarity Edit2: Added example</p> <p><strong>matrix_types.h</strong></p> <pre><code>#ifndef MATRIX_TYPES_H_ #define MATRIX_TYPES_H_ #include&lt;Eigen/Dense&gt; typedef Eigen::Matrix&lt;double, 9, 1&gt; Vector9d; typedef Eigen::Matrix&lt;double, 9, 2&gt; Matrix92d; typedef Eigen::Matrix&lt;double, 2, 9&gt; Matrix29d; typedef Eigen::Matrix&lt;double, 9, 9&gt; Matrix9d; typedef Eigen::Matrix&lt;double, 3, 2&gt; Matrix32d; typedef Eigen::Matrix&lt;double, 2, 3&gt; Matrix23d; #endif </code></pre> <p><strong>Camera.h</strong></p> <pre class="lang-cpp prettyprint-override"><code>#ifndef CAMERA_H_ #define CAMERA_H_ #include &lt;Eigen/Dense&gt; #include &lt;Eigen/Geometry&gt; #include "matrix_types.h" class Camera { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef Eigen::Vector3d Vector3d; Camera( const Vector9d&amp; camVector, float width, float height, float near, float far ) : m_width(width), m_height(height), m_near(near), m_far(far) { m_setCamVec(camVector); } Camera( const Vector3d&amp; pos, const Vector3d&amp; forward, const Vector3d&amp; up, float width, float height, float near, float far ) : m_width(width), m_height(height), m_near(near), m_far(far) { m_setCamVec(pos, forward, up); } const Vector3d&amp; Position(){ return m_position; }; const Vector3d&amp; c(){ return Position(); } const Vector3d&amp; Forward(){ return m_forward; }; const Vector3d&amp; a(){ return Forward(); } const Vector3d&amp; up(){ return m_up; }; Matrix32d A(){ Matrix32d n_A; n_A &lt;&lt; m_forward, m_forward; return n_A; } Matrix32d R11(){ Matrix32d n_R11; n_R11 &lt;&lt; m_r1, m_r1; return n_R11; } Matrix32d R12(){ Matrix32d n_R12; n_R12 &lt;&lt; m_r1, m_r2; return n_R12; } float AspectRatio(){ return m_width/m_height; } float r(){ return AspectRatio(); } /// ()-operator so one can do camera() and get the Vector9 of its components const Vector9d&amp; operator () (){ return m_camVec; } /// assignment operator Camera&amp; operator = (const Vector9d&amp; camVec){ m_setCamVec(camVec); return *this; } Camera&amp; operator += (const Vector9d&amp; camOffset){ m_setCamVec(m_camVec + camOffset); return *this; } Camera&amp; operator -= (const Vector9d&amp; camOffset){ m_setCamVec(m_camVec - camOffset); return *this; } void SetPosition(const Vector3d&amp; pos){ m_position = pos; m_camVec(Eigen::seq(0,2)) = pos; } void SetForward(const Vector3d&amp; forw){ m_forward = forw; m_camVec(Eigen::seq(3,5)) = forw; m_recalculateRs(); } void SetUp(const Vector3d&amp; up){ m_up = up; m_camVec(Eigen::seq(6,8)) = up; m_recalculateRs(); } private: Vector9d m_camVec; Vector3d m_position; Vector3d m_forward; Vector3d m_up; Vector3d m_r1; Vector3d m_r2; float m_width; float m_height; float m_near; float m_far; void m_setCamVec(const Vector9d&amp; camVec){ m_camVec = camVec; m_position = m_camVec(Eigen::seq(0,2)); m_forward = m_camVec(Eigen::seq(3,5)); m_up = m_camVec(Eigen::seq(6,8)); m_recalculateRs(); } void m_setCamVec(const Vector3d&amp; pos, const Vector3d&amp; forw, const Vector3d&amp; up){ m_camVec &lt;&lt; pos, forw, up; m_position = pos; m_forward = forw; m_up = up; m_recalculateRs(); } void m_recalculateRs(){ m_r1 = (m_forward.cross(m_up)).normalized(); m_r2 = (m_r1.cross(m_forward)).normalized(); } }; // end Camera #endif </code></pre> <p><strong>main.cpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>/* The actual calculations here are nonsensical. Still, the use of the camera here is similar to the way it will be used later on. Meaning, matrices and camera vectors will be used for calculations. The camera will be part of a bigger project and I want to avoid rewriting everything because it was set up stupidly to begin with. */ #include &lt;iostream&gt; #include &lt;cmath&gt; #include &lt;Eigen/Dense&gt; #include &lt;limits&gt; #include "camera.h" int main() { Vector9d camVec {{1.0},{1.0},{5.0},{0.0},{1.0},{0.2},{0.0},{0.0},{1.0}}; Camera cam(camVec, 12.3f, 5.4f, 1.0f, 300.0f); double epsilon = 0.0001; Vector9d bestCamVec = camVec; double opt = std::numeric_limits&lt;double&gt;::max(); for(int j = 0; j &lt; 100; ++j){ Matrix9d P = Matrix9d::Constant(0); Vector9d camEps = Vector9d::Random() * epsilon; cam += camEps; for(int i = 0; i &lt; 1000; ++i){ Eigen::Vector2d p = Eigen::Vector2d::Random(); double d = p.norm(); double alpha = std::atan2(cam.a().cross(cam.up()).norm(), cam.a().dot(cam.up())); double a = cam.a().norm(); double b = (cam.a() + cam.R12()*p).norm(); Eigen::Matrix2d Y = p.asDiagonal(); Eigen::Matrix2d Y_ = Y.inverse(); Matrix92d B; B &lt;&lt; b/(d*a*a)*cam.A()*Y_, -std::tan(alpha)/a*cam.R11()*Y, cam.R12()*Y*std::sin(alpha); P += B*B.transpose(); } double det = std::abs(P.determinant()); if(opt &gt; det){ opt = det; bestCamVec = cam(); } } std::cout &lt;&lt; "Best camera vector is \n" &lt;&lt; bestCamVec &lt;&lt; "\n with " &lt;&lt; opt; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T03:13:43.613", "Id": "463050", "Score": "0", "body": "@Lisa I have installed EIgen and compilled your code. Caveat: I am well familiar with Linear algebra but I do not know Eigen. There are some unused member variables: `m_near` and `m_far` (turn on `-Wall` `-Wextra`). I have had a look at how Eigen stores these vectors. They seem to be just \"value types\", ie an `Eigen::Vector3d` is literally 3 `double`s (ie 24 bytes) on the stack. If, from my cursory glance, i have understood correctly, then you are worried about recomputing/storing `m_r1` & `m_r2`. Don't be, they are only of type Vector3d." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T03:17:35.990", "Id": "463051", "Score": "1", "body": "@Lisa Please provide a `main()` which shows how you intend to use `Camera` and I can give a fuller answer. I suspect the answer is: you are prematurely worrying about copying/pointers etc. C++ is extremely good and fast at \"value types\". So at 2x 24bytes I wouldn't worry too much at all until you have a real example to test with. Why are `m_width` and `m_height` and the resulting `AspectRatio()` of type `float`? When everything else is a `double`? I would just stick to double. With H/W acceleration they are almost the same speed and there is probably no issue with storage here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T18:36:58.053", "Id": "463166", "Score": "0", "body": "@OliverSchonrock Added an example. Sorry it took so long. You are right, making it all to double type makes more sense" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T19:30:02.537", "Id": "463174", "Score": "0", "body": "@Lisa. Thanks for the example. Initially, I failed to read the comment at top. Wrecked my brain for 5mins trying to understand what it does, before concluding \"either the code is crazy or I am\". Glad it's the former. ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T19:36:34.037", "Id": "463175", "Score": "0", "body": "@Lisa I added some notes about making getters `const` and `[[nodiscard]]` below, just for style." } ]
[ { "body": "<h2>Scope</h2>\n\n<p>I cannot fully comment on use of the class or the linear algebra involved, because:</p>\n\n<ol>\n<li>It's not clear how it will be used </li>\n<li>There are no real operations shown, just setup/config of the class plus \"camera move\". </li>\n</ol>\n\n<h2>General</h2>\n\n<ul>\n<li>Code compiles fine on a recent compiler (I am using clang-9 ). Only 2 warnings with <code>-Wall -Wextra</code>:</li>\n</ul>\n\n<pre><code>camera.cpp:110:9: warning: private field 'm_near' is not used [-Wunused-private-field]\n float m_near;\n ^\ncamera.cpp:111:9: warning: private field 'm_far' is not used [-Wunused-private-field]\n float m_far;\n ^\n</code></pre>\n\n<ul>\n<li>Given you are using gcc7.4 and that I assume you have <code>-std=C++17</code> enabled, then I do <strong>not</strong> believe you need <code>EIGEN_MAKE_ALIGNED_OPERATOR_NEW</code>. As <a href=\"https://eigen.tuxfamily.org/dox-devel/group__TopicUnalignedArrayAssert.html\" rel=\"nofollow noreferrer\">documented here</a> and explained in more detail in this <a href=\"https://eigen.tuxfamily.org/bz/show_bug.cgi?id=1409\" rel=\"nofollow noreferrer\">bugzilla entry</a>. All of Eigen's aligment challenges are solved in recent C++17 compilers apparently. Your question mentions C++11, but if you can you should be compiling with <code>-std=c++17</code> to get best behaviour from Eigen and have access many other useful features. The only reason to not do this would be if you have some other 3rd party dependency which won't compile in C++17 mode, or if you also need to support platforms with older , more limited compilers, where C++17 is not available. </li>\n<li>You are using <code>double</code> for all your vector/matrix coefficients, yet you are using <code>float</code> for <code>m_width</code> and <code>m_height</code> and therefore <code>AspectRatio()</code>. Is there a specific reason? If not I would just standardise on <code>double</code>, which can often be faster on modern hardware with FP co-processors. </li>\n<li>Instead of your <code>typedef</code>s you could consider writing this, which is considered \"more modern practice\":</li>\n</ul>\n\n<pre><code>using Vector9d = Eigen::Matrix&lt;double, 9, 1&gt;;\n</code></pre>\n\n<ul>\n<li>Your constructors and operator methods look fine to me</li>\n<li>You could get \"extra points\" for C++ style by making your \"getter\" methods <code>const</code> and <code>[[nodiscard]]</code> like this:</li>\n</ul>\n\n<pre><code> [[nodiscard]] const Vector3d&amp; Forward() const { /* ... */ };\n [[nodiscard]] const Vector3d&amp; a() const { /* ... */ };\n [[nodiscard]] const Vector3d&amp; up() const { /* ... */ };\n [[nodiscard]] Matrix32d A() const { /* ... */ };\n [[nodiscard]] Matrix32d R11() const { /* ... */ };\n [[nodiscard]] Matrix32d R12() const { /* ... */ };\n</code></pre>\n\n<ul>\n<li>When you compile for performance (ie \"Release mode\") ensure you pass <code>-DNDEBUG=1 -O3</code> similar to below. The <code>NDEBUG</code> bypasses runtime checks on matrix dimensions and <code>-O3</code> will bring huge benefits, especially with Eigen's <a href=\"https://eigen.tuxfamily.org/dox-devel/group__TutorialMatrixArithmetic.html\" rel=\"nofollow noreferrer\">expression templates</a>.</li>\n</ul>\n\n<pre><code>g++ -DNDEBUG=1 -O3 -Wall -Wextra -std=c++17 -I include/eigen/ -o build/camera apps/camera.cpp\n</code></pre>\n\n<h2>Memory structure: layout, allocation and operations</h2>\n\n<p>You seemed concerned about speed / copying / memory usage and therefore whether you should be using pointers. </p>\n\n<p>Firstly the vectors/matrices you are using are fixed size and very very small. The biggest one is 9 elements of <code>double</code>s which are 8 bytes each so 72 bytes (you don't seem to use the <code>Matrix92d</code>). You don't appear to have <code>std::vector</code>s or other collections of these vectors/matrices or of the camera object itself. </p>\n\n<p>Your concern seems to be related to \"moving and therefore changing the camera object often\". You have decided to recompute the internal <code>m_r1</code> and <code>m_r2</code> during <code>m_setCamVec</code> which is called from eg <code>operator-=</code>. </p>\n\n<p>I have read up on the Eigen operations and studied how Eigen stores its structures. They are very simple: essentially, under the hood they are C-style arrays. On my machine, <code>sizeof (Camera)</code> reports that your objects will be 208 bytes, which is very manageable on the stack. This includes all the vectors/matrices which are all packed into the object (no heap allocations here). </p>\n\n<p>If you needed to pass one or a few <code>Camera</code> objects around between functions, you should pass them by reference. Not least because Eigen <a href=\"https://eigen.tuxfamily.org/dox-devel/TopicFunctionTakingEigenTypes.html\" rel=\"nofollow noreferrer\">recommends that</a> for its structures. </p>\n\n<p>If you were to make thousands of <code>Camera</code> objects then these should probably go on the heap, and that would happen naturally if you made a <code>std::vector&lt;Camera&gt;</code> of them. But even then, each <code>Camera</code> object on the heap would contain all its 208 bytes of vectors/matrices within it. </p>\n\n<p>When you call <code>operator+=</code> or other methods which reposition the Camera it looks like there are just a few assignment statements for <code>m_position</code> etc and then <code>recalculateRS()</code> which does 2 tiny cross-products and assignments. </p>\n\n<p>Therefore, <strong>there is no need to worry about copying</strong> during the recalculation and re-assigning to the member fields. Apart from any possible temporaries, (which Eigen tries to minimise), Eigen and C++ will use <strong>the same memory</strong> which is already part of your 208-byte Camera object. Very little (if any!) extra memory will be used and everything (!) will be cleaned up each time you reposition the camera object. </p>\n\n<h2>Expected costs</h2>\n\n<p>This should all be super fast because:</p>\n\n<ul>\n<li>You have chosen a good quality linear algebra library </li>\n<li>You are using fixed sized matrices</li>\n<li>Your matrices are very small</li>\n<li>If you compile with <code>-O3 -DNDEBUG=1</code> then Eigen &amp; the compiler should be able to optimise away any temporaries. </li>\n<li>There are no heap allocations here at all (unless you have thousands of camera objects). Also, if Eigen cannot avoid a temporary, it will likely use the stack for it:</li>\n</ul>\n\n<blockquote>\n <p><code>EIGEN_STACK_ALLOCATION_LIMIT</code> - defines the maximum bytes for a buffer\n to be allocated on the stack. For internal temporary buffers, dynamic\n memory allocation is employed as a fall back. For fixed-size matrices\n or arrays, exceeding this threshold raises a compile time assertion.\n Use 0 to set no limit. Default is 128 KB.</p>\n</blockquote>\n\n<p>you can further force this with:</p>\n\n<blockquote>\n <p><code>EIGEN_NO_MALLOC</code> - if defined, any request from inside the Eigen to\n allocate memory from the heap results in an assertion failure. This is\n useful to check that some routine does not allocate memory\n dynamically. Not defined by default.</p>\n</blockquote>\n\n<p>Note that, if Eigen did allocate memory (very unlikely from what we have seen of your application), then Eigen <strong>will free</strong> that memory as soon as it's not needed. This is the standard behaviour in C++. </p>\n\n<h2>Better to store or construct?</h2>\n\n<p>Impossible to tell without knowing the usage pattern. Need to know the actual number of times camera is repositioned vs the number of times these quantities would have to be computed if they were not stored. <strong>Neither option seems expensive</strong>. Since there is no <code>malloc</code>, this is just two SIMD optimised cross products of tiny matrices. I have no idea how long that takes but if it's longer than a couple of hundred cycles I would be surprised. </p>\n\n<h2>Performance mockup</h2>\n\n<p>I hacked this basic loop to get an idea. The <code>escape()</code> is to avoid the compiler just removing our program altogether. </p>\n\n<pre><code>static void escape(void *p) {\n asm volatile(\"\" : : \"g\"(p) : \"memory\");\n}\n\nint main() {\n Vector9d init = Vector9d::Random();\n auto cam = Camera{init, 2, 1, 3, 4};\n std::cout &lt;&lt; cam.Position() &lt;&lt; \"\\n\";\n for (std::size_t i = 0; i &lt; 1'000'000; ++i) {\n cam += init;\n Matrix32d r12 = cam.R12();\n escape(&amp;r12);\n }\n std::cout &lt;&lt; cam.Position() &lt;&lt; \"\\n\";\n return 0;\n}\n</code></pre>\n\n<p>On my (quite old i7 2600) machine with <code>-O3 -DNDEBUG</code> that runs in 65ms. So a single camera move takes around (very roughly!) 65ns. Here is the, slightly modified to eliminate the <code>std::cout</code> printing, version <a href=\"https://godbolt.org/z/baaf6x\" rel=\"nofollow noreferrer\">in machine code</a>. A few hundred lines of assembly, packed full of SIMD instructions. Scary fast? </p>\n\n<p>The bottlenecks for your application <em>are likely to lie elsewhere</em> in your calling code. In general you are slightly in danger of \"premature optimisation\" concerns. It's not at all clear that there is anything expensive here. Need to measure first when application is up and running. </p>\n\n<p>I hope that helps. I had to make some assumptions. Come back with comments if they were incorrect. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T18:10:37.037", "Id": "463156", "Score": "2", "body": "Does `NDEBUG` need to be defined to `1` specifically? If Eigen is using standard `assert`, then it's sufficient to define it (`-DNDEBUG`) and it doesn't need a value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T18:19:12.023", "Id": "463158", "Score": "0", "body": "@TobySpeight Yes that's probably correct. It's an old habbit of mine. Make it \"something truthy\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T18:31:06.267", "Id": "463162", "Score": "0", "body": "Thank you very much for your answer. I usually use C# or scripting languages, so I am very paranoid and start to overthink stuff when it comes to C++ and how to manage memory and pointers, references etc. Your notes on Eigen were really insightful for me and take away the paranoia a little." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T18:34:05.300", "Id": "463164", "Score": "0", "body": "@Lisa Thanks! I understand the paranoia. It comes naturally when you work with \"managed languages\" Always trying to optimise, but \"not quite in control\" of what is really happening. But yeah: C++ with Eigen just eats this for breakfast it seems. Since you're new: If you found the answer useful, please upvote it and accept it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T15:11:00.507", "Id": "236356", "ParentId": "236293", "Score": "5" } } ]
{ "AcceptedAnswerId": "236356", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T13:39:06.577", "Id": "236293", "Score": "4", "Tags": [ "c++", "beginner", "object-oriented", "c++11" ], "Title": "Mathematical Camera class with types of Eigen library" }
236293
<p>The code below looks at different range values and then populates specific cells on a worksheet called GeneralInfo in the <code>Worksheet_Activate</code> event.<br><br>The below code does work as expected, but its time to clean it up a little bit, so I am looking for some ideas.<br><br> I have tried to split up the code with using smaller procedures and functions, but the way I wrote those procedures made the code a little easier to maintain, but caused a lot more <code>If</code> and <code>Select Case</code> Statements then I currently have; I also tried to place items like the <code>CustNames</code> into an array, but failed miserably with that, so I could use some thoughts on best way to approach cleaning this up.</p> <p><strong>EDIT:</strong> Added additional code per request</p> <pre><code>Private Sub Worksheet_Activate() Select Case GeneralInfo.Range("genLoanNumber") Case Is = vbNullString Select Case SheetData.Range("Construction_Loan") Case Is = vbNullString Select Case SheetData.Range("Do_Not_Assign_Loan_Number") Case Is = vbNullString If MsgBox("Would you like to assign the loan number now?", vbYesNo + vbCritical, UCase("Assign Loan Number")) = vbYes Then AssignLoanNumber Else: SheetData.Range("Do_Not_Assign_Loan_Number") = "X" End If End Select End Select End Select Dim guarantorCount As Integer, borrCount As Integer guarantorCount = 0 borrCount = Application.WorksheetFunction.CountA(loanData.Range("B2:B9")) GeneralInfo.Range("A7") = vbNullString Dim CustName1 As String, CustName2 As String, CustName3 As String, custName4 As String Dim CustName5 As String, CustName6 As String, CustName7 As String, custName8 As String CustName1 = loanData.Range("CustLNSuff1") &amp; ", " &amp; loanData.Range("CustFMI1") CustName2 = loanData.Range("CustLNSuff2") &amp; ", " &amp; loanData.Range("CustFMI2") CustName3 = loanData.Range("CustLNSuff3") &amp; ", " &amp; loanData.Range("CustFMI3") custName4 = loanData.Range("CustLNSuff4") &amp; ", " &amp; loanData.Range("CustFMI4") CustName5 = loanData.Range("CustLNSuff5") &amp; ", " &amp; loanData.Range("CustFMI5") CustName6 = loanData.Range("CustLNSuff6") &amp; ", " &amp; loanData.Range("CustFMI6") CustName7 = loanData.Range("CustLNSuff7") &amp; ", " &amp; loanData.Range("CustFMI7") custName8 = loanData.Range("CustLNSuff8") &amp; ", " &amp; loanData.Range("CustFMI8") Dim c As Range If loanData.Range("Entity") &lt;&gt; vbNullString Then If GeneralInfo.Range("NoGuar") = 0 Or GeneralInfo.Range("NoGuar") = vbNullString Then For Each c In loanData.Range("B3:B9") If c.Value &lt;&gt; vbNullString Then guarantorCount = guarantorCount + 1 End If Next c With GeneralInfo .Range("NoGuar") = guarantorCount .Range("A7") = "Guarantor(s)" .Range("genBorrName") = loanData.Range("CustName1") .Range("genGuarantorName1") = loanData.Range("CustName2") .Range("genGuarantorName2") = loanData.Range("CustName3") .Range("genGuarantorName3") = loanData.Range("CustName4") .Range("genGuarantorName4") = loanData.Range("CustName5") .Range("genGuarantorName5") = loanData.Range("CustName6") End With End If Else: GeneralInfo.Range("NoGuar") = 0 GeneralInfo.Range("A7") = vbNullString Select Case borrCount Case Is = 1 GeneralInfo.Range("genBorrName") = CustName1 Case Is = 2 GeneralInfo.Range("genBorrName") = CustName1 &amp; " &amp; " &amp; CustName2 Case Is = 3 GeneralInfo.Range("genBorrName") = CustName1 &amp; " &amp; " &amp; CustName2 GeneralInfo.Range("genGuarantorName1") = CustName3 Case Is = 4 GeneralInfo.Range("genBorrName") = CustName1 &amp; " &amp; " &amp; CustName2 GeneralInfo.Range("genGuarantorName1") = CustName3 &amp; " &amp; " &amp; custName4 Case Is = 5 GeneralInfo.Range("genBorrName") = CustName1 &amp; " &amp; " &amp; CustName2 GeneralInfo.Range("genGuarantorName1") = CustName3 &amp; " &amp; " &amp; custName4 GeneralInfo.Range("genGuarantorName2") = CustName5 Case Is = 6 GeneralInfo.Range("genBorrName") = CustName1 &amp; " &amp; " &amp; CustName2 GeneralInfo.Range("genGuarantorName1") = CustName3 &amp; " &amp; " &amp; custName4 GeneralInfo.Range("genGuarantorName2") = CustName5 &amp; " &amp; " &amp; CustName6 Case Is = 7 GeneralInfo.Range("genBorrName") = CustName1 &amp; " &amp; " &amp; CustName2 GeneralInfo.Range("genGuarantorName1") = CustName3 &amp; " &amp; " &amp; custName4 GeneralInfo.Range("genGuarantorName2") = CustName5 &amp; " &amp; " &amp; CustName6 GeneralInfo.Range("genGuarantorName3") = CustName7 Case Is = 8 GeneralInfo.Range("genBorrName") = CustName1 &amp; " &amp; " &amp; CustName2 GeneralInfo.Range("genGuarantorName1") = CustName3 &amp; " &amp; " &amp; custName4 GeneralInfo.Range("genGuarantorName2") = CustName5 &amp; " &amp; " &amp; CustName6 GeneralInfo.Range("genGuarantorName3") = CustName7 &amp; " &amp; " &amp; custName8 End Select End If ' GETS COUNTY CODE DEPENDANT ON COUNTY NAME lastRow = LoanCodes.Cells(LoanCodes.Rows.Count, "Q").End(xlUp).row Dim i As Integer Dim countyName As String countyName = loanData.Range("County") Select Case loanData.Range("County") Case Is &lt;&gt; vbNullString For i = 3 To lastRow For Each c In LoanCodes.Range("Q" &amp; i) If LCase(Split(c.Value, " ")(0)) = LCase(Split(countyName, " ")(0)) Then GeneralInfo.Range("genProperty_Tax_Code") = c.Offset(0, -1).Value End If Next c Next i Case Is = vbNullString Exit Sub End Select If Not SheetData.Range("Date_Outside_Appraisal_Received") = vbNullString Then With GeneralInfo.Range("genAppReceived") .Interior.Color = RGB(252, 213, 180) .BorderAround , xlThin, xlColorIndexAutomatic .Value = "X" End With GeneralInfo.Range("AE14") = "Appraisal Received(Outside)" End If If Not SheetData.Range("Date_Outside_Title_Received") = vbNullString Then With GeneralInfo.Range("genTitleReceived") .Interior.Color = RGB(252, 213, 180) .BorderAround , xlThin, xlColorIndexAutomatic .Value = "X" End With GeneralInfo.Range("AE15") = "Title Work Received(Outside)" End If If Not SheetData.Range("Date_In_House_Appraisal_Received") = vbNullString Then With GeneralInfo.Range("genAppReceivedIH") .Interior.Color = RGB(252, 213, 180) .BorderAround , xlThin, xlColorIndexAutomatic .Value = "X" End With GeneralInfo.Range("AE16") = "In-House Eval Received" End If If Not SheetData.Range("Date_In_House_Title_Received") = vbNullString Then With GeneralInfo.Range("genTitleReceivedIH") .Interior.Color = RGB(252, 213, 180) .BorderAround , xlThin, xlColorIndexAutomatic .Value = "X" End With GeneralInfo.Range("AE17") = "In-House Title Work Received" End If If SheetData.Range("In_House_Eval_Ordered") &lt;&gt; vbNullString Then With GeneralInfo.Range("genAppReceivedIH") .Interior.Color = RGB(252, 213, 180) .BorderAround , xlThin, xlColorIndexAutomatic .Value = "X" End With GeneralInfo.Range("AE16") = "In-House Eval Received" End If If SheetData.Range("In_House_Title_Ordered") &lt;&gt; vbNullString Then With GeneralInfo.Range("genTitleReceivedIH") .Interior.Color = RGB(252, 213, 180) .BorderAround , xlThin, xlColorIndexAutomatic .Value = "X" End With GeneralInfo.Range("AE17") = "In-House Title Work Received" End If End Sub </code></pre> <pre class="lang-vb prettyprint-override"><code>Sub AssignLoanNumber() Dim wbData As Workbook Dim wsData As Worksheet Dim nextCell As Long Dim cName As String, lnProg As String, LoanNum As String, AppDate As String, msgCap As String Dim loanAmt As Double Application.DisplayAlerts = False Application.ScreenUpdating = False cName = loanData.Range("CustName1") lnProg = GeneralInfo.Range("genLoanProg") AppDate = GeneralInfo.Range("genAppDate") loanAmt = GeneralInfo.Range("GenLoanAmount") If IsWorkBookOpen("L:\Loans\1_Frequent\Consumer Loan Numbers - MLA.xlsx") Then If MsgBox("The Consumer Loan Numbers Workbook is currently open." &amp; vbCrLf &amp; _ "Please try again later.", vbOKOnly + vbCritical) = vbOK Then Exit Sub End If Else Select Case cName Case Is = vbNullString If MsgBox("You will need to manually enter in the Customer's Name, Application Date and Dollar Amount in the corresponding fields in the Consumer Loan Numbers Workbook.", _ vbOKOnly + vbInformation) = vbOK Then Workbooks.Open ("L:\Loans\1_Frequent\Consumer Loan Numbers - MLA.xls") End If Case Is &lt;&gt; "Zack Test" If AppDate = vbNullString Then AppDate = InputBox("Please enter in the Application Date or TBD if we do not have a full Application") GeneralInfo.Range("genAppDate") = AppDate End If If GeneralInfo.Range("genLoanNumber") &lt;&gt; vbNullString Then Exit Sub Else: Set wbData = Workbooks.Open("L:\Loans\1_Frequent\Consumer Loan Numbers - MLA.xlsx") Set wsData = wbData.Sheets("MLA") nextCell = wsData.Cells(wsData.Rows.Count, "B").End(xlUp).row + 1 LoanNum = wsData.Range("B" &amp; nextCell).Offset(0, -1) wsData.Range("B" &amp; nextCell) = cName wsData.Range("B" &amp; nextCell).Offset(0, 1) = AppDate GeneralInfo.Range("genLoanNumber") = LoanNum wbData.Close True GoTo Message End If Case Is = "Zack Test": Exit Sub End Select End If Message: msgCap = "The following information was tied to Loan Number: " &amp; LoanNum &amp; vbCrLf &amp; _ " Customer Name: " &amp; cName &amp; vbCrLf &amp; _ " Application Date: " &amp; AppDate MsgBox msgCap, vbOKOnly + vbInformation Application.ScreenUpdating = True Application.DisplayAlerts = True End Sub </code></pre> <pre class="lang-vb prettyprint-override"><code>Option Explicit Public Function IsWorkBookOpen(FileName As String) Dim ff As Long, ErrNo As Long On Error Resume Next ff = FreeFile() Open FileName For Input Lock Read As #ff Close ff ErrNo = Err On Error GoTo 0 Select Case ErrNo Case 0: IsWorkBookOpen = False Case 70: IsWorkBookOpen = True Case Else: Error ErrNo End Select End Function </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T20:31:47.667", "Id": "463181", "Score": "0", "body": "`AssignLoanNumber` Isn't defined anywhere in your code. Please include it so we can accurately review your code without making assumptions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T20:38:19.683", "Id": "463182", "Score": "0", "body": "Sorry about that. I added the code for that procedure and the function that is in the `AssignLoanNumber` procedure." } ]
[ { "body": "<p>The variable <code>lastRow</code> isn't defined anywhere. From the menu Tools>Options>Editor tab>Code Settings group>Require Variable Declaration. Make sure that box is checked. It mandates all variable be declared before use. Future-you will thank present you for that.</p>\n\n<hr>\n\n<p>Static cell ranges like <code>\"B2:B9\"</code> will break if a row/column is inserted above/to-the-left-of that range. As is done elsewhere in your code use a named range. This aids in documenting your code.</p>\n\n<hr>\n\n<p>The repeated <code>Select Case</code> can be shortened. It will only step in when check is true. Consolidate them and extract them into a private function.</p>\n\n<pre><code>Private Function AreLoanInputsBlank() As Boolean\n AreLoanInputsBlank = GeneralInfo.Range(\"genLoanNumber\").Value2 = vbNullString _\n And SheetData.Range(\"Construction_Loan\").Value2 = vbNullString _\n And SheetData.Range(\"Do_Not_Assign_Loan_Number\").Value2 = vbNullString\nEnd Function\n</code></pre>\n\n<p>That function then is called as follows. Note the removal of <code>Else:</code>. That's a code smell. Place it on its own line. Using <code>:</code> just because you can IMO needlessly opens you to more difficulties debugging later. The assignment of <code>\"X\"</code> is also now explicitly done by accessing the <code>.Value2</code> property. Avoid using default members as it arguably makes code harder to understand. This includes <code>Err</code> being replaced with <code>Err.Number</code>. Just say no to default members.</p>\n\n<pre><code> If AreLoanInputsBlank Then\n Dim repsonse As VbMsgBoxResult\n response = MsgBox(\"Would you like to assign the loan number now?\", vbYesNo + vbCritical, UCase$(\"Assign Loan Number\"))\n If repsonse = vbYes Then\n AssignLoanNumber\n Else\n SheetData.Range(\"Do_Not_Assign_Loan_Number\").Value2 = \"X\"\n End If\n End If\n</code></pre>\n\n<hr>\n\n<p>Variables with numeric suffixes like <code>CustName1</code> is as code smell. Use an array instead.</p>\n\n<pre><code>Dim CustName1 As String, CustName2 As String, CustName3 As String, custName4 As String\nDim CustName5 As String, CustName6 As String, CustName7 As String, custName8 As String\n\nCustName1 = loanData.Range(\"CustLNSuff1\") &amp; \", \" &amp; loanData.Range(\"CustFMI1\")\nCustName2 = loanData.Range(\"CustLNSuff2\") &amp; \", \" &amp; loanData.Range(\"CustFMI2\")\nCustName3 = loanData.Range(\"CustLNSuff3\") &amp; \", \" &amp; loanData.Range(\"CustFMI3\")\ncustName4 = loanData.Range(\"CustLNSuff4\") &amp; \", \" &amp; loanData.Range(\"CustFMI4\")\nCustName5 = loanData.Range(\"CustLNSuff5\") &amp; \", \" &amp; loanData.Range(\"CustFMI5\")\nCustName6 = loanData.Range(\"CustLNSuff6\") &amp; \", \" &amp; loanData.Range(\"CustFMI6\")\nCustName7 = loanData.Range(\"CustLNSuff7\") &amp; \", \" &amp; loanData.Range(\"CustFMI7\")\ncustName8 = loanData.Range(\"CustLNSuff8\") &amp; \", \" &amp; loanData.Range(\"CustFMI8\")\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>Dim customerNames(1 To 8) As String\ncustomerNames(1) = loanData.Range(\"CustLNSuff1\").Value2 &amp; \", \" &amp; loanData.Range(\"CustFMI1\").Value2\ncustomerNames(2) = loanData.Range(\"CustLNSuff2\").Value2 &amp; \", \" &amp; loanData.Range(\"CustFMI2\").Value2\ncustomerNames(3) = loanData.Range(\"CustLNSuff3\").Value2 &amp; \", \" &amp; loanData.Range(\"CustFMI3\").Value2\ncustomerNames(4) = loanData.Range(\"CustLNSuff4\").Value2 &amp; \", \" &amp; loanData.Range(\"CustFMI4\").Value2\ncustomerNames(5) = loanData.Range(\"CustLNSuff5\").Value2 &amp; \", \" &amp; loanData.Range(\"CustFMI5\").Value2\ncustomerNames(6) = loanData.Range(\"CustLNSuff6\").Value2 &amp; \", \" &amp; loanData.Range(\"CustFMI6\").Value2\ncustomerNames(7) = loanData.Range(\"CustLNSuff7\").Value2 &amp; \", \" &amp; loanData.Range(\"CustFMI7\").Value2\ncustomerNames(8) = loanData.Range(\"CustLNSuff8\").Value2 &amp; \", \" &amp; loanData.Range(\"CustFMI8\").Value2\n</code></pre>\n\n<p>which can further be condensed to a dedicated function for populating the array</p>\n\n<pre><code>Private Function GetCustomerNames(ByVal lowerBound As Long, ByVal upperBound As Long) As String()\n Dim tempArray() As String\n ReDim tempArray(lowerBound, upperBound)\n Dim nameCounter As Long\n For nameCounter = lowerBound To upperBound\n tempArray(nameCounter) = loanData.Range(\"CustLNSuff\" &amp; CStr(nameCounter)).Value2 &amp; \", \" &amp; loanData.Range(\"CustFMI\" &amp; CStr(nameCounter)).Value2\n Next\n GetCustomerNames = tempArray\nEnd Function\n</code></pre>\n\n<p>that is called via.</p>\n\n<pre><code>Dim customerNames() As String\ncustomerNames = GetCustomerNames(1, 8)\n</code></pre>\n\n<p>The <code>For ... Next</code> loop for population mandates you follow <code>Range(\"CustLNSuff\" &amp; #)</code> convention for the names. If you can't follow that keep the dedicated function but return to populating each element on its own line. IE <code>tempArray(1) = loanData.Range(\"CustLNSuff1\").Value2 &amp; \", \" &amp; loanData.Range(\"CustFMI1\").Value2</code>. I hope you got the idea.</p>\n\n<hr>\n\n<p>Checking <code>GeneralInfo.Range(\"NoGuar\").value = vbNullString</code> is a smell. If you're checking that the cell is not populated <code>IsEmpty(GeneralInfo.Range(\"NoGuar\"))</code> is preferred. The caveat to this is if that cell contains a formula that results to <code>\"\"</code> then checking against <code>vbNullString</code> is appropriate.</p>\n\n<hr>\n\n<p>The section where you're assigning the named ranges <code>genBorrName</code>, <code>genGuarantorName1</code>, <code>genGuarantorName2</code>, and <code>genGuarantorName3</code> has duplicated assignment. Don't Repeat Yourself (DRY). <code>GeneralInfo.Range(\"genBorrName\") = CustName1 &amp; \" &amp; \" &amp; CustName2</code> occurs in case 2 through 8. Extract this block of code into its own sub and name it. As I'm not sure the best way to deal with this section, I did what I thought best. After refactoring.</p>\n\n<pre><code>Private Sub AssignGrantorNames(ByVal borrCount As Long, ByRef names() As String)\n If borrCount &lt; 1 Then\n Const InvalidArgument As Long = 5\n Err.Raise InvalidArgument, \"AssignGrantorNames\", \"Invalid number provided.\"\n End If\n\n If borrCount = 1 Then\n GeneralInfo.Range(\"genBorrName\") = names(1)\n Exit Sub\n Else\n GeneralInfo.Range(\"genBorrName\") = names(1) &amp; \" &amp; \" &amp; names(2)\n If borrCount = 2 Then Exit Sub\n End If\n\n If borrCount = 3 Then\n GeneralInfo.Range(\"genGuarantorName1\") = names(3)\n Exit Sub\n Else\n GeneralInfo.Range(\"genGuarantorName1\") = names(3) &amp; \" &amp; \" &amp; names(4)\n If borrCount = 4 Then Exit Sub\n End If\n\n If borrCount = 5 Then\n GeneralInfo.Range(\"genGuarantorName2\") = names(5)\n Else\n GeneralInfo.Range(\"genGuarantorName2\") = names(5) &amp; \" &amp; \" &amp; names(6)\n If borrCount = 6 Then Exit Sub\n End If\n\n If borrCount = 7 Then\n GeneralInfo.Range(\"genGuarantorName3\") = names(7)\n Else\n GeneralInfo.Range(\"genGuarantorName3\") = names(7) &amp; \" &amp; \" &amp; names(8)\n End If\nEnd Sub\n</code></pre>\n\n<p>That code is thereafter called as follows.</p>\n\n<pre><code>AssignGrantorNames borrCount, customerNames\n</code></pre>\n\n<hr>\n\n<p>I'm a proponent of declaring a variable just before it's use. The reason for this is <code>lnProg</code> and <code>loanAmt</code> are both declared, assigned a value, and then never used... They don't need to be there. Declaring the variable and assigning it immediately before it's used avoids scenario.</p>\n\n<hr>\n\n<p>Have your boolean checks be consistent. Choose one and stick with it.</p>\n\n<ul>\n<li><code>If fooSheet.Range(\"bar\") &lt;&gt; vbNullString Then</code></li>\n<li><code>If Not fooSheet.Range(\"bar\") = vbNullString Then</code></li>\n</ul>\n\n<hr>\n\n<p>Another instance of DRY. <code>.Interior.Color = RGB(252, 213, 180)</code> is used several times. Extract that duplicated into a dedicate Sub.</p>\n\n<pre><code>Private Sub UpdateCellFormatting(ByVal updateCell As Range, ByVal interiorColor As Long, ByVal value As String)\n updateCell.Interior.Color = interiorColor\n updateCell.BorderAround Weight:=xlThin, ColorIndex:=xlColorIndexAutomatic\n updateCell.value = \"X\"\nEnd Sub\n</code></pre>\n\n<p>Then call it and provide the arguments it needs. Note the 2 new constants that are provided to every invocation of the sub. Now instead of changing multiple lines you change it once and it will updated all usages.</p>\n\n<pre><code> Const PeachInteriorColor As Long = 11851260 'RGB(252, 213, 180)\n Const UpdateValue As String = \"X\"\n\n If SheetData.Range(\"Date_Outside_Appraisal_Received\").Value2 &lt;&gt; vbNullString Then\n UpdateCellFormatting GeneralInfo.Range(\"genAppReceived\"), PeachInteriorColor, UpdateValue\n GeneralInfo.Range(\"AE14\").Value2 = \"Appraisal Received(Outside)\"\n End If\n</code></pre>\n\n<hr>\n\n<p>The block of code below has a few issues. They are listed as I saw them to illustrate how cleaning up code leads you to find further ways to clean it:</p>\n\n<ul>\n<li>Variable reuse: Dont. <code>c</code> is used declared above and reused here. Create a new variable and use it in this location. </li>\n<li>As originally written there's no need to use a <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/for-eachnext-statement\" rel=\"nofollow noreferrer\">For Each ... Next statement</a> and use <code>c</code> because <code>Range(\"Q\" &amp; i)</code> is a single cell.</li>\n<li>The <code>i</code> variable is being incremented as part of the <code>For ... Next statement</code>. Use <em>that</em> range, starting from row 3 to <code>lastRow</code>, for the <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/fornext-statement\" rel=\"nofollow noreferrer\">For Each ... Next</a> statement.</li>\n<li>The statement <code>LCase(Split(countyName, \" \")(0))</code> is repeatedly executed within the loop when it shouldn't. Have that occur <em>once</em> before the loop and use the result.</li>\n<li>The column used <code>\"Q\"</code> can be referenced with a constant so that any changes require updating only that constant.</li>\n<li>Only the <em>last</em> assignment to <code>GeneralInfo.Range(\"genProperty_Tax_Code\").Value2</code> is used. All other assignments are overwritten each time.</li>\n</ul>\n\n<pre><code>lastRow = LoanCodes.Cells(LoanCodes.Rows.Count, \"Q\").End(xlUp).Row\nDim i As Integer\nDim countyName As String\n\ncountyName = loanData.Range(\"County\")\n\nSelect Case loanData.Range(\"County\")\n Case Is &lt;&gt; vbNullString\n For i = 3 To lastRow\n For Each c In LoanCodes.Range(\"Q\" &amp; i)\n If LCase(Split(c.value, \" \")(0)) = LCase(Split(countyName, \" \")(0)) Then\n GeneralInfo.Range(\"genProperty_Tax_Code\") = c.Offset(0, -1).value\n End If\n Next c\n Next i\n Case Is = vbNullString\n Exit Sub\nEnd Select\n</code></pre>\n\n<p>Following those points you can refactor to</p>\n\n<pre><code> Const LoanCodeColumn As String = \"Q\"\n Dim countyName As String\n countyName = loanData.Range(\"County\").Value2\n Dim countyNameBeforeFirstSpaceCharacter As String\n countyNameBeforeFirstSpaceCharacter = LCase(Split(countyName, \" \")(0))\n Select Case countyName\n Case Is &lt;&gt; vbNullString\n Dim lastRow As Long\n lastRow = LoanCodes.Cells(LoanCodes.Rows.Count, LoanCodeColumn).End(xlUp).Row\n Dim lastCell As Range\n Set lastCell = LoanCodes.Cells(lastRow, LoanCodeColumn)\n If LCase(Split(lastCell.Value2, \" \")(0)) = countyNameBeforeFirstSpaceCharacter Then\n GeneralInfo.Range(\"genProperty_Tax_Code\").Value2 = lastCell.Offset(0, -1).value\n End If\n Case Is = vbNullString\n Exit Sub\n End Select\n</code></pre>\n\n<hr>\n\n<p><code>AssignLoanNumber</code> is implictly public. Explicitly make it public by adding the <code>Public</code> access modifier.</p>\n\n<hr>\n\n<p><code>MsgBox</code> with the only button available as <code>vbOKOnly</code> can only return <code>vbOK</code> as its result. No need to check the return value. Display the message and exit.</p>\n\n<pre><code>If MsgBox(\"The Consumer Loan Numbers Workbook is currently open.\" &amp; vbCrLf &amp; _\n \"Please try again later.\", vbOKOnly + vbCritical) = vbOK Then\n Exit Sub\nEnd If\n</code></pre>\n\n<p>Refactor it.</p>\n\n<pre><code>MsgBox \"The Consumer Loan Numbers Workbook is currently open.\" &amp; vbCrLf &amp; _\n \"Please try again later.\", vbOKOnly + vbCritical\nExit Sub\n</code></pre>\n\n<hr>\n\n<p>You don't need to use <code>( )</code> for <code>Workbooks.Open (\"L:\\Loans\\1_Frequent\\Consumer Loan Numbers - MLA.xls\")</code>. Notice the space between <code>Open</code> and <code>(</code>. You're coercing evaluation of the string before supplying it as an argument, causing it to be read only. Bringing this to your attention so you're not bitten by this. Illustrative example shows that even though <code>ByRef</code> is used, only the non parenthetical invocation reflects the assignment from within the method. This is different from <code>Set wbData = Workbooks.Open(\"L:\\Loans\\1_Frequent\\Consumer Loan Numbers - MLA.xlsx\")</code> which does not have the space after <code>Open</code> because <code>( )</code> are mandated because of the assignment of the return value.</p>\n\n<pre><code>Public Sub Foo()\n Dim uncoercedArgument As String\n uncoercedArgument = \"uncoerced argument string\"\n DemonstarteTheEffectsOfCoercedEvaluation uncoercedArgument\n Debug.Print uncoercedArgument\n\n Dim coercedArugment As String\n coercedArugment = \"coerced Arugment string\"\n DemonstarteTheEffectsOfCoercedEvaluation (coercedArugment)\n Debug.Print coercedArugment\nEnd Sub\n\nPrivate Sub DemonstarteTheEffectsOfCoercedEvaluation(ByRef value As String)\n value = \"I'm changed\"\nEnd Sub\n</code></pre>\n\n<hr>\n\n<p>It feels like your <code>GoTo Message</code> can be refactored so you don't actually need to use GoTo. I'll leave that to you.</p>\n\n<hr>\n\n<p>Edits Rubberduck caught that I forgot/overlooked when worrying about the bigger edits. ***Disclosure: I'm a contributor to the poject. </p>\n\n<ul>\n<li><code>UCase</code> -> <code>UCase$</code>: Use typed function. Same for <code>LCase</code> -> <code>LCase$</code>, <code>RCase</code> -> <code>RCase$</code>.</li>\n<li><code>... As Integer</code> -> <code>... As Long</code>: Use a 32-bit number to avoid overflows. IIRC internally <code>Integer</code> actually uses <code>Long</code>.</li>\n</ul>\n\n<hr>\n\n<p>Complete refactoring all together.</p>\n\n<pre><code>Public Sub foo()\n Dim customerNames(1 To 8) As String\n Dim nameCounter As Long\n For nameCounter = LBound(customerNames) To UBound(customerNames)\n customerNames(nameCounter) = loanData.Range(\"CustLNSuff\" &amp; CStr(nameCounter)).Value2 &amp; \", \" &amp; loanData.Range(\"CustFMI\" &amp; CStr(nameCounter)).Value2\n Next\nEnd Sub\n\nPrivate Sub Worksheet_Activate()\n If AreLoanInputsBlank Then\n Dim response As VbMsgBoxResult\n response = MsgBox(\"Would you like to assign the loan number now?\", vbYesNo + vbCritical, UCase$(\"Assign Loan Number\"))\n If response = vbYes Then\n AssignLoanNumber \"L:\\Loans\\1_Frequent\\\"\n Else\n SheetData.Range(\"Do_Not_Assign_Loan_Number\").Value2 = \"X\"\n End If\n End If\n\n GeneralInfo.Range(\"A7\").Value2 = vbNullString\n\n If loanData.Range(\"Entity\").Value2 &lt;&gt; vbNullString Then\n If GeneralInfo.Range(\"NoGuar\").Value2 = 0 Or IsEmpty(GeneralInfo.Range(\"NoGuar\")) Then\n Dim cell As Range\n For Each cell In loanData.Range(\"B3:B9\")\n If cell.value &lt;&gt; vbNullString Then\n Dim guarantorCount As Long\n guarantorCount = guarantorCount + 1\n End If\n Next\n\n With GeneralInfo\n .Range(\"NoGuar\").Value2 = guarantorCount\n .Range(\"A7\").Value2 = \"Guarantor(s)\"\n .Range(\"genBorrName\").Value2 = loanData.Range(\"CustName1\").Value2\n .Range(\"genGuarantorName1\").Value2 = loanData.Range(\"CustName2\").Value2\n .Range(\"genGuarantorName2\").Value2 = loanData.Range(\"CustName3\").Value2\n .Range(\"genGuarantorName3\").Value2 = loanData.Range(\"CustName4\").Value2\n .Range(\"genGuarantorName4\").Value2 = loanData.Range(\"CustName5\").Value2\n .Range(\"genGuarantorName5\").Value2 = loanData.Range(\"CustName6\").Value2\n End With\n End If\n Else\n GeneralInfo.Range(\"NoGuar\").Value2 = 0\n GeneralInfo.Range(\"A7\").Value2 = vbNullString\n\n Dim customerNames() As String\n customerNames = GetCustomerNames(1, 8)\n\n Dim borrCount As Long\n borrCount = Application.WorksheetFunction.CountA(loanData.Range(\"B2:B9\"))\n\n AssignGrantorNames borrCount, customerNames\n End If\n\n' GETS COUNTY CODE DEPENDANT ON COUNTY NAME\n Const LoanCodeColumn As String = \"Q\"\n Dim countyName As String\n countyName = loanData.Range(\"County\").Value2\n Dim countyNameBeforeFirstSpaceCharacter As String\n countyNameBeforeFirstSpaceCharacter = LCase$(Split(countyName, \" \")(0))\n Select Case countyName\n Case Is &lt;&gt; vbNullString\n Dim lastRow As Long\n lastRow = LoanCodes.Cells(LoanCodes.Rows.Count, LoanCodeColumn).End(xlUp).Row\n Dim lastCell As Range\n Set lastCell = LoanCodes.Cells(lastRow, LoanCodeColumn)\n If LCase$(Split(lastCell.Value2, \" \")(0)) = countyNameBeforeFirstSpaceCharacter Then\n GeneralInfo.Range(\"genProperty_Tax_Code\").Value2 = lastCell.Offset(0, -1).Value2\n End If\n Case Is = vbNullString\n Exit Sub\n End Select\n\n Const PeachInteriorColor As Long = 11851260 'RGB(252, 213, 180)\n Const UpdateValue As String = \"X\"\n Const UpdateBorderWeight As Long = XlBorderWeight.xlThin\n Const UpdateBorderColor As Long = XlColorIndex.xlColorIndexAutomatic\n\n If SheetData.Range(\"Date_Outside_Appraisal_Received\").Value2 &lt;&gt; vbNullString Then\n UpdateCellFormatting GeneralInfo.Range(\"genAppReceived\"), PeachInteriorColor, UpdateBorderWeight, UpdateBorderColor, UpdateValue\n GeneralInfo.Range(\"AE14\").Value2 = \"Appraisal Received(Outside)\"\n End If\n\n If SheetData.Range(\"Date_Outside_Title_Received\").Value2 &lt;&gt; vbNullString Then\n UpdateCellFormatting GeneralInfo.Range(\"genTitleReceived\"), PeachInteriorColor, UpdateBorderWeight, UpdateBorderColor, UpdateValue\n GeneralInfo.Range(\"AE15\").Value2 = \"Title Work Received(Outside)\"\n End If\n\n If SheetData.Range(\"Date_In_House_Appraisal_Received\").Value2 &lt;&gt; vbNullString Then\n UpdateCellFormatting GeneralInfo.Range(\"genAppReceivedIH\"), PeachInteriorColor, UpdateBorderWeight, UpdateBorderColor, UpdateValue\n GeneralInfo.Range(\"AE16\").Value2 = \"In-House Eval Received\"\n End If\n\n If SheetData.Range(\"Date_In_House_Title_Received\").Value2 &lt;&gt; vbNullString Then\n UpdateCellFormatting GeneralInfo.Range(\"genTitleReceivedIH\"), PeachInteriorColor, UpdateBorderWeight, UpdateBorderColor, UpdateValue\n GeneralInfo.Range(\"AE17\").Value2 = \"In-House Title Work Received\"\n End If\n\n If SheetData.Range(\"In_House_Eval_Ordered\").Value2 &lt;&gt; vbNullString Then\n UpdateCellFormatting GeneralInfo.Range(\"genAppReceivedIH\"), PeachInteriorColor, UpdateBorderWeight, UpdateBorderColor, UpdateValue\n GeneralInfo.Range(\"AE16\").Value2 = \"In-House Eval Received\"\n End If\n\n If SheetData.Range(\"In_House_Title_Ordered\").Value2 &lt;&gt; vbNullString Then\n UpdateCellFormatting GeneralInfo.Range(\"genTitleReceivedIH\"), PeachInteriorColor, UpdateBorderWeight, UpdateBorderColor, UpdateValue\n GeneralInfo.Range(\"AE17\").Value2 = \"In-House Title Work Received\"\n End If\nEnd Sub\n\nPrivate Function AreLoanInputsBlank() As Boolean\n AreLoanInputsBlank = GeneralInfo.Range(\"genLoanNumber\").Value2 = vbNullString _\n And SheetData.Range(\"Construction_Loan\").Value2 = vbNullString _\n And SheetData.Range(\"Do_Not_Assign_Loan_Number\").Value2 = vbNullString\nEnd Function\n\nPrivate Sub AssignGrantorNames(ByVal borrCount As Long, ByRef customerNames() As String)\n If borrCount &lt; 1 Then\n Const InvalidArgument As Long = 5\n Err.Raise InvalidArgument, \"AssignGrantorNames\", \"Invalid number provided.\"\n End If\n\n If borrCount = 1 Then\n GeneralInfo.Range(\"genBorrName\").Value2 = customerNames(1)\n Exit Sub\n Else\n GeneralInfo.Range(\"genBorrName\").Value2 = customerNames(1) &amp; \" &amp; \" &amp; customerNames(2)\n If borrCount = 2 Then Exit Sub\n End If\n\n If borrCount = 3 Then\n GeneralInfo.Range(\"genGuarantorName1\").Value2 = customerNames(3)\n Exit Sub\n Else\n GeneralInfo.Range(\"genGuarantorName1\").Value2 = customerNames(3) &amp; \" &amp; \" &amp; customerNames(4)\n If borrCount = 4 Then Exit Sub\n End If\n\n If borrCount = 5 Then\n GeneralInfo.Range(\"genGuarantorName2\").Value2 = customerNames(5)\n Else\n GeneralInfo.Range(\"genGuarantorName2\").Value2 = customerNames(5) &amp; \" &amp; \" &amp; customerNames(6)\n If borrCount = 6 Then Exit Sub\n End If\n\n If borrCount = 7 Then\n GeneralInfo.Range(\"genGuarantorName3\").Value2 = customerNames(7)\n Else\n GeneralInfo.Range(\"genGuarantorName3\").Value2 = customerNames(7) &amp; \" &amp; \" &amp; customerNames(8)\n End If\nEnd Sub\n\nPrivate Function GetCustomerNames(ByVal lowerBound As Long, ByVal upperBound As Long) As String()\n Dim tempArray() As String\n ReDim tempArray(lowerBound, upperBound)\n Dim nameCounter As Long\n For nameCounter = lowerBound To upperBound\n tempArray(nameCounter) = loanData.Range(\"CustLNSuff\" &amp; CStr(nameCounter)).Value2 &amp; \", \" &amp; loanData.Range(\"CustFMI\" &amp; CStr(nameCounter)).Value2\n Next\n GetCustomerNames = tempArray\nEnd Function\n\nPrivate Sub UpdateCellFormatting(ByVal updateCell As Range, _\n ByVal interiorColor As Long, _\n ByVal borderWeight As Long, _\n ByVal borderColor As Long, _\n ByVal value As String)\n updateCell.Interior.Color = interiorColor\n updateCell.BorderAround Weight:=borderWeight, ColorIndex:=borderColor\n updateCell.value = value\nEnd Sub\n\nPublic Sub AssignLoanNumber(ByVal loanPath As String)\n Dim safeLoanPath As String\n If Right$(loanPath, 1) &lt;&gt; Application.PathSeparator Then\n safeLoanPath = loanPath &amp; Application.PathSeparator\n End If\n Application.DisplayAlerts = False\n Application.ScreenUpdating = False\n\n If IsWorkBookOpen(safeLoanPath &amp; \"Consumer Loan Numbers - MLA.xlsx\") Then\n MsgBox \"The Consumer Loan Numbers Workbook is currently open.\" &amp; vbCrLf &amp; \"Please try again later.\", vbOKOnly + vbCritical\n Exit Sub\n Else\n Dim customerName As String\n customerName = loanData.Range(\"CustName1\").Value2\n Select Case customerName\n Case Is = vbNullString\n MsgBox \"You will need to manually enter in the Customer's Name, Application Date and Dollar Amount in the corresponding fields in the Consumer Loan Numbers Workbook.\", _\n vbOKOnly + vbInformation\n Workbooks.Open safeLoanPath &amp; \"Consumer Loan Numbers - MLA.xls\"\n Case Is &lt;&gt; \"Zack Test\"\n Dim AppDate As String\n AppDate = GeneralInfo.Range(\"genAppDate\").Value2\n If AppDate = vbNullString Then\n AppDate = InputBox(\"Please enter in the Application Date or TBD if we do not have a full Application\")\n GeneralInfo.Range(\"genAppDate\").Value2 = AppDate\n End If\n\n If GeneralInfo.Range(\"genLoanNumber\").Value2 = vbNullString Then\n Dim wbData As Workbook\n Set wbData = Workbooks.Open(safeLoanPath &amp; \"Consumer Loan Numbers - MLA.xlsx\")\n Dim wsData As Worksheet\n Set wsData = wbData.Sheets(\"MLA\")\n\n Dim nextCell As Long\n nextCell = wsData.Cells(wsData.Rows.Count, \"B\").End(xlUp).Row + 1\n\n Dim LoanNum As String\n LoanNum = wsData.Range(\"B\" &amp; nextCell).Offset(0, -1).Value2\n wsData.Range(\"B\" &amp; nextCell).Value2 = customerName\n wsData.Range(\"B\" &amp; nextCell).Offset(0, 1).Value2 = AppDate\n GeneralInfo.Range(\"genLoanNumber\").Value2 = LoanNum\n wbData.Close True\n\n Dim msgCap As String\n msgCap = \"The following information was tied to Loan Number: \" &amp; LoanNum &amp; vbCrLf &amp; _\n \" Customer Name: \" &amp; customerName &amp; vbCrLf &amp; _\n \" Application Date: \" &amp; AppDate\n MsgBox msgCap, vbOKOnly + vbInformation\n End If\n End Select\n End If\n\n Application.ScreenUpdating = True\n Application.DisplayAlerts = True\nEnd Sub\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T22:31:19.777", "Id": "463390", "Score": "0", "body": "Thank you. I am reviewing all of the very helpful information in your review. I really appreciate the use of the `Array` with the customer names section since that was giving me a headache trying to figure out how to set that up." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T23:29:41.190", "Id": "236385", "ParentId": "236300", "Score": "4" } } ]
{ "AcceptedAnswerId": "236385", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T15:46:30.920", "Id": "236300", "Score": "3", "Tags": [ "vba", "excel" ], "Title": "Checks data already stored in specific worksheets then populates data as needed" }
236300
<p>I'm trying to add error handling and response logging for API calls. The way I have my application (chatbot) set up is that a helper function is called from the main dialog, and that helper function calls the API. I believe this is standard practice. What I'm not sure on is how I should be catching errors in the process and where the appropriate point to do various logging is. I've considered the approach of putting all error catching in the helper, but if the API call fails, I still need an exception path in my main dialog. So what I've settled on is a try/catch block to call the function, which will catch API call failure in the helper. If the API call is successful, I'm logging the result from the helper. If the API call fails, I'm logging the failure from the main dialog. Here are the appropriate code snippets:</p> <p><em>statusDialog.js</em></p> <pre><code>try { const orderResponse = await orderStatusHelper.getStatus(orderNumber); } catch(err) { appInsightsClient.trackTrace({ message: `API Response - ${path.basename(__filename)}`, severity: 3, properties: {'error':err.message,'callStack':err.stack} }); } </code></pre> <p><em>orderStatusHelper.js</em></p> <pre><code>let response = await request ({ url:url, method: 'POST', headers: headers, json: postData }); // If call fails, main function goes to catch block // If call succeeds, log response and return result appInsightsClient.trackTrace({ message: `API Response - ${path.basename(__filename)}`, severity: 1, properties: {response} }); return response; </code></pre> <p>I would appreciate feedback on</p> <ul> <li>If this is the proper method to catch errors when I'm calling a function that's calling an API</li> <li>If I am logging the response (or lack thereof) in the right spot</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T16:28:01.040", "Id": "236301", "Score": "2", "Tags": [ "node.js", "error-handling" ], "Title": "Best way to catch API errors and log responses when calling via helper function" }
236301
<p>i need to improve the performance of ConcurrentDictionary.</p> <p>for that i created 2 classes for check if the more efficiencies than the original.</p> <pre><code>public class FixedConcurrentDictionary&lt;TKey, TValue&gt; { readonly ConcurrentDictionary&lt;TKey, TValue&gt; _dictionary = new ConcurrentDictionary&lt;TKey, TValue&gt;(); public bool IsEmpty { get { return Count == 0; } } public int Count { get { return _dictionary.Skip(0).Count(); } } public IEnumerable&lt;TKey&gt; Keys { get { return _dictionary.Select(i =&gt; i.Key); } } public IEnumerable&lt;TValue&gt; Values { get { return _dictionary.Select(i =&gt; i.Value); } } public void Clear() { _dictionary.Clear(); } public bool TryGetValue(TKey key, out TValue value) { return _dictionary.TryGetValue(key, out value); } public bool ContainsKey(TKey key) { return _dictionary.ContainsKey(key); } public TValue this[TKey key] { get { TValue value; if (!TryGetValue(key, out value)) { return default(TValue); } return value; } set { _dictionary[key] = value; } } } public class FixedConcurrentDictionaryToList&lt;TKey, TValue&gt; { readonly ConcurrentDictionary&lt;TKey, TValue&gt; _dictionary = new ConcurrentDictionary&lt;TKey, TValue&gt;(); public bool IsEmpty { get { return Count == 0; } } public int Count { get { return _dictionary.Skip(0).ToList().Count(); } } public IEnumerable&lt;TKey&gt; Keys { get { return _dictionary.Select(i =&gt; i.Key).ToList(); } } public IEnumerable&lt;TValue&gt; Values { get { return _dictionary.Select(i =&gt; i.Value).ToList(); } } public void Clear() { _dictionary.Clear(); } public bool TryGetValue(TKey key, out TValue value) { return _dictionary.TryGetValue(key, out value); } public bool ContainsKey(TKey key) { return _dictionary.ContainsKey(key); } public TValue this[TKey key] { get { TValue value; if (!TryGetValue(key, out value)) { return default(TValue); } return value; } set { _dictionary[key] = value; } } } public class BenchDictionary : IDisposable { int _length; readonly ReaderWriterLockSlim _locker = new ReaderWriterLockSlim(); readonly Dictionary&lt;string, string&gt; _dictionary = new Dictionary&lt;string, string&gt;(); readonly Stopwatch _stopwatch = new Stopwatch(); bool _isStoppedBench = false; bool _useStopWatch = false; bool _isDisposed = false; public BenchDictionary(int length, bool useStopWatch) { _length = length; _useStopWatch = useStopWatch; var t1 = new Thread(() =&gt; { for (int i = 0; i &lt; _length; i++) { _locker.EnterWriteLock(); string str = $"t{i}"; _dictionary[str] = str; _locker.ExitWriteLock(); } if (_useStopWatch) _stopwatch.Stop(); _isStoppedBench = true; }); t1.Name = "t1"; t1.IsBackground = true; var t2 = new Thread(() =&gt; { while (true) { if (_isStoppedBench || _isDisposed) { if (_useStopWatch) System.Console.WriteLine($"BenchDictionary:: _dictionary.Values.Count: {_dictionary.Values.Count} time elapsed: {_stopwatch.Elapsed.TotalSeconds} sec"); return; } _locker.EnterReadLock(); int count = _dictionary.Values.Count; _locker.ExitReadLock(); } }); t2.Name = "t2"; t2.IsBackground = true; if (_useStopWatch) _stopwatch.Start(); t1.Start(); t2.Start(); } public void Dispose() { if (!_isDisposed) { _isDisposed = true; } } } public class BenchConcurrentDictionary : IDisposable { int _length; readonly ConcurrentDictionary&lt;string, string&gt; _concurrentDictionary = new ConcurrentDictionary&lt;string, string&gt;(); readonly Stopwatch _stopwatch = new Stopwatch(); bool _isStoppedBench = false; bool _useStopWatch = false; bool _isDisposed = false; public BenchConcurrentDictionary(int length, bool useStopWatch) { _length = length; _useStopWatch = useStopWatch; var t1 = new Thread(() =&gt; { for (int i = 0; i &lt; _length; i++) { string str = $"t{i}"; _concurrentDictionary[str] = str; } if (_useStopWatch) _stopwatch.Stop(); _isStoppedBench = true; }); t1.Name = "t1"; t1.IsBackground = true; var t2 = new Thread(() =&gt; { while (true) { if (_isStoppedBench || _isDisposed) { if (_useStopWatch) System.Console.WriteLine($"BenchConcurrentDictionary:: _concurrentDictionary.Values.Count: {_concurrentDictionary.Values.Count} time elapsed: {_stopwatch.Elapsed.TotalSeconds} sec"); return; } int count = _concurrentDictionary.Values.Count; } }); t2.Name = "t2"; t2.IsBackground = true; if (_useStopWatch) _stopwatch.Start(); t1.Start(); t2.Start(); } public void Dispose() { if (!_isDisposed) { _isDisposed = true; } } } public class BenchFixedConcurrentDictionary : IDisposable { int _length; readonly FixedConcurrentDictionary&lt;string, string&gt; _fixedConcurrentDictionary = new FixedConcurrentDictionary&lt;string, string&gt;(); readonly Stopwatch _stopwatch = new Stopwatch(); bool _isStoppedBench = false; bool _useStopWatch = false; bool _isDisposed = false; public BenchFixedConcurrentDictionary(int length, bool useStopWatch) { _length = length; _useStopWatch = useStopWatch; var t1 = new Thread(() =&gt; { for (int i = 0; i &lt; _length; i++) { string str = $"t{i}"; _fixedConcurrentDictionary[str] = str; } if (_useStopWatch) _stopwatch.Stop(); _isStoppedBench = true; }); t1.Name = "t1"; t1.IsBackground = true; var t2 = new Thread(() =&gt; { while (true) { if (_isStoppedBench || _isDisposed) { if (_useStopWatch) System.Console.WriteLine($"BenchFixedConcurrentDictionary:: _fixedConcurrentDictionary.Count: {_fixedConcurrentDictionary.Count} time elapsed: {_stopwatch.Elapsed.TotalSeconds} sec"); return; } int count = _fixedConcurrentDictionary.Count; } }); t2.Name = "t2"; t2.IsBackground = true; if (_useStopWatch) _stopwatch.Start(); t1.Start(); t2.Start(); } public void Dispose() { if (!_isDisposed) { _isDisposed = true; } } } public class BenchFixedConcurrentDictionaryToList : IDisposable { int _length; readonly FixedConcurrentDictionaryToList&lt;string, string&gt; _fixedConcurrentDictionaryToList = new FixedConcurrentDictionaryToList&lt;string, string&gt;(); readonly Stopwatch _stopwatch = new Stopwatch(); bool _isStoppedBench = false; bool _useStopWatch = false; bool _isDisposed = false; public BenchFixedConcurrentDictionaryToList(int length, bool useStopWatch) { _length = length; _useStopWatch = useStopWatch; var t1 = new Thread(() =&gt; { for (int i = 0; i &lt; _length; i++) { string str = $"t{i}"; _fixedConcurrentDictionaryToList[str] = str; } if (_useStopWatch) _stopwatch.Stop(); _isStoppedBench = true; }); t1.Name = "t1"; t1.IsBackground = true; var t2 = new Thread(() =&gt; { while (true) { if (_isStoppedBench || _isDisposed) { if (_useStopWatch) System.Console.WriteLine($"BenchFixedConcurrentDictionaryToList:: _fixedConcurrentDictionaryToList.Count: {_fixedConcurrentDictionaryToList.Count} time elapsed: {_stopwatch.Elapsed.TotalSeconds} sec"); return; } int count = _fixedConcurrentDictionaryToList.Count; } }); t2.Name = "t2"; t2.IsBackground = true; if (_useStopWatch) _stopwatch.Start(); t1.Start(); t2.Start(); } public void Dispose() { if (!_isDisposed) { _isDisposed = true; } } } </code></pre> <p>Than i perform bench marking:</p> <pre><code>[MemoryDiagnoser] [KeepBenchmarkFiles] [MinColumn, MaxColumn, MedianColumn] [Config(typeof(Config))] public class TestDictionary { private class Config : ManualConfig { public Config() { Add( Job.VeryLongRun .With(BenchmarkDotNet.Environments.Platform.AnyCpu) .WithLaunchCount(1) .WithTargetCount(1) .WithWarmupCount(0) ); } } [Params(10000000)] public int Length { get; set; } [Benchmark(Baseline = true)] public void BenchDictionary() { using (new BenchDictionary(Length, false)) { } } [Benchmark] public void BenchConcurrentDictionary() { using (new BenchConcurrentDictionary(Length, false)) { } } [Benchmark] public void BenchFixedConcurrentDictionary() { using (new BenchFixedConcurrentDictionary(Length, false)) { } } [Benchmark] public void BenchFixedConcurrentDictionaryToList() { using (new BenchFixedConcurrentDictionaryToList(Length, false)) { } } } </code></pre> <p>The results: <a href="https://i.stack.imgur.com/uGgdw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uGgdw.png" alt="enter image description here"></a></p> <p>I will be glad for getting a code review for this implementation. Thanks.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T19:09:38.693", "Id": "463015", "Score": "2", "body": "What's the reason for the `Skip(0)`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T10:25:56.687", "Id": "463092", "Score": "2", "body": "few operations in the ConcurrentDictionary cause to acquire all the locks at once: Count, Keys, Values.. so for prevent that i use linq that will attempt to use the count property with it is available.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T00:46:37.883", "Id": "463242", "Score": "0", "body": "OK now I see the point. You're trying to avoid locks by returning an enumerator instead of an array. What happens if I call `fixedDictionary.Keys.ToList()` while another thread is adding an item? Won't you (sometimes) get a \"collection was modified\" exception? Seems like this is making the dictionary less thread-safe." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T19:00:11.667", "Id": "236310", "Score": "3", "Tags": [ "c#", "performance", "multithreading" ], "Title": "ConcurrentDictionary performance" }
236310
<p>I am starting my adventure with Python and object oriented programming.</p> <p>I wrote a script for salting and hashing password. My main goal is practice with OOP, not cryptography. I know there is no error handling.</p> <p>Wonder how improve my code it and make more object oriented. It would be nice if someone more experienced can take a look and give me some advice how to make it better. Any help for newbie would be great!</p> <p><strong>Description:</strong></p> <p>The script is not really useful in real life. </p> <p>1st part:<br> Hash and salt password and next encode to base64 with added salt (needed for future comparing hashes). Algorithm: base64( SHA256(password + salt) + salt) Salt is X random bytes where X can be specify but by default it is 16.</p> <p>2nd part (some kind of authorization):<br> Compare input hash (e.x. from database) with new created hash from input plain password. New salt is created from salt taken from input hash. </p> <p><strong>Code:</strong></p> <pre class="lang-py prettyprint-override"><code>import base64 import hashlib import os class Hashing(object): # base64( SHA256(password + salt) + salt) # generate new salt (default 16 bytes) def generate_new_salt(self, salt_ln=16): self.new_salt = os.urandom(salt_ln) print(f'new salt: {self.new_salt}') return self.new_salt # get salt from hash def get_old_salt(self, input_hash, salt_ln=16): self.old_salt = base64.b64decode(input_hash)[-salt_ln:] print(f'old salt: {self.old_salt}') return self.old_salt # compute hash using parameters def compute_hash(self, password, salt): self.salt = salt self.enc_password = password.encode() # hashing SHA256(password + salt) hash_object = hashlib.sha256(self.enc_password + salt) # add salt to hash and encode to base64 hash_b64 = base64.b64encode(hash_object.digest() + salt) print(f'new_hash: {hash_b64}') return hash_b64 # create hash from new or old salt def create_hash(self, password, salt_ln=16,old_salt=None): if old_salt: #if old salt then use it self.salt = old_salt else: #else generate new salt self.salt = Hashing().generate_new_salt(salt_ln) hash = Hashing().compute_hash(password, self.salt) return hash # compare input hash with created using salt get from input def compare_hashes(self, password, old_hash, salt_ln=16): self.enc_password = password.encode() #get salt from input hash self.old_salt = Hashing().get_old_salt(old_hash, salt_ln) #recreat input hash re_hash = Hashing().create_hash(password,salt_ln, self.old_salt) print(f'Compare: old_hash: {old_hash}') print(f'Compare: new_hash: {re_hash}') #compare if re_hash.decode() == old_hash.decode(): return True else: return False #code below is just for testing NewSalt = Hashing().generate_new_salt() Hash = Hashing().create_hash('pass') OldSalt = Hashing().get_old_salt(Hash) CompareHash = Hashing().compare_hashes('pass', Hash) if CompareHash: print('HASHES THE SAME') else: print('NOT THE SAME') print(CompareHash) </code></pre> <p><strong>Questions:</strong></p> <ol> <li><p>What is a real difference between these two? With and w/o <strong>self.X</strong> works</p> <pre class="lang-py prettyprint-override"><code>def generate_new_salt(self, salt_ln=16): self.new_salt = os.urandom(salt_ln) print(f'new salt: {self.new_salt}') return self.new_salt </code></pre> <pre class="lang-py prettyprint-override"><code>def generate_new_salt(self, salt_ln=16): new_salt = os.urandom(salt_ln) print(f'new salt: {new_salt}') return new_salt </code></pre></li> <li><p>I have problem with passing default value of salt length, <code>salt_ln = 16</code>. For me it does not look nice when it is replicated in every method. Is there any way to do it more global?</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T23:04:20.333", "Id": "463039", "Score": "3", "body": "Note that sha256 is not secure for passwords: https://security.stackexchange.com/questions/90064/how-secure-are-sha256-salt-hashes-for-password-storage" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T23:43:35.110", "Id": "463042", "Score": "0", "body": "@markspace this script is just exercice with OOP, not cryptography. Ps. Fixed bug in code" } ]
[ { "body": "<h1>Questions</h1>\n\n<ol>\n<li><p><code>self</code> is the instance of whatever class the method is defined on.\nIn your example the method is <code>generate_new_salt</code> which is defined on the <code>Hashing</code> class.</p>\n\n<p>When you use <code>my_hashing = Hashing()</code> you're creating an instance and binding it to the variable <code>my_hashing</code>. When you then call the method, via something like <code>my_hashing.generate_new_salt(...)</code> then <code>self</code> is the same as <code>my_hashing</code>. They both point to the same instance of <code>Hashing</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; class Foo:\n def comp(self):\n return my_foo == self\n\n\n&gt;&gt;&gt; my_foo = Foo()\n&gt;&gt;&gt; my_foo.comp()\nTrue\n</code></pre>\n\n<p>This means that <code>self.foo = ...</code> binds <code>...</code> to the instance. This allows you to then use <code>self.foo</code> to get the value, <code>...</code>, back at a later date. Without having to pass it as an argument. If you have no reason to use <code>self.foo</code> rather than just <code>foo</code>, then using <code>self.foo</code> is not a good idea.</p></li>\n<li><p>This comes from two different but linked things.</p>\n\n<ul>\n<li><p>You're trying to be <em>too helpful</em>. A lot of your code is not doing much, and is just calling other functions.</p>\n\n<p>This is a common problem when programming, and so I would recommend you follow the <a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"noreferrer\">KISS principle</a>. If you don't need the helper now, then you don't need it at all.</p></li>\n<li><p>You're not really using objects to their potential. If you wrap all of your methods in <code>staticmethod</code> decorators then nothing will change. This highlights that you're not really following OOP. And it highlights you're barely using the features <code>class</code> provides.</p></li>\n</ul></li>\n</ol>\n\n<p>Given the above points, it would be best to start over.</p>\n\n<h1>Review</h1>\n\n<ul>\n<li><p>It's normally recommended to not use <code>print</code>. There are exceptions, but in most cases you're better served either by just not having <code>print</code> or using <code>logging</code>.</p>\n\n<p>There is one exception, which is to interact with the user via the CLI. And in this case <code>Hashing</code> does not need to do that. Where you're testing needs it and so you should only have them below that comment \"code below is just for testing\".</p></li>\n<li><p>Inheriting from object, <code>Hashing(object)</code>, is redundant in Python 3.</p></li>\n<li><p>Rather than using an <code>if</code> to compare something and then <code>return</code> <code>True</code> and <code>False</code>. You can just return the comparison.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>return re_hash.decode() == old_hash.decode()\n</code></pre></li>\n<li><p>It would be best if the code below the comment \"code below is just for testing\" were in a function. This would mean that the global namespace isn't polluted with things that don't need to be there.</p></li>\n<li>It's best to use an <code>if __name__ == '__main__':</code> guard. Since you only run the main function if you're testing, this will allow you to import the code without the testing code running.</li>\n</ul>\n\n<h1>From the ground up</h1>\n\n<ol>\n<li><p>Merging both the hash and the salt into the encoding, \"base64(hash + salt)\", is a smart way to keep the hash and the salt together. However it would be clearer if you create a class that stores the hash and the salt independently.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class PasswordHash:\n def __init__(self, hash, salt):\n self.hash = hash\n self.salt = salt\n\nph = PasswordHash(b'hash', b'salt')\nprint(ph.hash) # b'hash'\nprint(ph.salt) # b'salt'\n</code></pre>\n\n<p>From here you should be able to see two things:</p>\n\n<ul>\n<li>The method <code>get_old_salt</code> is now obsolete.</li>\n<li>You no longer need to care about the salt length.</li>\n</ul></li>\n<li><p>When you first define a class, after writing the <code>__init__</code>, you should ask yourself if the class will ever be printed. If it could be printed, then you should make at least one of these dunder methods, <a href=\"https://docs.python.org/3/glossary.html#term-special-method\" rel=\"noreferrer\">double underscore method</a>.</p>\n\n<ul>\n<li><code>__repr__</code> - Instructions on how to rebuild the method.</li>\n<li><code>__str__</code> - A human friendly interpretation of the class.</li>\n</ul>\n\n<p>In this case <code>__repr__</code> could make sense, but <code>__str__</code> doesn't.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def __repr__(self):\n return f'PasswordHash({self.hash}, {self.salt})'\n</code></pre>\n\n<p>You should be able to see, <code>__repr__</code> outputs the exact text we used to make the instance.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; print(PasswordHash(b'hash', b'salt'))\nPasswordHash(b'hash', b'salt')\n</code></pre></li>\n<li><p>From here we need to think about how we should hash the password, since we don't want to store the password in plaintext. And so we can add <code>compute_hash</code> to <code>PasswordHash</code>, with 2 modifications.</p>\n\n<ul>\n<li>I prefer the name <code>hash_password</code>, as it explains what it does, and what it does it on.</li>\n<li><p>Secondly I would make it a <code>staticmethod</code>. This comes with a couple of reasons why:</p>\n\n<ol>\n<li>It allows us to create <code>PasswordHash</code> from a password easier.</li>\n<li>It allows for subclasses of <code>PasswordHash</code> to change the way the class hashes things.</li>\n</ol></li>\n</ul>\n\n<p></p>\n\n<pre><code>@staticmethod\ndef hash_password(password, salt):\n hash = hashlib.sha256(password.encode() + salt)\n return base64.b64encode(hash.digest())\n</code></pre>\n\n<p>Currently making a <code>PasswordHash</code> from a password is pretty ugly.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>ph = PasswordHash(PasswordHash.hash_password(password, salt), salt)\n</code></pre></li>\n<li><p>Since the current interface for making a <code>PasswordHash</code> from a password is not the nicest. And is the standard way to use the class, we can make a class method to make it pretty.</p>\n\n<p>The reason this is a <code>classmethod</code> and not a standard method is because we need it to run before <code>__init__</code>. It is also a <code>classmethod</code> and not a <code>staticmethod</code> as we'll be using the first argument, <code>cls</code>, to instantiate the class.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>@classmethod\ndef from_password(cls, password, salt):\n return cls(cls.hash_password(password, salt), salt)\n</code></pre>\n\n<p>Now making the <code>PasswordHash</code> from a password is really clean.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>ph = PasswordHash.from_password('pass', salt)\n</code></pre></li>\n<li><p>We're almost at the end. The last thing to do is to add the spiritual child of <code>compare_hashes</code> to the class. Which is really simple since we have <code>self.salt</code> and <code>PasswordHash.hash_password</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def compare(self, password):\n return self.hash == self.hash_password(password, self.salt)\n</code></pre></li>\n</ol>\n\n<p>Tying this all together you can get:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import base64\nimport hashlib\nimport os\n\n\ndef new_salt(length=16):\n return os.urandom(length)\n\n\nclass PasswordHash:\n def __init__(self, hash, salt):\n self.hash = hash\n self.salt = salt\n\n @classmethod\n def from_password(cls, password, salt):\n return cls(cls.hash_password(password, salt), salt)\n\n def __repr__(self):\n return f'PasswordHash({self.hash}, {self.salt})'\n\n @staticmethod\n def hash_password(password, salt):\n hash = hashlib.sha256(password.encode() + salt)\n return base64.b64encode(hash.digest())\n\n def compare(self, password):\n return self.hash == self.hash_password(password, self.salt)\n\n\ndef main():\n salt = new_salt()\n print('salt:', salt)\n hash = PasswordHash.from_password('pass', salt)\n print('PasswordHash:', hash)\n print('hash:', hash.hash)\n print('salt:', hash.salt)\n print('compare pass:', hash.compare('pass'))\n print('compare bar :', hash.compare('bar'))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>To make the comparison to be more OOP you could rename <code>compare</code> to the dunder method <code>__eq__</code>. And then you could use it via the <code>==</code> operator.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print('compare pass:', hash == 'pass')\nprint('compare bar :', hash == 'bar')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T00:27:35.953", "Id": "236320", "ParentId": "236314", "Score": "5" } } ]
{ "AcceptedAnswerId": "236320", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T21:44:48.457", "Id": "236314", "Score": "9", "Tags": [ "python", "beginner", "python-3.x", "object-oriented" ], "Title": "Object oriented python" }
236314
<p>I wanted to write my own code for md5 in javascript and learn its inner mechanics. (I know it is not trusted anymore, deprecated, ... but I'm just learning).<br> I didn't want to just copy the code that uses these like 60 repeated lines and over-complicated functions (like <a href="https://css-tricks.com/snippets/javascript/javascript-md5/" rel="nofollow noreferrer">here</a>), so I started writing my own implementation:<br> (Although I have just written <a href="https://en.wikipedia.org/wiki/MD5#Pseudocode" rel="nofollow noreferrer">this pseudocode</a> in js)</p> <pre><code>function myMD5(string){ /*bit rotation*/ var rot = function(word, shift){return word &lt;&lt; shift | word &gt;&gt;&gt; (32 - shift);}; /*unsigning also cuts to 32bit words*/ var us = function(word){return word &gt;&gt;&gt; 0;}; /*function for unsigned adding words mod 2**32*/ var add = function(wordsarr){ var res = 0; for(var wr = 0; wr &lt; wordsarr.length; wr++) res = us(res + us(wordsarr[wr])); return res; }; /*converting string to utf8encoded string to bytes to 32bit-words to 512bit padded blocks*/ var bytes = []; string = unescape(encodeURIComponent(string)); for(var char = 0; char &lt; string.length; char++) bytes[char] = string.charCodeAt(char); bytes.push(0x80); var words = []; for(var byte = 0; byte &lt; bytes.length; byte += 4) words.push(bytes[byte + 3] &lt;&lt; 24 | bytes[byte + 2] &lt;&lt; 16 | bytes[byte + 1] &lt;&lt; 8 | bytes[byte]); while(words.length % 16 != 14) words.push(0); words.push((bytes.length - 1) &lt;&lt; 3); words.push((bytes.length - 1) &gt;&gt;&gt; 29); /*initialization of the constants*/ var K = []; for(var i = 1; i &lt;= 64; i++) K.push(Math.floor(0x100000000 * Math.abs(Math.sin(i)))); var shif = [0x07, 0x0c, 0x11, 0x16, 0x07, 0x0c, 0x11, 0x16, 0x07, 0x0c, 0x11, 0x16, 0x07, 0x0c, 0x11, 0x16, 0x05, 0x09, 0x0e, 0x14, 0x05, 0x09, 0x0e, 0x14, 0x05, 0x09, 0x0e, 0x14, 0x05, 0x09, 0x0e, 0x14, 0x04, 0x0b, 0x10, 0x17, 0x04, 0x0b, 0x10, 0x17, 0x04, 0x0b, 0x10, 0x17, 0x04, 0x0b, 0x10, 0x17, 0x06, 0x0a, 0x0f, 0x15, 0x06, 0x0a, 0x0f, 0x15, 0x06, 0x0a, 0x0f, 0x15, 0x06, 0x0a, 0x0f, 0x15]; var a0 = 0x67452301, b0 = 0xefcdab89, c0 = 0x98badcfe, d0 = 0x10325476; var F, ix; var chunk; var A, B, C, D; for(var pos = 0; pos &lt; words.length; pos += 16){ /*chunk = current 512bit block*/ var chunk = words.slice(pos, pos + 16); A = a0; B = b0; C = c0; D = d0; for(var rnd = 0; rnd &lt; 64; rnd++){ /*round type*/ if(rnd &lt; 16){ F = (B &amp; C) | (~B &amp; D); ix = rnd; } else if(rnd &lt; 32){ F = (B &amp; D) | (C &amp; ~D); ix = (5 * rnd + 1) % 16; } else if(rnd &lt; 48){ F = B ^ C ^ D; ix = (3 * rnd + 5) % 16; } else{ F = C ^ (B | ~D); ix = (7 * rnd) % 16; } /*prepare for the next round, compute the temporary F*/ F = add([F, A, K[rnd], chunk[ix]]); A = D; D = C; C = B; B = add([B, rot(F, shif[rnd])]); } /*add to the current state mod 2**32*/ a0 = add([a0, A]); b0 = add([b0, B]); c0 = add([c0, C]); d0 = add([d0, D]); } /*return the state words as 16 bytes*/ return [a0 &gt;&gt;&gt; 24, a0 &gt;&gt;&gt; 16 &amp; 0xff, a0 &gt;&gt;&gt; 8 &amp; 0xff, a0 &amp; 0xff, b0 &gt;&gt;&gt; 24, b0 &gt;&gt;&gt; 16 &amp; 0xff, b0 &gt;&gt;&gt; 8 &amp; 0xff, b0 &amp; 0xff, c0 &gt;&gt;&gt; 24, c0 &gt;&gt;&gt; 16 &amp; 0xff, c0 &gt;&gt;&gt; 8 &amp; 0xff, c0 &amp; 0xff, d0 &gt;&gt;&gt; 24, d0 &gt;&gt;&gt; 16 &amp; 0xff, d0 &gt;&gt;&gt; 8 &amp; 0xff, d0 &amp; 0xff]; }; </code></pre> <p>However, It doesn't work as it should...<br> I already fixed some mistakes, but now I can't find anything wrong! Could someone help me troubleshooting?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T17:32:16.827", "Id": "463150", "Score": "0", "body": "\"it doesn't work\" is never an appropriate description for an error since it is missing all details that are needed to find the bug." } ]
[ { "body": "<pre><code>function myMD5(string){\n</code></pre>\n\n<p>MD5 itself acts on bits or - for most runtimes - bytes. All string manipulation should take place <em>outside</em> any MD5 function.</p>\n\n<pre><code>/*unsigning also works cuts to 32bit words*/\n</code></pre>\n\n<p>That's not clear to me. Two verbs in a row...</p>\n\n<pre><code>string = unescape(encodeURIComponent(string));\n</code></pre>\n\n<p>Oh dear, that throws the principle of least surprise in the blender. Do not suddenly change the string without warning the user.</p>\n\n<p>The you first copy the <em>complete</em> message to bytes, and then to words. This uses a lot of unnecessary memory. There is a reason why most implementations (well, outside of those of JavaScript) use multiple <code>update</code> method and a final <code>digest</code> method. It is to handle larger messages, or messages that are actually split over multiple locations.</p>\n\n<pre><code>for(var i = 1; i &lt;= 64; i++)\n K.push(Math.floor(0x100000000 * Math.abs(Math.sin(i))));\n</code></pre>\n\n<p>This makes the code smaller, of course, but do you really want to perform that calculation for each MD5 invocation?</p>\n\n<pre><code>var A, B, C, D;\n</code></pre>\n\n<p>When using variable names that are specific to a specification, then please provide a link to the specification. Otherwise other devs are going to wonder about the special variable names (such as <code>shif</code>).</p>\n\n<pre><code>if(rnd &lt; 16){\n</code></pre>\n\n<p>Branching is relatively slow on modern processors. This is why you see the <em>unrolled loops</em> that you've coiled up again. To get speed, you want to perform operations chunks by buffering a chunk at a time. Then you want to have the code run as fast as possible.</p>\n\n<p>Fortunately you are using <code>else if</code> which makes it ever so slightly more performant. <em>Over a few runs</em>, the branching should become predictable and a good runtime should make it run faster.</p>\n\n<p>You are returning the result as bytes, which is how it should be. Don't forget to test your code against the official test vectors, and <em>add tests for your own edge cases</em> or your MD5 may <em>still</em> result in a wrong value.</p>\n\n<p>Your code looks fine if you just want to get a feel of what MD5 - a relatively simple crypto hash - looks like. It's good practice. But now you may want to proceed and see what it takes to make it efficient - and unroll your own code yourself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T02:26:21.223", "Id": "236324", "ParentId": "236316", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T21:58:20.837", "Id": "236316", "Score": "2", "Tags": [ "javascript", "cryptography", "hashcode" ], "Title": "Custom code for MD5 in js" }
236316
<p>Well, I'm working with Selenium to scrap a webpage that has obfuscated class names (example <code>&lt;div class="example-gHJkLM"&gt;...</code>)... </p> <p>So I needed to create an extension method to get </p> <pre class="lang-cs prettyprint-override"><code>public static ReadOnlyCollection&lt;IWebElement&gt; Descendants(this IWebElement element, bool hasChildren = false, int index = -1, string postAppend = "") { var web = element.GetWebDriver(); // &lt; 1ms var xpath = element.XPath(); // 5 ms return web.FindElements(By.XPath(xpath + "//" + (hasChildren ? "child::node()" : "*") + (index &gt; -1 ? $"[{index + 1}]" : string.Empty) + postAppend)); // 64 ms } public static ReadOnlyCollection&lt;IWebElement&gt; GetNodesByContainingClass(this IWebElement element, string className, bool toLower = false, bool useFullHierarchy = false) { return new ReadOnlyCollection&lt;IWebElement&gt;(element?.Descendants() .Where(n =&gt; (toLower ? n.GetAttribute("class")?.ToLowerInvariant() : n.GetAttribute("class")) ?.Contains(className) == true).ToList()); // ???? } public static IWebElement GetNodeByContainingClass(this IWebElement node, string className) { return node?.GetNodesByContainingClass(className).FirstOrDefault(); } </code></pre> <p>Example usage:</p> <pre class="lang-cs prettyprint-override"><code> var watch = Stopwatch.StartNew(); var welcomeMessage = messageBox .GetNodesByContainingClass( "icon-", false, true)? .LastOrDefault(); watch.Stop(); Console.WriteLine($@"[Getting welcome message element] Ellapsed {watch.ElapsedMilliseconds} ms!", Color.Yellow); </code></pre> <blockquote> <ul> <li>messageBox is a <code>IWebElement</code></li> <li>I'm using Colorful.Console package</li> </ul> </blockquote> <p>And this is what I got:</p> <p><a href="https://i.stack.imgur.com/7i1iY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7i1iY.png" alt="..."></a></p> <p>4 and 9 seconds to materialize a Where LINQ clause, seriously? I debugged the <code>element?.Descendants()</code> part and this has only 727 elements...</p> <p>Can anyone guide me?</p> <p>Also, I will be so thankfully if somebody suggests me a better approach to do this. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T03:45:01.357", "Id": "463052", "Score": "0", "body": "for start, try this `return new ReadOnlyCollection<IWebElement>(element?.Descendants().Where(n => n.GetAttribute(\"class\").Equals(className, StringComparison.InvariantCultureIgnoreCase)));` check the performance, and report." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T23:02:46.737", "Id": "463197", "Score": "0", "body": "But I'm not looking for Equals comparison, I'm checking Contains." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T23:46:22.690", "Id": "236317", "Score": "1", "Tags": [ "c#", "linq", "selenium" ], "Title": "Getting all descendants IWebElements (using XPath) is too slow in Selenium" }
236317
<p>I wrote this quick (lots of googling) and dirty (I hope not too dirty) script to download a URL list with a win32 wget port and save them as files with the url as the name to use as a "poor man's url cache" for another program.</p> <p>It works (tested ~200k links), but I wonder if I did progress management right (it was a power shell feature I wanted to test with this kind of task) and if there are other things I could improve (or make more readable/reduce script length) and/or unexpected failure points.</p> <p>It is my first time using powershell like this ... please be gentle ;P</p> <pre><code>param ([Parameter(Mandatory = $true)][string]$target = 'default'); cd $PSScriptRoot; $enableProgress = $true; #if ($enableProgress){ Add-Type -AssemblyName System.Web $urlPAth = "$( pwd )\url_$target.txt"; $baseCrawlPath = "$( pwd )\crawl_data\$target"; if (![System.IO.File]::Exists($urlPath)) { Write-Error "missing list file"; exit -1 } $foo = (mkdir $baseCrawlPath 2&gt; $null); Write-Progress -Id 13431 -Activity "Load database..." -PercentComplete -1 -Status "Reading file: $urlPath" $totalLines = (gc ".\url_$target.txt" | ? { $_.Trim() -ne '' }).Count; Write-Progress -Id 13431 -Activity "Load database..." -Completed $totalCounter = 0; $retMax = 10; $interGetSeconds = 3; $skipExisting = $true; [IO.File]::ReadLines($urlPath) | Where-Object { $_.Trim() -ne '' } | ForEach-Object { $totalCounter++; #$host.ui.RawUI.WindowTitle = "$totalLines || $totalCounter" # i scrapped this because wget percentage hijacks the title if ($enableProgress) { Write-Progress -Id 1 -Activity "DOWNLOAD - ($target)" -Status "Item $totalCounter of $totalLines" -PercentComplete (($totalCounter / $totalLines) * 100); } $theUrl = $_.Trim(); $retCount = 0; $fileName = $theUrl; # I url encode invalid path characters so that the url is preserved when url-decoding all files in folder [IO.Path]::GetInvalidFileNameChars() | foreach { $fileName = $fileName.Replace([String]$_,[System.Web.HttpUtility]::UrlEncode($_)) } $filePath = "$baseCrawlPath\$fileName"; # echo $filePath; # debug $keepTrying = ($retCount -lt $retMax); # $keepTrying = $true; # debug $fExists = $false; if ($skipExisting) { $fExists = [System.IO.File]::Exists($filePath); } if ($fExists) { $errored = $false; $keepTrying = $false } while ($keepTrying) { $retCount++; $keepTrying = ($retCount -lt $retMax); $rtPct = (($retCount/$retMax)*100); if ($rtPct -gt 100) { $rtPct = -1 } $rtPct = -1 if ($enableProgress) { Write-Progress -Id 2 -ParentId 1 -Activity "WGET [$_]" -Status "Attempt $retCount of $retMax" -PercentComplete $rtPct } $wgOut = ''; # $stderrFile = New-TemporaryFile; $stdoutOutput = cmd /c ver '&amp;' dir \nosuch 2&gt;$stderrFile; $stderrOutput = Get-Content $stdErrFile; Remove-Item $stderrFile # wget.exe -N "$_"; // timestamping was my initial idea but apparently I can't use urls as filenames wget.exe "$_" -O "$filePath"; $wreq = $true; # enable wait # i failed at putting stdout and stderr in a variable... #Invoke-Expression "C:\IncludePath\wget.exe \"$_\" -O \"$filePath\"" -OutVariable wgOut -ErrorVariable wgOut #echo (-join('C:\IncludePath\wget.exe',' "',$_,'"',' -O "',$filePath,'"')); #$stderrFile = New-TemporaryFile; $stdoutOutput = Invoke-Expression (-join('C:\IncludePath\wget.exe',' "',$_,'"',' -O "',$filePath,'"')) 2&gt;$stderrFile; $stderrOutput = Get-Content $stdErrFile; Remove-Item $stderrFile $errored = ($LASTEXITCODE -ne 0); # if($errored){pause} # debug if ($errored) { #echo $stderrOutput; // initial idea was to have streams in variables to print only in case of errors. #echo $stdoutOutput; For ($iTimeCounter1 = ($interGetSeconds*$retCount + 3)*5; $iTimeCounter1 -gt 0; $iTimeCounter1--) { if ($enableProgress) { Write-Progress -Id 4 -ParentId 2 -Activity "ZEN MEDITATION ..." -Status "WGET ERROR CODE: $LASTEXITCODE" -SecondsRemaining $iTimeCounter1; } Start-Sleep 1; } if ($enableProgress) { Write-Progress -Id 4 -ParentId 2 -Activity "ZEN MEDITATION ..." -Completed } #pause # debug } else { if ($enableProgress) { Write-Progress -Id 2 -ParentId 1 -Activity "WGET [$_]" -Status "Done. Attempt n. $retCount." -PercentComplete -1 } break; } } # END WHILE if ($wreq) # delay requests { For ($iTimeCounter1 = $interGetSeconds; $iTimeCounter1 -gt 0; $iTimeCounter1--) { if ($enableProgress) { Write-Progress -Id 2 -ParentId 1 -Activity "WGET [$_]" -Status "Done. Attempt n. $retCount." -CurrentOperation "Attesa tra una richiesta e l'altra..." -SecondsRemaining $iTimeCounter1; } Start-Sleep 1; } }; if ($enableProgress) { Write-Progress -Id 2 -ParentId 1 -Activity "WGET [$_]" -Status "Done. Attempt n. $retCount." -Completed } if ($errored) { pause } # debug } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-11T08:17:31.887", "Id": "475973", "Score": "1", "body": "You can even download files without using wget even showing the progressbar `Invoke-WebRequest Url -OutFile OutputFile`" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T23:50:54.987", "Id": "236318", "Score": "4", "Tags": [ "file-system", "windows", "cache", "powershell" ], "Title": "downloading a list of urls" }
236318
<p>I was tasked with writing a python script to check if a passed ID number exists within a file. The file I was give contains roughly 25,000 unique ID numbers. An ID number is a unique 9 digit number. </p> <p>I have a couple specific things for you to comment on if you decide to review this:</p> <ol> <li><p>As it stands, I convert the <code>user_id</code> passed in the <code>id_exists</code> to a <code>str</code>. I do this because I need the ID number to be the same type when I read the ID's from the file. Is there an easier way to accomplish this?</p></li> <li><p>This is my first time using a <strong>PEP 484</strong> type hint, <code>Generator</code>. Am I using it correctly?</p></li> <li><p>This is also my first time utilizing a generator in this fashion. I used a generator here because instead of loading the entire file into memory, storing in a list, then iterating over the list, I can read each line and can exit early if an ID is found. Is it good that I'm using it in this way, or is there an easier way to do this?</p></li> <li><p>Using a helper function is a new concept to me. Am I utilizing this helper function in the most pythonic way?</p></li> </ol> <p>Of course, any constructive criticism beyond these points is welcome. Thanks in advance.</p> <pre><code>""" Ensures id number matches any within the ID file. An ID number is a unique 9 digit number. """ import random import time from typing import Union, Generator def id_exists(user_id: Union[int, str]) -&gt; bool: """ Determines if the passed ID exists within the ID file. The ID passed must be of length 9 exactly, and only contain numbers. :param Union[int, str] user_id: User ID to check for existence :return bool: True if ID exists in file, False otherwise """ # Generator[yield_type, send_type, return_type] # def get_ids() -&gt; Generator[str, None, None]: """ Helper function for `id_exists`. Yields each line in the ID file. :return Generator[str, None, None]: Lines in ID file. """ with open("ids.txt", "r") as file: for line in file: yield line.strip() # Convert user_id to &lt;class 'str'&gt; if not already # if type(user_id) == int: user_id = str(user_id) # Ensure user_id matches specifications # if len(user_id) != 9 or not user_id.isdigit(): raise ValueError("ID should be 9 characters long and all digits.") # Check ID against file and return result # return any(user_id == stored_id for stored_id in get_ids()) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T19:59:56.477", "Id": "463492", "Score": "0", "body": "Can the `user_id` have leading 0's? If it can, the using `str()` for the conversion could cause problems. An f-string f\"{user_id:0>9}\" could be used to convert the integer and pad it with leading 0's." } ]
[ { "body": "<ol>\n<li><p>One of:</p>\n\n<ul>\n<li>Only take a string or a number.</li>\n<li>Use <code>str</code> either way.</li>\n<li>Work against a bespoke class.</li>\n</ul></li>\n<li><p>Yes. But I find it better to just use <code>Iterator[str]</code>, unless you're using the coroutine aspects of it.</p></li>\n<li><p>Yeah that's fine. But:</p>\n\n<ul>\n<li>You can just use <code>in</code> rather than <code>any(...)</code>.</li>\n<li>You don't need the function <code>get_ids</code> you can just use <code>any</code>, like you are now.</li>\n</ul></li>\n</ol>\n\n\n\n<ul>\n<li>Don't use <code>type(...) == int</code>, use <code>isinstance</code>.</li>\n<li><p>Validating <code>user_id</code> should probably happen somewhere else.</p>\n\n<p>I'll make a class as an example to show this.</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>class UserId:\n __slots__ = ('id',)\n id: int\n\n def __init__(self, id: int) -&gt; None:\n if not self.valid_id(id):\n raise ValueError(\"ID should be 9 characters long and all digits.\")\n self.id = id\n\n @staticmethod\n def valid_id(id: int) -&gt; bool:\n if not isinstance(id, int):\n return False\n str_id = str(id)\n return (\n len(str_id) == 9\n and str_id.isdigit()\n )\n\n def exists(self) -&gt; bool:\n user_id = str(self.id)\n with open('ids.txt') as f:\n return any(user_id == line.strip() for line in f)\n\n\nprint(UserId(123456789).exists())\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T06:59:41.467", "Id": "463071", "Score": "0", "body": "Hmm, I wonder why did you write the `return` from `valid_id()` method like this: `return (and len(str_id) == 9 and str_id.isdigit())`? Is it just a style thing or...?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T07:01:54.770", "Id": "463072", "Score": "0", "body": "@GrajdeanuAlex. Are you talking about the first and? If so, it's not meant to be there. Forgot to remove it when I moved `isinstance` out of the check" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T07:02:54.447", "Id": "463073", "Score": "0", "body": "yep. Thought that's a hidden feature that I haven't heard about" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T07:03:34.170", "Id": "463074", "Score": "0", "body": "@GrajdeanuAlex. That would be one weird feature. But tbh, it did look nicer..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T02:14:21.987", "Id": "236323", "ParentId": "236321", "Score": "3" } } ]
{ "AcceptedAnswerId": "236323", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T00:31:08.037", "Id": "236321", "Score": "4", "Tags": [ "python", "python-3.x", "file", "generator" ], "Title": "Check existence of user identification number" }
236321
<p>I am looking for a better way to minimize nested if statements in my <code>MessageHandler.handleMessage</code> method. I am looking to adhere to SRP and a function should do one thing and one thing well!</p> <p>Any input would be greatly appreciated.</p> <pre class="lang-py prettyprint-override"><code> class MessageHandler(): """ MessageHandler - Handles twitch IRC messages and emits events based on Commands and msgid tags """ def __init__(self): self.COMMANDS: COMMANDS = COMMANDS() def handleMessage(self, IrcMessage: str)-&gt;tuple: """ MessageHandler.handleMessage - breaks down data string from irc server returns tuple (event: str, message: Message) or returns tuple of (None, None) :param IrcMessage: a irc recieved message for server :type IrcMessage: str :raises TypeError: IrcMessage needs to be of type str :return: a tuple with event string and Message data type populasted with all parsed message data :rtype: tuple """ try: if not isinstance(IrcMessage, str): raise TypeError("MessageHandler.handleMessage requires input of type str") message = self._parse(IrcMessage) # Populate message values message.channel: str = message.params[0] if len(message.params) &gt; 0 else None message.text: str = message.params[1] if len(message.params) &gt; 1 else None message.id: str = message.tags.get("msg-id") message.raw: str = IrcMessage message.username: str = message.tags.get("display-name") # Parse badges and emotes message.tags = self._badges(self._emotes(message.tags)) # Transform IRCv3 Tags message = self._TransformIRCv3Tags(message) except AttributeError: return(None, None) # Handle message with prefix "tmi.twitch.tv" if message.prefix == self.COMMANDS.TMI_TWITCH_TV: # Handle command bot Username if message.command == self.COMMANDS.USERNAME: botUsername = message.params[0] # Chatroom NOTICE check msgid tag elif message.command == self.COMMANDS.NOTICE: if message.id in self.COMMANDS.MESSAGEIDS.__dict__.values(): return (self.COMMANDS.NOTICE, message) else: if message.raw.replace(":tmi.twitch.tv NOTICE * :",'') in ("Login unsuccessful", "Login authentication failed", "Error logging in", "Invalid NICK"): return (self.COMMANDS.LOGIN_UNSUCCESSFUL, \ message.raw.replace(":tmi.twitch.tv NOTICE * :",'')) else: return (message.command, message) # Handle message with prefix jtv ??????? unsure it is still required elif message.prefix == "jtv": print(message.params)#still testing else: if message.command == self.COMMANDS.MESSAGE: message.username: str = message.prefix[:message.prefix.find("!")] return (self.COMMANDS.MESSAGE, message) elif message.command == self.COMMANDS.WHISPER: return (self.COMMANDS.WHISPER, message) elif message.command == self.COMMANDS.NAMES: return (self.COMMANDS.NAMES, message) return (None, None) # invalid message @staticmethod def _TransformIRCv3Tags(message: Message)-&gt;Message: """ MessageHandler._TransformIRCv3Tags reformats message tags :param message: message object :type message: Message :return: message with updated tags :rtype: Message """ if message.tags: for key in message.tags: if key not in ("emote-sets", "ban-duration", "bits"): if isinstance(message.tags[key], bool): message.tags[key] = None elif message.tags[key] in ('0', '1'): message.tags[key] = bool(int(message.tags[key])) return message @staticmethod def _badges(tags: dict)-&gt;dict: """ MessageHandler._badges - Parse tags['badges'] from str to dict and update tags['badges'] :param tags: tags from parsed IRC message :type event: dict :return: tags :rtype: dict """ if ("badges" in tags and isinstance(tags.get("badges"), str)): badges = tags.get("badges").split(",") tags["badges"]: dict = {} for badge in badges: key, value = badge.split("/") if value is None: return tags tags["badges"][key] = value return tags @staticmethod def _emotes(tags: dict)-&gt;dict: """ MessageHandler._emotes - Parse tags['emotes'] from str to list and update tags['emotes'] :param tags: tags from parsed IRC message :type event: dict :return: tags :rtype: dict """ if ("emotes" in tags and isinstance(tags.get("emotes"), str)): emotes: dict = {} emoticons = tags.get("emotes").split("/") for emoticon in emoticons: key, value = emoticon.split(":") if value is None: return tags emotes[key] = value.split(",") tags["emotes"] = emotes return tags @staticmethod def _parse(data: str)-&gt;Message: """ MessageHandler._parse - Parses IRC messages to Message type :param data: string from IRC server :type event: str :return: message :rtype: Message """ message = Message() if not isinstance(data, str): raise TypeError("MessageHandler._parse requires input of type str") position: int = 0 nextspace: int = 0 if len(data) &lt; 1: return None if data.startswith("@"): nextspace = data.find(" ") if nextspace == -1: return None # invalid message form tags = data[1:nextspace].split(";") for tag in tags: key, value = tag.split("=") message.tags[key] = value or True position = nextspace + 1 while data[position] == " ": position += 1 if data[position] == ":": nextspace = data.find(" ", position) if nextspace == -1: return None # invalid message form message.prefix = data[position + 1:nextspace] position = nextspace + 1 while data[position] == " ": position += 1 nextspace = data.find(" ", position) if nextspace == -1: if len(data) &gt; position: message.command = data[position:] return message return None # invalid message form message.command = data[position:nextspace] position = nextspace + 1 while data[position] == " ": position += 1 dataLen = len(data) while position &lt; dataLen: nextspace = data.find(" ", position) if data[position] == ":": message.params.append(data[position + 1:]) break if nextspace != -1: message.params.append(data[position:nextspace]) position = nextspace + 1 while data[position] == " ": position += 1 continue if nextspace == -1: message.params.append(data[position:]) break return message </code></pre>
[]
[ { "body": "<p>I don't know how are twitch messages formes, but here is just a quick thought after a first look at your code: regex might be helpful, especially for _parse method. It seems that there are known delimiters.\nYou will be able to capture all relevant data in a single match, and for example drop all of your space skipping loops.</p>\n\n<p>You might want to take your _parse method outside of your handler class, and create a specific MessageParser class. Parsing the raw message is different from handling parsed message.</p>\n\n<p>In the handleMessage method, there's no return for the case of a \"tmi.twitch.tv\" when message.command == self.COMMANDS.USERNAME, so it ends up to return(None, None). Is it wanted? All other cases return something.</p>\n\n<p>Concerning the nested if, by now I don't see a lot of options...\nHowever, you can use intermediate variables to have only one exit point, instead of all the returns. This will greatly help debugging by having, for example, only one breakpoint.</p>\n\n<p>My 2 cents.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T02:07:45.117", "Id": "463405", "Score": "0", "body": "twitch messages use IRC formats, and I do like the idea of a single return statement and will have to edit that section. the username is just who you logged in as so no event necessary. Having the `_parse` method in the same module as `messageHandler` my thought was they would need to change at the same time which makes them bound together. i will also try out the regex method too ,thanks for you input" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T17:34:56.677", "Id": "236427", "ParentId": "236326", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T03:29:25.007", "Id": "236326", "Score": "3", "Tags": [ "python", "parsing" ], "Title": "Extracting event strings and message objects from Twitch IRC messages" }
236326
<p>I am working on a simple personal project to build a Hoffman Tree. In my constructor, shown below, I am reading in a file, creating HoffmanNodes that represent each char in the file then I got through the file to encode it. I need to create a Scanner to go through the file once to find all the chars and their frequency, then I recreate the scanner of the same file and go through it again to encode it. </p> <p>I have tried to do some research to find a more efficient way to do this, and I am coming up short. Is there an easier way to do this?</p> <pre><code>public HoffmanCoding(File inFile) { Scanner in = createScanner(inFile); //Check empty file if (in.hasNextLine() == false) { throw new IllegalArgumentException("Can not encode an empty file"); } //Create a HashMap that holds all the HoffmanNodes in the HoffmanTree nodeHashMap = buildNodeHashMap(in); //Use the HashMap to create a Priority Que that I then can use to make the tree PriorityQueue&lt;HoffmanTreeNode&gt; allNodes = new PriorityQueue&lt;&gt;(nodeHashMap.values()); //Build the HoffmanTree this.rootOfHoffmanTree = buildHoffmanTree(allNodes); //Assign a code to all the nodes based on their position in the tree. assignCode(this.rootOfHoffmanTree, ""); // Recreate scanner reset it to the begging of the file in = createScanner(inFile); //Encode and Decode the message. this.encodedMessage = encodeMessage(in); in.close(); this.decodedMessage = decodeMessage(this.encodedMessage); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T10:24:52.660", "Id": "463287", "Score": "0", "body": "Huffman, not Hoffman? https://en.wikipedia.org/wiki/Huffman_coding" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T22:06:55.410", "Id": "463386", "Score": "1", "body": "@forsvarir Ya i fixed that in my final version on my github but I didn't notice before I posted this. Thanks!" } ]
[ { "body": "<p>I'd be very skeptical about making any changes to the current code you have when it comes to creating the scanners. However, I do want to indicate that reopening a file while it is still open is probably not a good idea. So I'd use a <strong>try-with-resources</strong> when you create the <code>Scanner</code> instances. I don't think reopening a file is so resource intensive that it needs to be avoided.</p>\n\n<p>However, file access is commonly performed using a file pointer, and that file pointer can be reset. The question is then how to make a <code>FileInputStream</code> aware of that. This can be done by asking for the file channel (introduced with Java NIO2) and then setting the position on that.</p>\n\n<p>So if we read the <a href=\"https://docs.oracle.com/javase/7/docs/api/java/io/FileInputStream.html#getChannel()\" rel=\"noreferrer\">documentation of <code>FileInputStream#getChannel()</code></a> we get:</p>\n\n<blockquote>\n <p>Reading bytes from this stream will increment the channel's position. Changing the channel's position, either explicitly or by reading, will change this stream's file position.</p>\n</blockquote>\n\n<p>Ah! Right what we are after, so here is code that leaves the file open:</p>\n\n<pre><code>try (FileInputStream fis = new FileInputStream(inFile)) {\n Scanner scanner1 = new Scanner(fis);\n System.out.println(scanner1.nextLine());\n\n fis.getChannel().position(0L);\n\n Scanner scanner2 = new Scanner(fis);\n // prints the same line!\n System.out.println(scanner2.nextLine());\n\n // the underlying file stream will be closed anyway, but yeah...\n scanner2.close();\n scanner1.close();\n}\n</code></pre>\n\n<p>Reusing a scanner itself doesn't work. The reason is that <code>Scanner</code> instances cache data, which means that that data is not present anymore in any underlying stream. This is why no such functionality is supplied. <code>Scanner</code> is not a very heavy-weight component to instantiate, so I guess that's all right.</p>\n\n<p>The above code is pretty ugly because how Java handles <code>close()</code>. Any call to <code>Scanner.close()</code> - implicit or explicit - will also close the underlying <code>FileInputStream</code>. That's of course not very useful in this scenario.</p>\n\n<p>An ugly hack is to create a <code>FilterInputStream</code>-based decorator that simply forwards everything and then simply doesn't call <code>close</code> on the underlying stream. That way you can close the scanners without closing the underlying <code>FileInputStream</code>. But yeah, just as yucky as above code.</p>\n\n<p>The fact that it is possible to re-read the file without re-opening it is not sufficient reason to use tricks like above. If you close the file then the file handle is released and when reopening the file is probably still cached.</p>\n\n<hr>\n\n<p>I don't know enough about your application to know if rewriting your code to use Java NIO directly makes sense. <code>Scanner</code> was added to Java to make it easy to parse simple input, it was not meant to parse complex files, as the first line of documentation shows:</p>\n\n<blockquote>\n <p>A simple text scanner which can parse primitive types and strings using regular expressions.</p>\n</blockquote>\n\n<hr>\n\n<p>Your code looks OK-ish. I'm very worried about the number and use of fields though. Generally a lot of fields is a red flag when it comes to class design. The fact that all the processing is performed in the constructor is not a good sign either. The separate part of encoding should take place in a separate method, which would make above solution even harder to apply.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T04:48:29.567", "Id": "236332", "ParentId": "236327", "Score": "5" } }, { "body": "<p>I'm omitting the lines from your method not directly involved with creation of Scanner:</p>\n\n<blockquote>\n<pre><code>Scanner in = createScanner(inFile);\n//Check empty file\nif (in.hasNextLine() == false) {\n throw new IllegalArgumentException(\"Can not encode an empty file\");\n}\n//...other lines not involved with scanners \nin = createScanner(inFile); &lt;-- assignment of second scanner, first not closed\nin.close();\n</code></pre>\n</blockquote>\n\n<p>The first Scanner resource is not closed both in the case of empty file (exception cause the exit from the method) and when you reassign a new Scanner to the variable containing the old Scanner instance, so you have a <strong>resource leak</strong>.</p>\n\n<p>Personally I would separate the control of empty file from creation of a Scanner instance: a possible solution for it using the File.<a href=\"https://docs.oracle.com/javase/7/docs/api/java/io/File.html#length()\" rel=\"nofollow noreferrer\">empty</a> method (lot of debates about possible solutions how to check if one file is empty, check which is the best method for you)</p>\n\n<pre><code>public HoffmanEncoding(File inFile) throws FileNotFoundException {\n if (inFile.length() == 0L) {\n throw new IllegalArgumentException(\"Can not encode an empty file\");\n }\n // other lines of the method\n}\n</code></pre>\n\n<p>After, I would put the <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try with resources</a> construct inside your methods <code>encodeMessage</code> and <code>buildNodeHashMap</code> to ensure the automatic closing of scanners like the code below:</p>\n\n<pre><code>public class HoffmanEncoding {\n\n public HoffmanEncoding(File inFile) throws FileNotFoundException {\n if (inFile.length() == 0L) {\n throw new IllegalArgumentException(\"Can not encode an empty file\");\n }\n //omitting all lines in the method not involved with scanners\n nodeHashMap = buildNodeHashMap(inFile);\n encodedMessage = encodeMessage(inFile);\n }\n\n private String encodeMessage(File inFile) throws FileNotFoundException {\n StringBuilder encodedMessage = new StringBuilder();\n try (Scanner sc = new Scanner(inFile)) {\n //operations to construct the message\n }\n return encodedMessage.toString();\n }\n\n private Map buildNodeHashMap(File inFile) throws FileNotFoundException {\n Map nodeHashMap; //initialize it \n try (Scanner sc = new Scanner(inFile)) {\n //operations to populate the map\n }\n return nodeHashMap;\n }\n}\n</code></pre>\n\n<p>Note : better to add <code>static</code> to the two methods to avoid calls to instance methods inside the constructor.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:21:39.850", "Id": "236352", "ParentId": "236327", "Score": "2" } } ]
{ "AcceptedAnswerId": "236332", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T03:39:03.783", "Id": "236327", "Score": "4", "Tags": [ "java" ], "Title": "More efficient way than creating scanner of .txt file twice" }
236327
<p>I'm attempting to speed up some python code that is supposed to automatically pick the minimum samples argument in <a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html" rel="nofollow noreferrer">DBSCAN</a>. Currently the execution time grows exponentially as the number of training samples increases:</p> <ul> <li>0.128999948502 seconds for 100 training examples </li> <li>0.281999826431 seconds for 1000 training examples</li> <li>11.5310001373 seconds for 10000 training examples</li> </ul> <blockquote> <p><code>min_samples</code> is the number of samples (or total weight) in a neighborhood for a point to be considered as a core point. This includes the point itself.</p> </blockquote> <p>Can anyone make some suggestions for how to speed up the code?</p> <p>As a bonus, adding the <a href="https://github.com/scikit-learn/scikit-learn/issues/16299" rel="nofollow noreferrer"><code>n_jobs</code></a> argument to DBSCAN doesn't seem to affect the execution time of DBSCAN.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from sklearn.metrics.pairwise import euclidean_distances from time import time def autoselect_minsamps_orig(D_sym,eps,K,kmedian_thresh): min_samps = 10 kmedian_dist_prev = 0 for k in range(2,K): k_avg = [] # For each row, compute median distance to k nearest neighbors for row in D_sym: flat_row = np.squeeze(np.asarray(row)) row_nonzero = flat_row[np.flatnonzero(flat_row)] # Some nodes aren't connected to anything if len(row_nonzero) == 0: continue sorted_row = np.sort(row_nonzero) sorted_row_t = sorted_row[0:k] k_avg.append(np.median(sorted_row_t)) kmedian_dist = np.median(k_avg) kmedian_delta = abs(kmedian_dist - kmedian_dist_prev) if kmedian_delta &lt;= kmedian_thresh: min_samps=k break kmedian_dist_prev = kmedian_dist return min_samps num_training_examples = 100 num_features = 10 X = np.random.randint(5, size=(num_training_examples, num_features)) # generate a symmetric distance matrix D = euclidean_distances(X,X) eps = 0.25 kmedian_thresh = 0.005 K = num_training_examples start = time() result = autoselect_minsamps_orig(D,eps,K,kmedian_thresh) end = time() total_time = end - start print('autoselect_minsamps took {} seconds for {} training examples'.format(total_time,num_training_examples)) num_training_examples = 1000 num_features = 10 X = np.random.randint(5, size=(num_training_examples, num_features)) # generate a symmetric distance matrix D = euclidean_distances(X,X) eps = 0.25 kmedian_thresh = 0.005 K = num_training_examples start = time() result = autoselect_minsamps_orig(D,eps,K,kmedian_thresh) end = time() total_time = end - start print('autoselect_minsamps took {} seconds for {} training examples'.format(total_time,num_training_examples)) num_training_examples = 10000 num_features = 10 X = np.random.randint(5, size=(num_training_examples, num_features)) # generate a symmetric distance matrix D = euclidean_distances(X,X) eps = 0.25 kmedian_thresh = 0.005 K = num_training_examples start = time() min_samples = autoselect_minsamps_orig(D,eps,K,kmedian_thresh) end = time() total_time = end - start print('autoselect_minsamps took {} seconds for {} training examples'.format(total_time,num_training_examples)) # min_samples is used here db = DBSCAN(eps=eps, min_samples = min_samples, metric='precomputed', n_jobs=-1).fit(D) </code></pre>
[]
[ { "body": "<p>Since the elements in each row grows, sorting the row only to take the <code>k</code> smallest is a bit wasteful. Using <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.partition.html\" rel=\"nofollow noreferrer\"><code>numpy.partition</code></a> should always be faster:</p>\n\n<pre><code>sorted_row_t = np.partition(row_nonzero, k)[:k]\n</code></pre>\n\n<p>This is not needed with the examples you give, the row is already an array and flattened:</p>\n\n<pre><code>flat_row = np.squeeze(np.asarray(row))\n</code></pre>\n\n<p>Similarly, you can just use <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html\" rel=\"nofollow noreferrer\"><code>numpy.nonzero</code></a>, no need to flatten the flattened row again:</p>\n\n<pre><code>row_nonzero = flat_row[np.nonzero(frow)]\n</code></pre>\n\n<hr>\n\n<p>However, this whole <code>for</code> loop can be done entirely in <code>numpy</code>:</p>\n\n<ol>\n<li><p>First, mask all zeros by setting them to <code>numpy.nan</code>:</p>\n\n<pre><code>D = np.where(D == 0, np.nan, D)\n</code></pre></li>\n<li><p>Get the <code>k</code> smallest elements of each row. Since <code>numpy.nan</code> is not smaller than any number it will only appear at the beginning if (almost) the whole row was zeros:</p>\n\n<pre><code>k_smallest = np.partition(D, k, axis=1)[:, :k]\n</code></pre></li>\n<li><p>Compute the median of each row, and then the median of the median, ignoring <code>numpy.nan</code> values using <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.nanmedian.html\" rel=\"nofollow noreferrer\"><code>numpy.nanmedian</code></a>:</p>\n\n<pre><code>kmedian_dist = np.nanmedian(np.nanmedian(k_smallest, axis=1))\n</code></pre></li>\n</ol>\n\n<p>The first two steps can even be pulled outside of the <code>for k in ...</code> loop, which will save some more time. In that case we have to sort the whole array, though, because <code>numpy.partition</code> does not guarantee that the values are sorted, only that the <code>k</code> smallest values are in the slice up to <code>k</code>. Since <code>K</code> seems to be <code>max(D_sym.shape)</code> in all cases anyway, this should not make such a big difference. It will if the <code>k</code> at which the <code>for</code> loops stops is small enough, though, so you will have to test this.</p>\n\n<p>There's no need to <code>break</code> and then immediately <code>return</code> afterwards, just <code>return</code> directly.</p>\n\n<p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends using 4 spaces as indentation (not 3) and spaces after commas.</p>\n\n<hr>\n\n<p>In summary, this should do the same as your code:</p>\n\n<pre><code>def autoselect_minsamps_graipher(D_sym, eps, K, kmedian_thresh):\n D = np.sort(np.where(D_sym == 0, np.nan, D_sym), axis=1)\n kmedian_dist_prev = 0\n for k in range(2, K):\n kmedian_dist = np.nanmedian(np.nanmedian(D[:,:k], axis=1))\n if abs(kmedian_dist - kmedian_dist_prev) &lt;= kmedian_thresh:\n return k\n kmedian_dist_prev = kmedian_dist\n return 10 # fall back value\n</code></pre>\n\n<p>This is faster than your implementation, but suffers from similar scaling behaviour:</p>\n\n<pre><code>n autoselect_minsamps_orig autoselect_minsamps_graipher\n100 0.028 s 0.0088 s\n1000 0.32 s 0.064 s\n10000 9.5 s 3.6 s\n</code></pre>\n\n<hr>\n\n<p>You could also make timing your code easier by using a decorator:</p>\n\n<pre><code>from time import perf_counter\n\nclass Timer:\n def __init__(self, name=\"\"):\n self.name = \"\"\n self.start = None\n\n def __enter__(self):\n self.start = perf_counter()\n\n def __exit__(self, *args, **kwargs):\n delta = perf_counter() - self.start\n print(f\"{self.name} finished in {delta:.2f} seconds\")\n</code></pre>\n\n<p>Or, if you are stuck on Python 2:</p>\n\n<pre><code>from time import time\n\nclass Timer:\n def __init__(self, name=\"\"):\n self.name = \"\"\n self.start = None\n\n def __enter__(self):\n self.start = time()\n\n def __exit__(self, *args, **kwargs):\n delta = time() - self.start\n print \"{} finished in {:.2f} seconds\".format(self.name, delta)\n</code></pre>\n\n<p>Which you can use like this:</p>\n\n<pre><code>D = euclidean_distances(X,X)\neps = 0.25\nkmedian_thresh = 0.005\nK = num_training_examples\n\nwith Timer(f\"autoselect_minsamps_orig, K = {K}\"):\n min_samples = autoselect_minsamps_orig(D, eps, K, kmedian_thresh)\n</code></pre>\n\n<p>Note that I used <a href=\"https://docs.python.org/3/library/time.html#time.perf_counter\" rel=\"nofollow noreferrer\"><code>time.perf_counter</code></a>, which is better suited for timing, but which is Python 3 only.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T17:24:49.327", "Id": "465602", "Score": "0", "body": "I'm having trouble importing `perf_counter` from `time`...is it a Python 3 feature? I'm stuck with 2.7..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T17:26:44.823", "Id": "465603", "Score": "1", "body": "@random_dsp_guy It is. You can use `time.time()` instead. In that case, you should also do `print \"...\".format(...)` wherever I did `print(f\"...\"}`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T17:33:21.627", "Id": "465605", "Score": "0", "body": "Could you post a Python 2.7 compatible solution? I'm having trouble getting the arguments `Timer` to work (`AttributeError: Timer instance has no attribute 'name'`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T18:07:47.943", "Id": "465609", "Score": "1", "body": "@random_dsp_guy That is actually a typo Independent of the Python version, fixed. I'll see if I have some time later to do a Python 2 version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T18:12:18.877", "Id": "465610", "Score": "1", "body": "@random_dsp_guy Ok, I quickly did it for the class, you will have to adapt the calling code yourself (though it is just the name string). Code is untested, so let me know if there are further typos hidden ;-) In the future, if you are asking a question and are still stuck on Python 2, we have the tag [tag:python-2.x], which you can add in addition to the normal Python tag." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:40:58.533", "Id": "236353", "ParentId": "236329", "Score": "2" } } ]
{ "AcceptedAnswerId": "236353", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T04:06:09.963", "Id": "236329", "Score": "3", "Tags": [ "python", "performance", "python-2.x", "machine-learning" ], "Title": "Estimation of min_samples for DBSCAN" }
236329
<p>I know that multiple functions are already available. However, I thought of writing my own because I wanted to learn the logic (and also because I thought there wasn't enough confusion :P). Please review the function I wrote and suggest me efficient changes.</p> <p>Without further ado, here I go:</p> <pre><code>scan(string,size) char** string; size_t size; { string[0]=(char*)malloc(sizeof(char)); char keystroke=' '; while((keystroke=getc(stdin))!='\n') { string[0][size++]=keystroke; string[0]=(char*)realloc(string[0],size+1); } string[0][size]='\0'; return size; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T08:12:07.990", "Id": "463079", "Score": "2", "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>Your code is horrible:</p>\n\n<ul>\n<li>You don't check for end-of-file, which will lead to endless loops</li>\n<li>You don't check for failure of <code>malloc</code> or <code>realloc</code></li>\n<li>You call <code>realloc</code> way too often, which makes the code slow for large lines of input</li>\n<li>You cast the result of <code>malloc</code></li>\n<li>You use the outdated style of function definition from the 1980s</li>\n<li>The variable <code>string</code> is not a string but points to an array of pointers to strings, which is confusing</li>\n<li>The <code>#include</code> for <code>size_t</code> is missing</li>\n<li>Using <code>[0]</code> instead of <code>*</code> is extremely confusing</li>\n<li>There is no need to initialize <code>keystroke</code> to a space character</li>\n<li>The parameter <code>size</code> is useless since the only possible value that makes sense for it is 0</li>\n<li>The return type of the function is implicitly <code>int</code>, which is obsolete</li>\n<li>The returned value is of type <code>size_t</code>, which doesn't fit into an <code>int</code> and additionally differs in signedness</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T08:00:01.363", "Id": "463077", "Score": "0", "body": "Firstly, why would I check for EOF?? That being said, size_t defaults to unsigned long int in my system, (It seems, there was an error copying the code which I will fix immediately; thanks for pointing that out). Oh, yeah, and also I will add malloc and realloc failures (wonder how I forgot that??). Thanks :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T08:06:25.170", "Id": "463078", "Score": "0", "body": "Anyways, I edited the function to incorporate your suggestions 2,4,6,7,12." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T13:47:34.433", "Id": "463106", "Score": "1", "body": "@d4rk4ng31 \"why would I check for EOF?\" --> to know when `stdin` has no more data to provide." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T13:50:48.880", "Id": "463107", "Score": "0", "body": "Well, that work is accomplished by '\\n', isn't it? I mean, have I got the concept wrong?? Like, for e.g., I type in `3 4 t 5 6` and press enter, the array shows the required characters. Whatever the size of the input, it works. Do try it and tell me. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T13:51:39.503", "Id": "463108", "Score": "0", "body": "Here's the link --> https://github.com/kesarling/SL-V/blob/master/assignment2/main.c" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T13:52:10.060", "Id": "463109", "Score": "3", "body": "@d4rk4ng31 what if the input ends before you can read a '\\n'?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T13:52:56.160", "Id": "463110", "Score": "0", "body": "The input is being given by stdin, i.e. the terminal. \\n denotes the end of the input; that's what." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T13:53:43.063", "Id": "463111", "Score": "3", "body": "@d4rk4ng31, When `stdin` is _closed_, `getc(stdin)` returns `EOF` - that is the true end of input. Your code, instead of stopping, goes into an infinite loop. `'\\n'` is only the end of a _line_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T13:54:19.217", "Id": "463112", "Score": "0", "body": "Oh!! you mean to say like, if someone uses freopen to point stdin to a file? Well, umm..in that case, my code will wait" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T13:57:15.863", "Id": "463113", "Score": "0", "body": "But, in any other case, won't EOF be returned after user presses enter? In that case, it will have already broken the loop" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T13:57:30.817", "Id": "463114", "Score": "2", "body": "@d4rk4ng31 It does not wait, it loops, consuming memory until an allocation failed and then UB of attempting to de-reference a `NULL`. Loop should quit on either `'\\n'` and `NULL`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T13:58:42.483", "Id": "463117", "Score": "1", "body": "@d4rk4ng31 Because you have not tested it in enough different cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T13:58:53.770", "Id": "463118", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/103846/discussion-between-chux-reinstate-monica-and-d4rk4ng31)." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T07:19:43.030", "Id": "236336", "ParentId": "236334", "Score": "4" } }, { "body": "<p>Code does not handle end-of-file or rare input error well as there is no attempt to detect <code>EOF</code>.</p>\n\n<p>Perhaps something like</p>\n\n<pre><code>// char keystroke=' ';\nint keystroke=' ';\nwhile((keystroke=getc(stdin))!='\\n' &amp;&amp; keystroke!= EOF) {\n string[0][size++]=keystroke;\n string[0]=(char*)realloc(string[0],size+1);\n}\nif (keystroke == EOF &amp;&amp; size == 0) {\n free(string[0]);\n string[0] = NULL;\n return -1; // Maybe use (size_t)-1 to indicate EOF.\n}\n</code></pre>\n\n<p>Fuller <a href=\"https://codereview.stackexchange.com/q/179201/29485\">example code</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:59:35.440", "Id": "463132", "Score": "0", "body": "any particular reason to use `int keystroke` over `char keystroke` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T15:20:53.483", "Id": "463139", "Score": "2", "body": "@d4rk4ng31 `int getc(stdin)` returns type `int` and typically 257 different values. To save in `char` loses information. Using `char`, cannot distinguish `EOF` from a valid character." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:54:30.930", "Id": "236355", "ParentId": "236334", "Score": "2" } } ]
{ "AcceptedAnswerId": "236336", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T05:52:18.073", "Id": "236334", "Score": "1", "Tags": [ "c", "strings", "functional-programming", "dynamic-programming" ], "Title": "A function to scan user input as string" }
236334
<p>In node.js I have been trying to find a way to pass client context from the Express routes into the services without every service function to have a <code>context</code>. By context I mean an object with user type, ID, possible queries passed on the request, etc. </p> <p>I see four possible ways to do this, <strong>keep</strong> the context as argument of services (already more or less how it is done), <strong>refactor all</strong> services to only receive the exact data they need (a lot of work and have to take into account that other services might be getting called passing the context), <strong>instantiate</strong> services with the context (I already pass mongoose model on initializing services, seemed weird to always create new instances) or what I am trying to do, <strong>implicitly pass</strong> the context object between services with a Service base class like:</p> <pre><code>class Service { call(service, context = null) { service._context = context || this._context; return service; } callWith(context) { this._context = context || this._context; return this; } } class FooService extends Service { constructor(model) { this.model = model; } async foo(bar) { // Calls other service and passes the context object to it bar.test = await this.call(barService).test(bar); return await this.model.foo(bar); } } // Somewhere else, defining my Express routes: app.route(`foo/`).get(async (req, res, next) =&gt; { try { const limit = parseInt(req.query.limit, 10); const data = await fooService.callWith(req.context) .foo({ prop: req.query.property, limit: !isNaN(limit) ? limit : null }); res.send(data); } catch (err) { next(err); } }); </code></pre> <p>If there is a nicer clean way to do this would be great to know. Also I am worried that as services are singleton instances somehow it can run asynchronous code while using the wrong context. I know node is single-threaded, but the context property is not <em>async</em> while the methods are and context can change while still resolving a promise on another service. </p> <p>Any ideas are welcome, thanks. (Originally posted on <a href="https://stackoverflow.com/q/59928469/5374327">Stackoverflow</a>)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T10:56:33.807", "Id": "463095", "Score": "1", "body": "Refactor to use only what Is needed! Thats how it should be done. It May be a lot of work but only becase you made it wrong in the beginning. And it Will teach you a lesson to Write it properly next time right Away." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T12:30:33.097", "Id": "463103", "Score": "0", "body": "@slepic I know, but this is just one of the refactorings that need to be done in an existing application. I just fear that too big of a change will be dismissed easily" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T05:38:39.553", "Id": "463260", "Score": "0", "body": "Than keep it the way it is. If the services live longer than the context, they cannot have it as property just as you described. And the base services class Is a total nonsense. That Will just further deepen the problém And complicate all services." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T00:08:22.047", "Id": "463664", "Score": "0", "body": "Can you just elaborate a bit more of what your services do and what \"context\" really is in this case? I assume context is some form of DB connector and your services are just facilitating commands between Express and the DB?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-04T14:46:28.777", "Id": "463871", "Score": "0", "body": "@James The \"context\" is really just a data structure passed through httpContext with some helpers added, so something more or less like this: `{ userId: 'id', roles: [...], isAdmin: false, query: { problem: true } }`. The problem is that some logic depends on \"userId\", flags like \"isAdmin\", \"roles\" and extra properties like \"query\". I think the best way to improve this is to just break down the services into more specific methods, so that they are not a long string of possible cases, and the route handles which service method to call with only the `context.query` parameter (for example)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T08:36:32.780", "Id": "236339", "Score": "0", "Tags": [ "javascript", "design-patterns", "node.js" ], "Title": "Implicitly passing client context to services in Node.js" }
236339
<p>What would be the "correct" way of transforming an array of objects into an object that contains an array?</p> <p>Suppose I have this array that contains objects:</p> <pre><code>const paintings = [ { painting: "Mona Lisa" }, { painting: "The Starry Night" }, { painting: "The Last Supper" }, { painting: "Girl with a Pearl Earring" }, { painting: "American Gothic" }, { painting: "The Night Watch" } ]; </code></pre> <p>And I would like to transform it into this:</p> <pre><code>const paintings = { artworks: [ "Mona Lisa", "The Starry Night", "The Last Supper", "Girl with a Pearl Earring", "American Gothic", "The Night Watch" ] }; </code></pre> <p>I know that I can accomplish this with two nested loops like below, but is there a more "elegant" way of doing it? I think that these tasks are nowadays usually solved using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="nofollow noreferrer">map</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce" rel="nofollow noreferrer">reduce</a> functions but I find them a bit confusing to use. I would like to learn though!</p> <pre><code>const paintingsNew = { artworks: [] }; for (const painting of paintings) { for (const val of Object.values(painting).values()) { paintingsNew.artworks.push(val); } } console.log(paintingsNew); // { artworks: // [ 'Mona Lisa', // 'The Starry Night', // 'The Last Supper', // 'Girl with a Pearl Earring', // 'American Gothic', // 'The Night Watch' ] } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T11:13:46.753", "Id": "463096", "Score": "0", "body": "`artworks` maps every `{painting:\"MonaLisa\", artist: ...}` to its `painting`. In Computer Science a _projection_." } ]
[ { "body": "<p>Your code flattens the entire array of {} objects, indiscriminately flattening all properties. It does not mind, if there is only one single property, but it does not make <em>sense</em> semantically, especially if the array is named <code>paintings</code>.</p>\n\n<p>Rather consider the resulting array a projection/mapping to a single property <code>painting</code>.</p>\n\n<p>For a consistent array check and take only the <code>painting</code> property.</p>\n\n<pre><code>for (const p of paintings) {\n if (\"painting\" in p) {\n paintingsNew.artworks.push(p.painting);\n }\n}\n</code></pre>\n\n<p>The extra <code>if</code> protects against <code>undefined</code> entering corrupted data.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T11:32:22.180", "Id": "236344", "ParentId": "236343", "Score": "5" } }, { "body": "<p>If you want to use <code>Array.prototype.map</code> you can write something like this:</p>\n\n<pre><code>const paintings = [\n { painting: \"Mona Lisa\" },\n { painting: \"The Starry Night\" },\n { painting: \"The Last Supper\" },\n { painting: \"Girl with a Pearl Earring\" },\n { painting: \"American Gothic\" },\n { painting: \"The Night Watch\" }\n];\n\nconst paintingsNew = {\n artworks: []\n};\n\npaintings.map(x =&gt; {\n paintingsNew.artworks.push(x);\n});\n</code></pre>\n\n<p>When you use <code>map</code> it practically iterates over every item of the array. We have to pass a callback function accepting the <code>currentValue</code> (here the <code>x</code> argument), and optionally the <code>index</code> and the <code>array</code>.</p>\n\n<p>You can (and normally should) return some calculated value in the callback function. Since here everything you want is to create a new object containing the array, you push each item to the array inside the object <code>paintingsNew</code>. You don't even need <code>map</code> for this, you can just write:</p>\n\n<pre><code>const paintingsNew = {\n artworks: paintings // paintings is defined before\n};\n</code></pre>\n\n<p>However I suppose you'd have some further requirements, which you could work out inside the callback function of the <code>map</code>. As suggested by @Joop Eggen, you could check if the key <code>painting</code> is present in the object:</p>\n\n<pre><code>paintings.map(x =&gt; {\n if ('painting' in x) {\n paintingsNew.artworks.push(x);\n }\n});\n</code></pre>\n\n<p>Now this would make more sense when using <code>map</code>. You could certainly apply some more advanced logic if your initial array is more diverse and you'd like to create an output object with more complex structure.</p>\n\n<p>EDIT: Immediatelly after posting I saw you want to get only the value for the key <code>painting</code>. This means in the <code>map</code> callback you push <code>x.painting</code> instead of just <code>x</code>.</p>\n\n<pre><code>paintings.map(x =&gt; {\n if ('painting' in x) {\n paintingsNew.artworks.push(x.painting);\n }\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:41:05.427", "Id": "463126", "Score": "6", "body": "You are misusing `map`. It is for creating a new array like this: `const newPaintings = paintings.map(x => x.painting)`, not to execute side-effects. You should be using `.forEach()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:43:57.707", "Id": "463128", "Score": "1", "body": "@RoToRa thank you for the comment. You're right, `.forEach()` is more appropriate for this. I used `.map()` because the OP stated in the question he/she wanted to use `map` or `reduce`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-28T20:04:06.053", "Id": "467038", "Score": "0", "body": "if you [edit] your answer to not suggest calling `.push()` inside the callback to `.map()` then I would consider changing my vote..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T11:54:23.250", "Id": "236345", "ParentId": "236343", "Score": "0" } } ]
{ "AcceptedAnswerId": "236344", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T10:32:05.717", "Id": "236343", "Score": "3", "Tags": [ "javascript", "beginner", "array", "json" ], "Title": "Array of objects to array" }
236343
<p>First I fetch an instance from the database. The three functions <code>getSwitches</code>, <code>getSingle</code> and <code>getLinears</code> need the return value instance. When all requests are finished I want to fill the array <code>barFrequencyData</code> with the data. </p> <p>How do I correctly refactor the code? Should I use <code>async/await</code> or promises in this case?</p> <pre><code>barFrequencyData.datasets[0].data.length = 0; barFrequencyData.labels.length = 0; let barFrequencyFill = [{ label: null, value: 0, }]; let myUser = jwt_decode(localStorage.usertoken); let myInstance = 0; getInstance(myUser) .then(instance =&gt; { myInstance = instance.data; getSwitches(myInstance) .then(res =&gt; { for (let i = 0; i &lt; res.data.length; i++) { barFrequencyFill.push({ label: res.data[i].name, value: res.data[i].counterAmount }); } }) .catch(err =&gt; { return err; }); getSingle(myInstance) .then(res =&gt; { for (let i = 0; i &lt; res.data.length; i++) { barFrequencyFill.push({ label: res.data[i].label, value: res.data[i].value }); } }) .catch(err =&gt; { return err; }); getLinears(myInstance) .then(res =&gt; { for (let i = 0; i &lt; res.data.length; i++) { barFrequencyFill.push({ label: res.data[i].name, value: res.data[i].distance, }) } }) .catch(err =&gt; { return err; }); return barFrequencyFill; }) .then(barFrequencyFill =&gt; { for (let i = 0; i &lt; barFrequencyFill.length; i++) { barFrequencyData.datasets[0].data.push(barFrequencyFill[i].value); barFrequencyData.labels.push(barFrequencyFill[i].label) } }) .catch(err =&gt; { return err; }); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T16:14:29.737", "Id": "463333", "Score": "0", "body": "Welcome to Code Review! Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T12:46:14.587", "Id": "236346", "Score": "1", "Tags": [ "javascript", "react.js" ], "Title": "Fetching data and then writing them to an array" }
236346
<p>A few days ago someone asked this question. But they quickly deleted the post offering no solution.<br> Given:</p> <pre class="lang-py prettyprint-override"><code>a = ['COP' , '\t\t\t', 'Basis', 'Notl', 'dv01', '6m', '9m', '1y', '18m', '2y', '3y', "15.6", 'mm', '4.6', '4y', '5y', '10', 'mm', '4.6', '6y', '7y', '8y', '9y', '10y', '20y', 'TOTAL', '\t\t9.2' ] </code></pre> <p>They needed to traverse the list and get the following 2D table. Where the first column has only values ending in "m" or "y".</p> <pre class="lang-py prettyprint-override"><code>"COB", "Basis", "Notl" ('6m', '', '') ('9m', '', '') ('1y', '', '') ('18m', '', '') ('2y', '', '') ('3y', '15.6', '') ('4y', '', '') ('5y', '10', '') ('6y', '', '') ('7y', '', '') ('8y', '', '') ('9y', '', '') ('10y', '', '') ('20y', '', '') </code></pre> <p>I answered the question, using a coroutine and a linked list as shown below:</p> <pre><code> a = ['COP' , '\t\t\t', 'Basis', 'Notl', 'dv01', '6m', '9m', '1y', '18m', '2y', '3y', "15.6", 'mm', '4.6', '4y', '5y', '10', 'mm', '4.6', '6y', '7y', '8y', '9y', '10y', '20y', 'TOTAL', '\t\t9.2' ] headers = ('COP', "Basis", 'Notl', 'dv01') def is_Number(value): is_number = False try: float(value) except ValueError: pass else: is_number = True return is_number def is_cob(value): return True if (value[0].isnumeric() and (value[-1] == "m" or value[-1] == "y")) \ else False class Node: def __init__(self, data=None, next_cop=None, next_column=None): self.data = data self.next_cop = None self.next_column = None class LinkedList: def __init__(self): self.headNode = None def printlist(self): print("This is the list =&gt;:") temp = self.headNode while temp: print("Data-&gt; :", temp.data) temp1 = temp.next_column while temp1: print("|") print("---&gt;Column: Bias, Notl =", temp1.data) temp1 = temp1.next_column temp = temp.next_cop def isEmpty(self): return False if self.headNode else True def insert_at_head(self, node): if self.isEmpty(): self.headNode = node else: node.next_cop = self.headNode self.headNode = node def insert_at_tail(self, node): if self.isEmpty(): self.headNode = node return temp = self.headNode while temp.next_cop: temp = temp.next_cop temp.next_cop = node def insert_at_tail_column_of_nodeX(self, nodeX, node): temp = self.get_pointer_to_nodeX(nodeX) while temp.next_column: temp = temp.next_column temp.next_column = node def get_pointer_to_nodeX(self, nodeX): temp = self.headNode while temp.next_cop != nodeX: temp = temp.next_cop temp = temp.next_cop return temp def get_last_node_data(self): if self.isEmpty(): return self.headNode.data temp = self.headNode while temp.next_cop: temp = temp.next_cop return temp.data def get_last_node(self): if self.isEmpty(): return self.headNode temp = self.headNode while temp.next_cop: temp = temp.next_cop return temp def iterate_from(self, node=None): while node is not None: yield node node = node.next_cop def rows(llist): lst = [] while True: value = yield if value is None: break lst.append(value) is_number = is_Number(value) if is_cob(value): llist.insert_at_tail(Node(value)) if is_number and is_cob(llist.get_last_node_data()) \ and (is_cob(lst[-2]) or is_Number(lst[-2])): llist.insert_at_tail_column_of_nodeX(llist.get_last_node(), Node(value)) return llist if __name__ == "__main__": llist = LinkedList() sent_to_coro = [elem for elem in a if elem not in headers] coro_rows = rows(llist) next(coro_rows) for element in sent_to_coro: print("Sending....", element) coro_rows.send(element) try: coro_rows.send(None) except StopIteration as exc: result = exc.value out = [] for item in llist.iterate_from(llist.headNode): cop = item.data basis = item.next_column.data if item.next_column else "" notl = item.next_column.next_column.data if basis and item.next_column.next_column else "" out.append((cop,basis,notl)) for itm in out: print(itm) </code></pre> <p>Someone posted a solution with regex that was just a few lines of code, but unfortunately it was deleted because the question itself was just a question with no code and immediately started to be downvoted of course.</p> <p>I would like to:</p> <ol> <li>Hear some suggestion on this code. Specifically, I wanted to know if there is any real improvement to this code.</li> <li>Is this solution overworked?</li> <li>I would like to see other solutions to this problem using Regex</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:03:12.157", "Id": "463119", "Score": "0", "body": "Do you have a link to the original post. Even though it is deleted?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:15:56.967", "Id": "463120", "Score": "0", "body": "Unfortunately no. It was all so fast, I just can tell it was a couple of days ago and it was his/her first post in https://stackoverflow.com/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:18:26.180", "Id": "463121", "Score": "0", "body": "Let me clarify, that I answered the question but was not even able to post it. What I'm looking for is a review of my response and the answer that was posted that was using RegEx" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:23:03.680", "Id": "463123", "Score": "0", "body": "@Peilonrayz, I guess it is the link https://stackoverflow.com/questions/59940421/what-is-the-best-way-to-do-this-in-python" } ]
[ { "body": "<p>To be brief on your three points.</p>\n\n<p>You can try to omit extra variables and trust the function boundary. For example, your code starts with this excellently named function:</p>\n\n<pre><code>def is_Number(value):\n is_number = False\n try:\n float(value)\n except ValueError:\n pass\n else:\n is_number = True\n return is_number\n</code></pre>\n\n<p>or more concisely,</p>\n\n<pre><code>def is_Number(value):\n try:\n float(value)\n except ValueError:\n return False\n return True\n</code></pre>\n\n<p>You might see <a href=\"http://www.omahapython.org/IdiomaticPython.html\" rel=\"nofollow noreferrer\">Code Like A Pythonista</a> for a better explanation.</p>\n\n<p>Yes, your code does seem overly worked for the problem.</p>\n\n<p>Instead of giving you a regex, I recommend <a href=\"http://regex101.com\" rel=\"nofollow noreferrer\">Regex101</a>. It is a single web page playground for experimenting with RegEx with full explanations of what matches. Be sure to pick 'Python' for the dialect.</p>\n\n<p>Keep hacking! Keep notes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T16:41:35.770", "Id": "463475", "Score": "0", "body": "yes, this is a valid observation.Thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T06:32:51.110", "Id": "236397", "ParentId": "236347", "Score": "2" } }, { "body": "<p>With some help I found a solution using RegEx that indeed shows what I did is overworked. I failed to see the array as a long string and apply a RegEx to it</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import re\na = ['COP' , '\\t\\t\\t', 'Basis', 'Notl', 'dv01', '6m', '9m', '1y',\n '18m', '2y', '3y', \"15.6\", 'mm', '4.6', '4y', '5y', '10', 'mm',\n '4.6', '6y', '7y', '8y', '9y', '10y', '20y', 'TOTAL', '\\t\\t9.2']\n\n rule2 = re.compile(r\"\\b(\\d+[ym])\\W+([0-9]+\\.?[0-9]*)*\\b\")\n a_str = \" \".join(a)\n OUT2 = re.findall(rule2, a_str)\n print(OUT2)\n\n</code></pre>\n\n<p>output</p>\n\n<pre><code>&gt;&gt; [('6m', ''), ('9m', ''), ('1y', ''), ('18m', ''), ('2y', ''), ('3y', '15.6'), ('4y', ''), ('5y', '10'), ('6y', ''), ('7y', ''), ('8y', ''), ('9y', ''), ('10y', ''), ('20y', '')]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T02:22:05.153", "Id": "236453", "ParentId": "236347", "Score": "0" } } ]
{ "AcceptedAnswerId": "236453", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T12:48:57.997", "Id": "236347", "Score": "5", "Tags": [ "python", "python-3.x", "linked-list" ], "Title": "Converting a 1D list to a 2D table" }
236347
<pre><code>categories = [{id: "761601bc-4daf-4db2-a0cf-fe7f443fcb94", name: "Shoes"},{id: "601ebcfe-fcbd-4075-a4b4-a42e356c5747", name: "Hats"},{id: "238933cf-77a5-4443-b290-7d7c836f80ff", name: "Eyewear"}]; voucher = {id:1,categories:["761601bc-4daf-4db2-a0cf-fe7f443fcb94","601ebcfe-fcbd-4075-a4b4-a42e356c5747"]}; filterCategories(voucher) { const result = voucher.categories ? categories .filter(cat =&gt; { return voucher.categories.includes(cat.id); }) .map(v =&gt; v.name) .sort() .join() : ""; return result; } </code></pre> <p>Expecting: "Hats,Shoes"</p> <p>The result needs to be filtered and sorted and returned as a string. Is there a faster, more efficient way of doing this. Maybe using Lodash?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:59:40.417", "Id": "463133", "Score": "0", "body": "I think that this would widely be considered to be the most concise and easily accepted approach. As for time complexity, I don't think that there would be a more efficient way without a trade-off in readability." } ]
[ { "body": "<p>Normally there are a lot of categories, so I'd go through the voucher.categories array:</p>\n\n<pre><code>const filterCategories = (voucher, categories) =&gt; (\n Array.isArray(voucher.categories) ?\n voucher.categories\n .map(categoryId =&gt; {\n const categoryFound = categories.find(c =&gt; c.id === categoryId);\n return categoryFound ? categoryFound.name : null;\n })\n .filter(categoryName =&gt; categoryName !== null)\n .sort()\n .join() :\n \"\"\n);\n</code></pre>\n\n<p>This way you don't have to go through the entire list of 'master' categories (which in practice may be very long) doing a search on the voucher categories in each iteration.</p>\n\n<p>Note: it would be much faster if you could have the categories as an object with the id as index:</p>\n\n<pre><code>categories = {\n [\"761601bc-4daf-4db2-a0cf-fe7f443fcb94\"]: {name: \"Shoes\"},\n [\"601ebcfe-fcbd-4075-a4b4-a42e356c5747\"]: {name: \"Hats\"},\n [\"238933cf-77a5-4443-b290-7d7c836f80ff\"]: {name: \"Eyewear\"}\n};\n\nconst filterCategories = (voucher, categories) =&gt; (\n Array.isArray(voucher.categories) ?\n voucher.categories\n .map(categoryId =&gt; {\n const categoryFound = categories[categoryId];\n return categoryFound ? categoryFound.name : null;\n })\n .filter(categoryName =&gt; categoryName !== null)\n .sort()\n .join() :\n \"\"\n );\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T08:58:33.220", "Id": "463274", "Score": "0", "body": "You are wrong. Assuming the ids Are unique and `c = categories.length` And `v=voucher.categories.length`, ignoring sort And join, time complexity Is `c*v+v` in OP's implementation And `v*c+v` in yours. And that's the same thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T09:10:42.023", "Id": "463277", "Score": "0", "body": "But hey thinking about it, for randomly chosen voucher categories you probably save some searches in most cases. Just the asymptotic upper limit is the same." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T12:19:26.340", "Id": "463446", "Score": "0", "body": "@slepic thanks for your comments. I'm assuming 'categories' is a master table of categories, with id as PK (unique). I'm also assuming 'categories' is in practice much longer than 'voucher.categories' (c >> v). So under these conditions, even with the same asymptotic limit, I think my function would be faster, but I haven't measured it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T19:29:19.443", "Id": "463488", "Score": "0", "body": "To be more specific. If all the voucher categories are on the end of the master categories list, the performance will be same. If all voucher categories are on the beginning of the master categories list, then your implementation goes to `v*v + v`. Somewhere between for the rest (and likely most) of cases. The performance gain will also be proportional to `c - v` (assuming `v<=c`, although, in practise, likely just `v<c` or even `v<<c`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T19:38:07.250", "Id": "463489", "Score": "0", "body": "So yeah yours is gonna be (somewhat) faster in most real world scenarios. I already voted your answer up yesterday :) Anyway, now I'm getting curious if a simple for loop combining the map and filter can make it even faster..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T15:24:33.333", "Id": "236357", "ParentId": "236348", "Score": "3" } }, { "body": "<p>It may make sense to turn <code>voucher.categories</code> into a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\"><code>Set</code></a> (or store them in a <code>Set</code> instead of an array in the first place) to speed up the <code>contains</code> call, however that is only sensible, if you expect it to contain a lot of items.</p>\n\n<p>Other than that I'd move the check for the existence of <code>voucher.categories</code> (and add a check if it's empty) outside the expression, in order to reduce the indentations and make the code more readable:</p>\n\n<pre><code>filterCategories(voucher) {\n if (!voucher.categories || voucher.categories.length == 0) {\n return \"\";\n }\n return categories\n .filter(cat =&gt; voucher.categories.includes(cat.id))\n .map(v =&gt; v.name)\n .sort()\n .join();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T12:29:59.703", "Id": "236413", "ParentId": "236348", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T13:14:02.307", "Id": "236348", "Score": "4", "Tags": [ "javascript", "array", "lodash.js" ], "Title": "Filter one array based on values of another, is this the best way?" }
236348
<p>I am currently building cache for my application, and I would like to have my redis cache client work the same way you would dependency inject a DbContext.</p> <p>I am using StackExchange.Redis to manage my redis cache: <a href="https://github.com/StackExchange/StackExchange.Redis" rel="nofollow noreferrer">https://github.com/StackExchange/StackExchange.Redis</a></p> <p>I have made it work, but I am not very confident in the way I implemented it.</p> <p>In my services I have added:</p> <pre class="lang-cs prettyprint-override"><code> services.AddSingleton&lt;IConnectionMultiplexer(ConnectionMultiplexer .Connect("localhost:6379,allowAdmin=true")); services.AddScoped&lt;ICacheClient, CacheClient&gt;(); </code></pre> <p>I could not figure out how to add IDatabase to services.</p> <p>My CacheClient looks like this:</p> <pre class="lang-cs prettyprint-override"><code> public class CacheClient : ICacheClient { private readonly IConnectionMultiplexer _connectionMultiplexer; private readonly IDatabase _redisCache; private readonly ISerializer _serializer; public CacheClient(IConnectionMultiplexer connectionMultiplexer, ISerializer serializer) { _connectionMultiplexer = connectionMultiplexer; _serializer = serializer; _redisCache = connectionMultiplexer.GetDatabase(); } //add/set cache methods removed for the sake of brevity. } </code></pre> <p>From here I can use _redisCache to access the database and do operations such as _redisCache.StringSetAsync etc...</p> <p>Now ICacheClient can be injected into my application and I can use my cache logic in any class. Which is very nice.</p> <p>Is there anything wrong with this way of implementing my cache client?</p>
[]
[ { "body": "<p>I can share with you an example version of Redis service such as getting subscribers or accessing the other databases and also for catching connection issues.</p>\n<p><code>ConfigurationOptions</code> allows us to initialize service with more Redis servers(Redis pool), if needed you can easily change the constructor parameters.</p>\n<p>Note that <code>ConnectionMultiplexer.Connect();</code> is <code>already static</code> method, so you can initialize service in class when needed as I did below.</p>\n<p>In Addition, I assume that you take <code>ISerializer</code> for the object serialization, if it is, I added an example of <code>serialize</code>/<code>deserialize </code>for you.</p>\n<p>I hope it helps you.</p>\n<pre class=\"lang-c# prettyprint-override\"><code> public class CacheClient : ICacheClient\n {\n private readonly ConfigurationOptions configuration = null;\n private Lazy&lt;IConnectionMultiplexer&gt; _Connection = null;\n\n public CacheClient(string host = &quot;localhost&quot;, int port = 6379, bool allowAdmin = false)\n {\n configuration = new ConfigurationOptions()\n {\n //for the redis pool so you can extent later if needed\n EndPoints = { { host, port }, },\n AllowAdmin = allowAdmin,\n //Password = &quot;&quot;, //to the security for the production\n ClientName = &quot;My Redis Client&quot;,\n ReconnectRetryPolicy = new LinearRetry(5000),\n AbortOnConnectFail = false,\n };\n _Connection = new Lazy&lt;IConnectionMultiplexer&gt;(() =&gt;\n {\n ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(configuration);\n //redis.ErrorMessage += _Connection_ErrorMessage;\n //redis.InternalError += _Connection_InternalError;\n //redis.ConnectionFailed += _Connection_ConnectionFailed;\n //redis.ConnectionRestored += _Connection_ConnectionRestored;\n return redis;\n });\n }\n\n //for the 'GetSubscriber()' and another Databases\n public IConnectionMultiplexer Connection { get { return _Connection.Value; } }\n\n //for the default database\n public IDatabase Database =&gt; Connection.GetDatabase();\n\n public T JsonGet&lt;T&gt;(RedisKey key, CommandFlags flags = CommandFlags.None)\n {\n RedisValue rv = Database.StringGet(key, flags);\n if (!rv.HasValue)\n return default;\n T rgv = JsonConvert.DeserializeObject&lt;T&gt;(rv);\n return rgv;\n }\n\n public bool JsonSet(RedisKey key, object value, TimeSpan? expiry = null, When when = When.Always, CommandFlags flags = CommandFlags.None)\n {\n if (value == null) return false;\n return Database.StringSet(key, JsonConvert.SerializeObject(value), expiry, when, flags);\n }\n private void _Connection_ErrorMessage(object sender, RedisErrorEventArgs e)\n {\n throw new NotImplementedException();\n }\n\n //add/set cache methods removed for the sake of brevity.\n }\n\n</code></pre>\n<p><strong>Adding Service</strong></p>\n<pre class=\"lang-c# prettyprint-override\"><code> services.AddSingleton&lt;ICacheClient&gt;(new CacheClient(allowAdmin:true));\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-24T13:18:54.663", "Id": "473156", "Score": "1", "body": "Very nice, I have been looking for something to handle the case when the redis server is not up.\n\nRight now a request throws and error if the redis server is down. Id like to have it just fall back to SQL if it is not up. I will try to implement this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-24T20:41:21.420", "Id": "473211", "Score": "0", "body": "i am also using this code and i am updating the code when i have changed it. if you see better solution please share with me. this is my best solution too." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T00:10:21.293", "Id": "240660", "ParentId": "236349", "Score": "4" } } ]
{ "AcceptedAnswerId": "240660", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T13:32:29.507", "Id": "236349", "Score": "4", "Tags": [ "c#", ".net", "dependency-injection", "redis", ".net-core" ], "Title": "Dependency Injected StackExchange.Redis Client" }
236349
<p>I am learning programming with Python. I am not sure if I can write a try/except block like this.</p> <pre><code>import os import shutil try: shutil.rmtree('c:/guna/newCAT1') print("dir newCAT1 deleted") except: os.mkdir('c:/guna/newCAT1') print("dir newCAT1 created") fileIN=open('c:/guna/newCAT1/secretMSG.txt','w' ) fileIN.writelines("the dog is green") fileIN.close() else: print("exception code did not execute") os.mkdir('c:/guna/newCAT1') print("dir newCAT1 created") fileIN = open('c:/guna/newCAT1/secretMSG.txt', 'w') fileIN.writelines("the dog is green") fileIN.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T01:00:36.127", "Id": "463246", "Score": "2", "body": "What do you mean you’re not sure?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T13:49:47.123", "Id": "463305", "Score": "1", "body": "Please can you add more information to your post. As currently it's unclear what you're asking for. Thank you." } ]
[ { "body": "<p>You might want to ask a more specific question on Stack Overflow if you don't know if it works.</p>\n\n<p>In the meantime, you should catch the most specific exception you can, so <code>except OSError</code> instead of a bare <code>except</code>. Also, you should use exception code to mitigate a problem and continue, so more like:</p>\n\n<pre><code>try:\n shutil.rmtree('c:/guna/newCAT1')\n print(\"dir newCAT1 deleted\")\nexcept OSError:\n pass # do nothing on this exception.\n# continue with making the directory. The exception statement is complete\n</code></pre>\n\n<p>or, if you read the documentation for <code>shutil.rmtree</code>:</p>\n\n<pre><code>shutil.rmtree('c:/guna/newCAT1', ignore_errors=True)\nprint(\"dir newCAT1 deleted\")\nos.mkdir('c:/guna/newCAT1')\nprint(\"dir newCAT1 created\")\nfileIN=open('c:/guna/newCAT1/secretMSG.txt','w' )\nfileIN.writelines(\"the dog is green\")\nfileIN.close()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-29T14:35:57.110", "Id": "490341", "Score": "0", "body": "thank you for the code example. it gave me idea about how to write a python code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T06:44:02.620", "Id": "236398", "ParentId": "236351", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:11:52.323", "Id": "236351", "Score": "1", "Tags": [ "python", "beginner", "python-3.x", "error-handling" ], "Title": "File handling with try and except" }
236351
<p>I'm taking on a project from a previous programmer. My goal is to make it a bit smaller and hopefully better. Originally the code has a bunch of length checks and Booleans as shown below.</p> <p><strong>C#</strong></p> <pre><code>string[] splitStrArray = SNString.Split('-'); string part1 = splitStrArray[0]; string part2 = splitStrArray[1]; string part3 = splitStrArray[2]; bool part1ok = false; bool part2ok = false; bool part3ok = false; if (part1.Length == 3) { part1ok = true; } if (part2.Length == 8) { part2ok = true; } if (part3.Length == 3) { part3ok = true; } if(part1ok &amp;&amp; part2ok &amp;&amp; part3ok) { return true; } else { return false; } </code></pre> <p>Is it a good practice to keep that or should I change it to my following idea?</p> <pre><code>string[] splitStrArray = SNString.Split('-'); string part1 = splitStrArray[0]; string part2 = splitStrArray[1]; string part3 = splitStrArray[2]; if(part1.Length == 3 &amp;&amp; part2.Length == 8 &amp;&amp; part3.Length == 3) { return true; } else { return false; } </code></pre> <p>Basically a barcode is scanned, and a SN is passed to the application. The goal is to make sure the SN scanned is of a format XXX-XXXXXXXX-XXX. Sometimes there are occurrences of SNs that are formatted XXXXXXXXXXXXX or XXX-XXXXXXXXXX not complete or missing a specific dash.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T16:00:27.837", "Id": "463143", "Score": "2", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please edit to the site standard, which is for the title to simply state the task accomplished by the code. Please see [**How to get the best value out of Code Review: Asking Questions**](https://CodeReview.Meta.StackExchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T23:14:51.460", "Id": "463198", "Score": "10", "body": "I note that the code is already possibly wrong. Who says that `Split` returns an array with exactly four elements? If you already know that there are exactly three hyphens in the string, then whatever code ensures that invariant should ensure the other invariants are met. If you do not already know that, then your program can crash. Either way, something seems wrong here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T23:24:46.200", "Id": "463205", "Score": "1", "body": "Exactly three elements, I meant to say. Three regions separated by hyphens." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T00:44:43.097", "Id": "463240", "Score": "5", "body": "I'm mildly amused by this being considered \"massive\"... certainly large in comparison to what it could be, but it's not a thousand-line function like I've seen before." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T12:09:27.513", "Id": "463297", "Score": "0", "body": "Tried posting an answer, but there's a blocking error: **\"_Your post appears to contain code that is not properly formatted as code. Please indent all code by 4 spaces using the code toolbar button or the CTRL+K keyboard shortcut. For more editing help, click the [?] toolbar icon._\"**. The answer's displaying just fine in the preview screen." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T12:17:46.477", "Id": "463299", "Score": "0", "body": "Looks like it's protesting the inclusion of \\$\\mathrm{\\TeX} :\\$\n$$\n{\\left.\n\\underbrace{\\texttt{XXX}}_{3}\n-\n\\underbrace{\\texttt{XXXXXXXX}}_{8}\n-\n\\underbrace{\\texttt{XXX}}_{3}\n\\right.}_{\\Large{.}}\n$$\nMeh, ah wells." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T15:32:29.000", "Id": "463321", "Score": "1", "body": "Note what this code fails for `X` with a `IndexOutofRangeException` and pass for `XXX-XXXXXXXX-XXX---------ABCEDJH1234!@#$%*()_`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T21:56:32.687", "Id": "463385", "Score": "0", "body": "I bet the numerous partxxx variables were to inspect values in the debugger." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T08:48:59.257", "Id": "463433", "Score": "2", "body": "This question lacks any indication of what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T16:22:02.597", "Id": "463560", "Score": "0", "body": "What is *\"SN\"*? *\"Serial number\"*? *\"Social network\"*? *\"Screen name?\"* *\"[Shared-nothing](https://en.wiktionary.org/wiki/shared-nothing)\"*? *\"[Social Security number](https://en.wikipedia.org/wiki/Social_Security_number)\"*? If Social Security number, it should be SSN, not SN." } ]
[ { "body": "<blockquote>\n <p>Is it a good practice to keep that </p>\n</blockquote>\n\n<p><strong>No</strong></p>\n\n<blockquote>\n <p>or should I change it to my idea </p>\n</blockquote>\n\n<p>Yours is better but it could be better. </p>\n\n<p>The <code>if..else</code> could just be simplified like </p>\n\n<pre><code>return part1.Length == 3 &amp;&amp; part2.Length == 8 &amp;&amp; part3.Length == 3;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T20:56:59.390", "Id": "463373", "Score": "5", "body": "`return new Regex(@\"\\d{3}-\\d{8}-\\d{3}\").IsMatch(SNString);`, or if you wanted to match just about any number/letters, the expression would be `[a-zA-Z0-9]{3}-[a-zA-Z0-9]{8}-[a-zA-Z0-9]{3}`, there's a lot of ways to skin this in a simple way, the OP should be aiming for readability/maintainability." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T15:53:58.990", "Id": "236358", "ParentId": "236354", "Score": "23" } }, { "body": "<p>Your idea is definitely better than the original, but I think it could be better still.</p>\n\n<p>Firstly;</p>\n\n<pre><code>if(part1.Length == 3 &amp;&amp; part2.Length == 8 &amp;&amp; part3.Length == 3)\n{\n return true;\n}\nelse\n{\n return false;\n}\n</code></pre>\n\n<p>This can be simplified into a single return statement, as follows;</p>\n\n<pre><code>return part1.Length == 3 &amp;&amp; part2.Length == 8 &amp;&amp; part3.Length == 3;\n</code></pre>\n\n<p>Secondly, it would probably be better if the length values you are comparing to were constants. It's definitely better if there's ever a chance that the expected length changes (then you know you only need to change one place in the code), but even if you know it will remain constant for the life of the codebase it's a lot easier to read and understand <code>something.Length == XCodeLength</code> than <code>something.Length == 3</code> and having to know or find out that this is because XCodes always have length 3. (Obviously naming and set up of this are very context dependent...)</p>\n\n<p>Thirdly, do the separate parts mean anything? I.e. is there a more meaningful name that could be used for each bit of the split? (e.g. if these were telephone numbers (which they aren't based on the numbers, but it's the best example I could think of) it'd be a lot more clear if <code>part1</code> was instead called <code>countryCode</code> (or <code>areaCode</code> - pick your format, but the point is the same)). Naming these well would also link nicely into putting the lengths into constants.</p>\n\n<p>As a final point, you may have a specific code style you need to follow, but it's more normal for C# to use var when possible rather than writing out the type of a variable when it can be inferred (you can still easily see the type in an IDE).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T16:49:06.950", "Id": "463145", "Score": "0", "body": "The input is always in a format of XXX-XXXXXXXX-XXX. The insides dont mean much to me yet" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T23:25:20.893", "Id": "463206", "Score": "13", "body": "@Travis: I am confused. If the input is **always** in that format then why do you need the function at all?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T04:47:42.600", "Id": "463257", "Score": "1", "body": "@EricLippert Perhaps to validate that the input actually matches the format?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T10:00:47.327", "Id": "463282", "Score": "2", "body": "@ZevSpitz Eric is not confused; that's just a rhetorical question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T19:19:08.210", "Id": "463362", "Score": "7", "body": "No, I'm genuinely confused. If the input is *always* in the desired format then there is no need to write a validator that confirms that except, say, as an assertion. Also, as I noted, the original code assumes that the input is definitely in a form that has at least two dashes; it crashes otherwise, indicating that the code has never been tested in an environment where that invariant was violated. It is unclear to me what properties are actually being tested for here, and why the existing code assumes some invariants are met but not others." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T16:26:27.057", "Id": "236359", "ParentId": "236354", "Score": "9" } }, { "body": "<p>I know it's answered, but I think the whole converting to char array is not needed. </p>\n\n<p>You can simplify it further to (based on original code):</p>\n\n<pre><code>// SNString?.Length == 16 -&gt; Should be exactly 16 characters\n// SNString?[3] == '-' -&gt; the first dash should be in index number 3\n// SNString?[12] == '-' -&gt; the first dash should be in index number 12\n// SNString?.Replace(\"-\", \"\")?.Length == 14 -&gt; if there is only 2 dashes, then removing them would result with length == 14, otherwise is false\nreturn SNString?.Length == 16 &amp;&amp; SNString?[3] == '-' &amp;&amp; SNString?[12] == '-' &amp;&amp; SNString?.Replace(\"-\", \"\")?.Length == 14;\n</code></pre>\n\n<p>which is equivalent to :</p>\n\n<pre><code>if(SNString?.Length == 16)\n{\n if (SNString?[3] == '-' &amp;&amp; SNString?[12] == '-' &amp;&amp; SNString?.Replace(\"-\", \"\")?.Length == 14)\n return true;\n}\n\nreturn false;\n</code></pre>\n\n<p>You should check the length of the provided string, then apply the other validations. \nThe string length will determine if you need to apply the other validations or not.\nif the string's length is not equal to 16, then surely it's not a valid format.\nif the string length == 16, then it's a valid format which needs to be validated.\nThen you just get the position of the first and last dashes. if they're in the correct position, \nthen the first, second, and third parts should have the correct length. Then, you can use <code>Replace</code> to replace all dashes with empty string, and check the result length, if the result is 14, then there were only two dashes, which is valid, otherwise is not valid. </p>\n\n<p>Now, you can validate three parts <code>XXX-XXXXXXXX-XXX</code>, if your characters group are all numbers (without the dashes), \nthen you can add something like <code>ulong.TryParse(SNString?.Replace(\"-\", string.Empty), out ulong result)</code>, if true, then they're all numbers, otherwise it's false.</p>\n\n<p>Doing that, would avoid converting it to char array.</p>\n\n<p>There is one thing that you should consider, if there is certain format for each characters group, you might need to use <code>Regex</code> instead. \nFor instance, if the first part should always contains letters only, or one digit with two letters ..etc. \nthen the current validation process will provide a non-valid string. Also, you might consider adding a validation of English letters and Digits to avoid having some non-English inputs. </p>\n\n<p>here is Regex example (for future reference) :</p>\n\n<pre><code>System.Text.RegularExpressions.Regex.Match(SNString, @\"^[^-]{3}-[^-]{8}-[^-]{3}$\");\n</code></pre>\n\n<p>With this, you'll have the flexablity to adjust the regex pattern to match the conditions you need. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T18:58:06.547", "Id": "463168", "Score": "0", "body": "Interesting answer! What does the '?' mean at the end, ex: SNString?.Length vs SNString.Length? Also from the understanding I have, it will always be numbers, if there are any letters that is some bad news bears" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T20:23:40.763", "Id": "463180", "Score": "1", "body": "@Travis `?` is null conditional operator. when you use `SNString?.Length ` you're saying ` if SNString != null then, return length, otherwise, return null. and `null == 3` is false. also, it'll not throw a null exception. and since it's in numbers format, you'll need to use regex solution and adjust the pattern to accept only numbers, this would be the simplest approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T23:15:59.473", "Id": "463199", "Score": "7", "body": "The first solution is not correct, insofar as it produces a different result for some inputs than the original." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T23:17:29.413", "Id": "463201", "Score": "3", "body": "Moreover, I do not understand the last clause of the first solution. Surely if the string is already known to be of length 16 by the first clause, then the length of the substring starting at character 13 and going to the end is always of length 3. How can the last clause be false?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T23:18:43.883", "Id": "463203", "Score": "2", "body": "Your second solution, by contrast, is better than the original poster's solution, as it gives correct results for a larger class of strings than the original solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T07:51:28.843", "Id": "463270", "Score": "7", "body": "The first solution will also return true when you have e.g. \"---------------\" as an input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T14:42:06.243", "Id": "463313", "Score": "0", "body": "I think your first suggestion is awfully difficult to understand, since it takes a lot of mental work to look at \"length is 16, hyphen at 3, hyphen at 12\" and figure out that that's supposed to mean \"first hyphen-separated part is of length 3, second is of length 8, third is of length 3.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T07:43:25.997", "Id": "463425", "Score": "0", "body": "@EricLippert I have fixed that, thanks for noting that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T07:43:56.967", "Id": "463426", "Score": "0", "body": "@SomeBody fixed that as well. thanks for noticing it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T07:49:05.727", "Id": "463428", "Score": "0", "body": "@TannerSwett still, since it is a fixed format, I think a straight forward validation would be better, no need for extra work, and yes, it depends on how do you look at it, as both are the same, but different view's angle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T16:04:10.703", "Id": "463470", "Score": "0", "body": "Your solution to \"count the number of dashes in a string\" is \"replace the dashes and allocate a new string and then check the length of that string\". That is really bad. **If you want to count something, use the `Count` function**." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T20:03:17.410", "Id": "463495", "Score": "0", "body": "@EricLippert creating a new immutable string is lighter than creating a new class instance of `Func<char, bool>`. Plus, if it can be done without `Linq`, there is no need for using `Linq`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T20:32:04.330", "Id": "463498", "Score": "0", "body": "You're making the wrong argument. The amortized cost of the delegate is tiny because it is cached. The new string is not! The correct form of your argument is to critique the weight of the enumerator! When you do, consider the circumstances under which the enumerator can also be cached. What are they?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T20:33:11.100", "Id": "463499", "Score": "0", "body": "But regardless the micro optimization is not the most important optimization. Make the code read like its intention! That is the compelling benefit. Not saving a few nanoseconds." } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T18:39:41.337", "Id": "236369", "ParentId": "236354", "Score": "7" } }, { "body": "<p>The original code includes <code>.Split('-')</code> which makes an array and at least three new strings; the other answers include invoking the regex engine, or making new substrings. I wanted to write a version which does little more work than walking the string once, checking the indices. I don't suggest you should use it, but maybe if you like premature optimization</p>\n\n<pre><code>String SNString = \"XXX-XXXXXXXX-XXX\";\n\n// Validate the string pattern without copying it.\n\nreturn ((SNString.Length == 16)\n &amp;&amp; (SNString.IndexOf('-' 0) == 3) // part1 must be length 3 for this to hold.\n &amp;&amp; (SNString.IndexOf('-', 4) == 12) // part2 must be length 12-4 == 8 for this.\n &amp;&amp; (SNString.IndexOf('-', 13) == -1));// part3 ends length 16 string. 16-13 == 3.\n</code></pre>\n\n<hr>\n\n<p>I do like the readability of the original version more than the <code>&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;</code> infested waters of the other options; you can keep a lot of that simplicity and shorten it down a lot, with something like this:</p>\n\n<pre><code>string[] parts = SNString.Split('-');\n\nif (parts[0].Length != 3) {\n return false;\n}\n\nif (parts[1].Length != 8) {\n return false;\n}\n\nif (parts[2].Length != 3) {\n return false;\n}\n\nreturn true;\n</code></pre>\n\n<p>NB. this has the same risk of the original and some other answers that there might be more than three parts after splitting.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T14:10:13.063", "Id": "463311", "Score": "1", "body": "In the general case, the, \"escape out quickly on any failure\" approach is great. \n In the OP's specific code, using a single return statement is both simpler and more readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T01:04:39.797", "Id": "463404", "Score": "0", "body": "@Brian yeah there's not much in it - the single line answer is deceptive, as it still depends on doing a Split() and then assigning three parts of the array to three new string variables, so it ends up longer and less obviously correct from that. And if you inline the checks to `parts[1].Length == 3 &&` then the added bracket indexing in one line starts to get a bit dense for my liking. It's `A && B || C && !D` style code which makes me unhappy - so hard to verify by eye that the tests do exactly what was intended in every case, but `== && == && ==` could be simple enough." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T12:11:26.967", "Id": "236412", "ParentId": "236354", "Score": "5" } }, { "body": "<pre><code>string[] splitStrArray = SNString.Split('-');\nint[] expectedLengths = { 3, 8, 3 };\n\nif( splitStrArray.length != 3 ){\n return false;\n}\n\nfor( int i = 0; i &lt; expectedLengths; ++i ){\n int expectedLength = expectedLengths[i];\n int actualLength = splitStrArray[i].Length;\n\n if( expectedLength != actualLength ){\n return false;\n }\n}\n\nreturn true;\n</code></pre>\n\n<p>I prefer loops, early exits and an \"innocent until proven guilty\" approach.</p>\n\n<p>With regards to making code simple and generic, the original code is terrible.\nExplicitly naming values in an array like that, then doing the same operation to them all is bad practise. Reasons being:</p>\n\n<ul>\n<li>It's awkward to maintain</li>\n<li>It's not scalable</li>\n<li>It just causes code to become longer than needed</li>\n</ul>\n\n<p>It might be overkill in this situation, but generalised code that don't have names like \"part1, part2, part3\" is just way easier for me to read and get to grips with.</p>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T16:07:22.843", "Id": "463471", "Score": "0", "body": "Like many of the other answers to this question, this code also crashes when given bad input. What does your function do when handed, say, the empty string?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T16:16:15.547", "Id": "463631", "Score": "0", "body": "Ah, good catch there mate. I was just trying to refactor the existing functionality, rather than take any additional scenarios into account." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T15:22:12.970", "Id": "236421", "ParentId": "236354", "Score": "1" } }, { "body": "<h2>Filter validation</h2>\n\n<p>For validation code, you could use a more compact but somewhat verbose pattern of <em>failing early, failing fast</em>.</p>\n\n<pre><code>{\n // Test for: XXX-XXXXXXXX-XXX\n\n var parts = SNString.Split( '-' );\n\n if ( parts.Length != 3 )\n return false;\n if ( parts[ 0 ].Length != 3 )\n return false;\n if ( parts[ 1 ].Length != 8 )\n return false;\n if ( parts[ 2 ].Length != 3 )\n return false;\n\n return true;\n}\n</code></pre>\n\n<p>The function will have a lot a exit points, but only a \"success\" result, at the end. Think the validation process as a filter, what only let pass correct data.</p>\n\n<p>I may nitpick this code is only testing what:</p>\n\n<pre><code>{\n // \"Mask\" test for: XXX-XXXXXXXX-XXX\n\n var hyphens = 0;\n for ( int pos = 0 ; pos &lt; SNString.Length ; pos++ )\n if ( SNString[ pos ] == '-' )\n hyphens++;\n\n if ( hyphens == 2 &amp;&amp; SNString.Length == 16 &amp;&amp; SNString[ 3 ] == '-' &amp;&amp; SNString[ 12 ] == '-' )\n return true;\n\n return false;\n}\n</code></pre>\n\n<p>No string splits, no allocations, only validations in place.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T23:15:16.087", "Id": "463394", "Score": "1", "body": "With `X-X-XXXXXXXX-XXX` the .Split() code would fail it, and your second code would pass it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T15:07:41.170", "Id": "463460", "Score": "0", "body": "Yes. I will fix that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T15:28:28.867", "Id": "236423", "ParentId": "236354", "Score": "1" } } ]
{ "AcceptedAnswerId": "236358", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T14:51:27.190", "Id": "236354", "Score": "6", "Tags": [ "c#" ], "Title": "Minimizing string length checker in C# + format(ish) function" }
236354
<p>I have written a palindrome program. And I was just wondering if it correct? I checked using the words racecar and madam, and it says they are palindromes. I have also tested nonpalindrome words and it worked correctly.</p> <p>Is my implementation correct? If it's not could you correct it for me. It it works correct, is there an easier way to implement this?</p> <pre><code>def is_palindrome(x): for i in range(0,len(x)): x = x.lower() if x[i::1] == x[::-1]: return("%s Is a palindrome" %(x)) else: return("%s Is not a palindrome" %(x)) print(is_palindrome('racecar')) </code></pre>
[]
[ { "body": "<p>You don't need the loop. Once <code>i &gt; 0</code>, the <code>if</code> statement will always be <code>False</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>x = 'abba'\nx[0::1] == x[::-1]\nTrue\n\nx[1::1] == x[::-1]\nFalse\n\nx[1::1]\n'bba'\n</code></pre>\n\n<p>So drop the iteration. Besides, the immediate <code>return</code> won't allow for iteration anyways, a second iteration will never be reached:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def is_palindrome(x):\n x = x.lower()\n\n if x[::-1] == x:\n return f'{x} is a palindrome'\n else:\n return f'{x} is not a palindrome'\n</code></pre>\n\n<p>You don't need the parentheses with <code>return</code>, and I'd use f-strings instead of <code>%</code> formatting if you're on python 3.5+.</p>\n\n<p>If you are adding the possibilities of spaces/punctuation, you could change <code>x</code> to only include alphabet chars:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def is_palindrome(x):\n # this will produce only alphabet lowercase chars\n # and join them into a string, though I'm not sure if\n # this is a use case for you\n x = ''.join(filter(str.isalpha, x.lower()))\n\n if x[::-1] == x:\n return f'{x} is a palindrome'\n else:\n return f'{x} is not a palindrome'\n</code></pre>\n\n<p>To show what that join statement does:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># maybe this should be a palindrome if you ignore the\n# non-alpha chars including spaces\nx = \"ABC1234CB a.\"\n\ny = ''.join(filter(str.isalpha, x.lower()))\n'abccba'\n</code></pre>\n\n<h2>Edit</h2>\n\n<p>To address concerns in the comments, if you wanted to offer options into what kind of filtering you want to provide, you could use a dictionary to act as a mapping:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from functools import partial\n\ndef is_palindrome(input_str, filter_type='nofilter'):\n \"\"\"\n Parameter 'filter_type' defaults to pass-through, but you can\n provide options such as 'alphanum', 'nospace' (to just get rid of spaces), and 'alpha'\n \"\"\"\n filters = {\n 'alpha': partial(filter, str.isalpha),\n 'alphanum': partial(filter, str.isalnum),\n 'nospace': partial(filter, lambda char: not char.isspace()),\n 'nofilter': partial(map, lambda char: char) # this is just a pass-through \n }\n\n # raise this exception just so the use is more clear to the user\n # what is expected\n try:\n f = filters[filter_type]\n except KeyError as e:\n raise ValueError(\n f\"Invalid filter_type, choose one of {'\\n'.join(filters)}\"\n ) from e\n\n x = ''.join(filter_type(input_str.lower()))\n\n # you can just check the first half of the string\n # against the last half reversed, rather than comparing the entire string \n midpoint = len(x) // 2\n if len(x) % 2: # even length\n a = b = midpoint\n else:\n a, b = midpoint + 1, midpoint\n\n return x[:a] == x[b::-1]\n</code></pre>\n\n<p><a href=\"https://docs.python.org/3.6/library/functools.html#functools.partial\" rel=\"nofollow noreferrer\"><code>partial</code></a> will bind arguments to a function and return a new callable. As a small example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def f(a):\n return a\n\ng = partial(f, 1)\nf(2)\n2\n\ng()\n1\n</code></pre>\n\n<p>Which is helpful for taking a function that takes many arguments and returning one that takes fewer arguments.</p>\n\n<p>Credit to <a href=\"https://codereview.stackexchange.com/a/236367/185198\">Toby Speight</a> for returning <code>bool</code> type, @Baldrickk for midpoint slice, and @Peilonrayz for concern over input filtering.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T14:00:02.440", "Id": "463307", "Score": "0", "body": "Why have you added `str.isalpha`? 0w0 is a palindrome, not because you mutilate it to become w." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T14:49:00.510", "Id": "463315", "Score": "0", "body": "@Peilonrayz sure, that didn't appear to be OP's use case. I didn't see any clarification from OP that this needed to be the case, and I don't see how it makes the review wrong. I also mentioned that OP *could* have this option, but it's not necessary" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T14:53:36.523", "Id": "463316", "Score": "1", "body": "@Peilonrayz it could easily be made to be alphanumeric, which would make sense, but it _does_ show the method by which would be done, so I wouldn't fault the answer for this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T14:55:14.163", "Id": "463317", "Score": "1", "body": "An additional note - you don't need to compare the full string `x` with its reverse - you need only compare the first half with the reverse of the second half." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T15:55:06.340", "Id": "463323", "Score": "0", "body": "@Baldrickk And why o' why would I ever want my `is_palindrome` to mangle my input? Not only does it violate SRP, it makes absolutely no sense for it to be there. If you want to check if only the alpha is a palindrome, then make a `filter_to_alpha` function and use `is_palindrome(filter_to_alpha(value))`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T16:30:05.787", "Id": "463338", "Score": "0", "body": "@Peilonrayz I made an edit to more clearly outline options OP could use. Again, a lot of this starts to just turn into personal taste based on how the code is supposed to be used, but hopefully this is a bit more clear" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T16:33:46.650", "Id": "463341", "Score": "0", "body": "@Baldrickk the midpoint slice suggestion is a really good one for longer strings, thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T17:22:37.377", "Id": "463353", "Score": "0", "body": "To be clear, this is continuing to violating SRP in the same way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T18:57:36.137", "Id": "463357", "Score": "0", "body": "@Peilonrayz Maybe so, but if I don't include that, does that make the review bad? Normally I'm not one to argue with suggestions, but a review does not have to cover every facet of code. Do I need to cover code down to the nth possible standard for it to be correct? I don't see that outlined in [How to Answer](https://codereview.stackexchange.com/help/how-to-answer)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T19:38:51.140", "Id": "463363", "Score": "0", "body": "\"does that make the review bad?\" To me; when an answer add a problem that the OP didn't - yes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T13:08:19.147", "Id": "463451", "Score": "0", "body": "@Peilonrayz palindromes as defined in a language basis only involve the letters. For example, \"Don’t nod.\" is a palindrome, despite being different to \".don t'noD\". Therefore a palindrome checker is expected to make the conversion. If you were writing up formal requirements, that would be one. Mangling input is done all the time - if I want a phone number off you, I don't care if you write `01234 567 890` or `01234567890` or `0123 45 67 890` - all I care about is the data that represents - the presentation of that is separate. palindromes are about the characters, so that's what you test." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T13:11:38.150", "Id": "463452", "Score": "0", "body": "@Peilonrayz if you want to implement it as a pair of functions, then that's fine, but the principle of least astonishment would be to provide the defined correct answer to `is_palindrome(value)` and not have to call `is_palindrome(filter_to_alpha(value))` to get the correct result." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T13:19:24.810", "Id": "463453", "Score": "0", "body": "@Baldrickk I was rather astonished when I saw the normalization. So, to me, it violates that too." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T17:43:36.307", "Id": "236366", "ParentId": "236360", "Score": "8" } }, { "body": "<p>I would expect a function that has a &quot;predicate&quot; name (<code>is_x()</code>) to return a boolean value rather than a string. The boolean is much more useful to the caller.</p>\n<p>We should add a main-guard to top-level code, so the file could be useful as a module.</p>\n<p>Consider adding some unit tests. A convenient way to do this is using the <a href=\"https://docs.python.org/3.8/library/doctest.html\" rel=\"nofollow noreferrer\"><code>doctest</code></a> module, which finds tests in the function's docstring; any line beginning with <code>&gt;&gt;&gt;</code> is a test, and is immediately followed by the expected result.</p>\n<p>Building on <a href=\"https://codereview.stackexchange.com/a/236366/75307\">the version shown by C.Nivs</a>, that would give this improved version:</p>\n<pre><code>def is_palindrome(x):\n '''\n True if the letters of x are the same when\n reversed, ignoring differences of case.\n &gt;&gt;&gt; is_palindrome('')\n True\n &gt;&gt;&gt; is_palindrome('a')\n True\n &gt;&gt;&gt; is_palindrome('a0')\n False\n &gt;&gt;&gt; is_palindrome('ab')\n False\n &gt;&gt;&gt; is_palindrome('ab a')\n False\n &gt;&gt;&gt; is_palindrome('Aba')\n True\n &gt;&gt;&gt; is_palindrome('Àbà')\n True\n '''\n x = x.lower()\n # Alternative (letters only):\n # x = ''.join(filter(str.isalpha, x.lower()))\n # Alternative (letters and digits only):\n # x = ''.join(filter(str.isalnum x.lower()))\n return x[::-1] == x\n\nif __name__ == '__main__':\n import sys\n for string in sys.argv[1:]:\n # check each command-line argument\n message = 'is a palindrome' if is_palindrome(string) else 'is not a palindrome'\n print(f'{string} {message}')\n else:\n # no arguments, so run self-test\n import doctest\n doctest.testmod()\n</code></pre>\n<p>It may well make sense to separate the pre-processing from the palindrome checking, so that <code>is_palindrome()</code> simply returns <code>x[::-1] == x</code>, and the caller is responsible for deciding which characters are significant. We could call it with a specific canonicalisation:</p>\n<pre><code>is_palindrome(string.lower())\n</code></pre>\n<p>More advanced would be to pass a normalisation function and/or a character filter, as optional arguments:</p>\n<pre><code>def is_palindrome(s, normalise=None, char_filter=None):\n '''\n True if the letters of x are the same when\n reversed, ignoring differences of case.\n &gt;&gt;&gt; is_palindrome('')\n True\n &gt;&gt;&gt; is_palindrome('a')\n True\n &gt;&gt;&gt; is_palindrome('a0')\n False\n &gt;&gt;&gt; is_palindrome('a0', char_filter=str.isalpha)\n True\n &gt;&gt;&gt; is_palindrome('ab')\n False\n &gt;&gt;&gt; is_palindrome('ab a')\n False\n &gt;&gt;&gt; is_palindrome('Aba')\n False\n &gt;&gt;&gt; is_palindrome('Aba', normalise=str.lower)\n True\n &gt;&gt;&gt; is_palindrome('Àbà', normalise=str.lower)\n True\n '''\n if normalise:\n s = normalise(s)\n if char_filter:\n s = ''.join(filter(char_filter, s))\n return s == ''.join(reversed(s))\n</code></pre>\n<p>Usage of these optional arguments should be apparent from the extra tests I've added.</p>\n<hr />\n<h2>Bug</h2>\n<p>Whether we use <code>[::-1]</code> or <code>reversed()</code> to reverse the input string, we have a bug when the input contains characters that are formed using combining accents, as demonstrated by these additional tests:</p>\n<pre><code>&gt;&gt;&gt; is_palindrome(&quot;o̅o&quot;) # o+overline, o\nFalse\n&gt;&gt;&gt; is_palindrome(&quot;o̅o̅&quot;) # o+overline, o+overline\nTrue\n</code></pre>\n<p>Both of these fail, because we reverse the string by treating each Unicode character independently, rather than considering them as (possibly multi-character) letters. To fix that, we'll need to find or create a combining-character-aware function to reverse a string - I'm not aware of such a thing in the Python standard library.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T01:37:13.910", "Id": "463250", "Score": "0", "body": "Yeah im a beginner if you can't already tell lol but I mean the program is still working and putting out positive results but I guess I need to make it more clearer and organized" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T17:59:46.710", "Id": "236367", "ParentId": "236360", "Score": "9" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T16:34:19.933", "Id": "236360", "Score": "7", "Tags": [ "python", "palindrome" ], "Title": "Python palindrome program" }
236360
<p>Just looking for advice/thoughts on the overall AccountModal and how its written. looking to achieve better written, more legible, less repetitive code, more concise, cleaner etc...</p> <p>AccountScreen.js:</p> <pre><code>import React from 'react'; import { StyleSheet, ScrollView, View, Dimensions, Image } from 'react-native'; import * as Colors from '../assets/colors'; import * as Components from '../components'; import { onProfileChange } from '../actions/Profile'; import { TouchableOpacity } from 'react-native-gesture-handler'; import { connect } from 'react-redux'; const { width } = Dimensions.get('window'); class AccountScreen extends React.Component { constructor (props) { super(props); this.state = { visible: false, modalType: null, modalData: '' }; this.listener = props.onProfileChange(this.props.email); } setModal = (type) =&gt; { this.setState({ visible: !this.state.visible, modalType: type, modalData: this.props[type] }); }; renderConditionalOptions = () =&gt; { if (this.props.role === 'a') { return ( &lt;View&gt; {this.props.activated !== true ? ( &lt;TouchableOpacity style={{ padding: width * 0.05, borderBottomWidth: 1, borderBottomColor: Colors.PRIMARY_OFF_WHITE }} onPress={() =&gt; this.setModal('activate')} &gt; &lt;Components.BodyText style={{ fontSize: 18 }} text={'Activate/De-Activate'} /&gt; &lt;/TouchableOpacity&gt; ) : null} &lt;TouchableOpacity style={{ padding: width * 0.05, borderBottomWidth: 1, borderBottomColor: Colors.PRIMARY_OFF_WHITE }} onPress={() =&gt; this.setModal('adultRated')} &gt; &lt;Components.BodyText style={{ fontSize: 18 }} text={'Change Content Rating'} /&gt; &lt;/TouchableOpacity&gt; &lt;TouchableOpacity style={{ padding: width * 0.05, borderBottomWidth: 1, borderBottomColor: Colors.PRIMARY_OFF_WHITE }} onPress={() =&gt; this.setModal('categories')} &gt; &lt;Components.BodyText style={{ fontSize: 18 }} text={'Modify Categories'} /&gt; &lt;/TouchableOpacity&gt; &lt;TouchableOpacity style={{ padding: width * 0.05, borderBottomWidth: 1, borderBottomColor: Colors.PRIMARY_OFF_WHITE }} onPress={() =&gt; this.verificationProcess} &gt; &lt;Components.BodyText style={{ fontSize: 18 }} text={'Get Verified'} /&gt; &lt;/TouchableOpacity&gt; &lt;/View&gt; ); } }; render () { return ( &lt;ScrollView style={styles.container}&gt; {/* HEADER CONTAINER CONTAINER */} &lt;View style={styles.headerContainer}&gt; {/* IMG / NAME ROW */} &lt;View style={{ justifyContent: 'space-evenly', alignItems: 'center', flexDirection: 'row' }}&gt; &lt;TouchableOpacity onPress={() =&gt; this.setModal('profileImg')} style={{ alignItems: 'center', justifyContent: 'center', borderColor: Colors.PRIMARY_GREEN, borderWidth: 5, borderRadius: width * 0.7, backgroundColor: Colors.PRIMARY_OFF_WHITE, width: width * 0.35, height: width * 0.35 }} &gt; &lt;Image style={{ borderRadius: width * 0.5, height: width * 0.33, width: width * 0.33 }} source={ this.props.profileImg != '' ? ( { uri: this.props.profileImg } ) : ( require('../assets/img/white-user.png') ) } resizeMode={'contain'} /&gt; &lt;/TouchableOpacity&gt; &lt;View style={{ alignItems: 'center' }}&gt; &lt;Components.BodyText text={this.props.legalName} style={{ fontSize: 22, fontWeight: 'bold', marginTop: width * 0.01 }} /&gt; {/* Edit Username */} &lt;TouchableOpacity onPress={() =&gt; this.setModal('username')} style={{ borderWidth: 1, borderColor: Colors.PRIMARY_OFF_WHITE, borderRadius: width, paddingHorizontal: width * 0.025, paddingVertical: width * 0.015, marginTop: width * 0.01 }} &gt; &lt;Components.BodyText text={'@' + this.props.username} style={{ textAlign: 'center', fontSize: 16 }} /&gt; &lt;/TouchableOpacity&gt; &lt;/View&gt; &lt;/View&gt; &lt;/View&gt; {/* LOWER CONTAINER */} &lt;View style={{ borderTopLeftRadius: 25, borderTopRightRadius: 25, borderBottomLeftRadius: 25, borderBottomRightRadius: 25, backgroundColor: 'white', width: width, marginBottom: width * 0.05 }} &gt; &lt;TouchableOpacity style={{ padding: width * 0.05, borderBottomWidth: 1, borderBottomColor: Colors.PRIMARY_OFF_WHITE }} onPress={() =&gt; this.setModal('email')} &gt; &lt;Components.BodyText text={'Update Email'} style={{ fontSize: 18 }} /&gt; &lt;/TouchableOpacity&gt; &lt;TouchableOpacity style={{ padding: width * 0.05, borderBottomWidth: 1, borderBottomColor: Colors.PRIMARY_OFF_WHITE }} onPress={() =&gt; this.setModal('password')} &gt; &lt;Components.BodyText style={{ fontSize: 18 }} text={'Change Password'} /&gt; &lt;/TouchableOpacity&gt; &lt;TouchableOpacity style={{ padding: width * 0.05, borderBottomWidth: 1, borderBottomColor: Colors.PRIMARY_OFF_WHITE }} onPress={() =&gt; this.setModal('phoneNumber')} &gt; &lt;Components.BodyText style={{ fontSize: 18 }} text={'Update Phone Number'} /&gt; &lt;/TouchableOpacity&gt; {/* CONDITIONAL OPTIONS */} {this.renderConditionalOptions()} &lt;/View&gt; {this.state.visible === true ? ( &lt;Components.AccountModal visible={this.state.visible} data={this.state.modalData} type={this.state.modalType} closeModal={this.setModal} navigation={this.props.navigation} /&gt; ) : null} &lt;/ScrollView&gt; ); } } const styles = StyleSheet.create({ container: { flex: 1, //justifyContent: 'space-between', backgroundColor: Colors.PRIMARY_OFF_WHITE }, headerContainer: { borderBottomLeftRadius: 25, borderBottomRightRadius: 25, width: width, backgroundColor: 'white', shadowColor: '#333', shadowOffset: { width: 3, height: 3 }, shadowOpacity: 0.5, shadowRadius: 10, elevation: 15, paddingVertical: width * 0.05, marginBottom: 30 } }); const mapStateToProps = ({ profile }) =&gt; { const { role, activated, profileImg, legalName, username, email, phoneNumber, bio, adultRated, categories, verified } = profile; return { role, activated, profileImg, legalName, username, email, phoneNumber, bio, adultRated, categories, verified }; }; const mapDispatchToProps = { onProfileChange }; export default connect(mapStateToProps, mapDispatchToProps)(AccountScreen); </code></pre> <p>AccountModal.js:</p> <pre><code>//imports removed for brevity const { height, width } = Dimensions.get('window'); class AccountModal extends React.Component { constructor (props) { super(props); this.state = { rating: null, visible: props.visible, text: '', text2: '', showInput: false, type: '', img: '', categories: props.categories != null ? props.categories : [] }; } componentDidMount () { let first = this.props.type[0]; this.setState({ type: this.props.type.replace(/^./, first.toUpperCase()) }); } format = (input) =&gt; { let trimmed = input; trimmed = trimmed.includes(' ') ? trimmed.replace(' ', '-') : trimmed; return (trimmed = trimmed[0].toUpperCase() + trimmed.substring(1)); }; openImgPicker = () =&gt; { ImagePicker.openPicker({ width: 150, height: 150, cropping: true, cropperToolbarTitle: 'Pinch/Zoom to Crop Image', cropperCircleOverlay: true }).then((img) =&gt; { this.setState({ img: img.path }); }); }; addCategory = () =&gt; { let trimmed = this.format(this.state.text); this.setState({ categories: [ ...this.state.categories, trimmed ] }); this.refs.input.clear(); }; closeModal = () =&gt; { this.props.closeModal(); this.refs.input.clear(); this.props.resetInfo(); }; onSave = (type) =&gt; { switch (type) { case 'Bio': this.props.updateBio(this.props.docId, this.state.text); break; case 'Username': this.props.updateUsername(this.props.docId, this.state.text); break; case 'Email': this.props.updateEmail(this.props.docId, this.state.text); break; case 'Categories': this.props.updateCategories(this.props.docId, this.state.categories); break; case 'AdultRated': this.props.updateAdultRated(this.props.docId, this.state.rating); break; case 'ProfileImg': this.props.updateProfileImg({ uid: this.props.user.uid, id: this.props.docId, uri: this.state.img, url: this.props.profileImg }); break; case 'PhoneNumber': this.props.sendVerificationCode(this.state.text); this.refs.input.clear(); break; case 'ConfirmCode': this.props.compareCode( { id: this.props.verificationId, inputCode: this.state.text }, this.props.docId, this.props.phoneNumber ); case 'Verified': case 'Activate': case 'Deactivate': } }; renderModal = () =&gt; { switch (this.state.type) { case 'Bio': case 'Username': case 'Email': case 'Verified': return ( &lt;Modal visible={this.state.visible} transparent={true} animationType={'slide'} onRequestClose={() =&gt; this.closeModal} &gt; &lt;View style={styles.modalContainer}&gt; &lt;Components.BodyText text={this.state.type + ':'} style={{ color: 'white', fontSize: 20, fontWeight: 'bold', textAlign: 'center', marginBottom: 5 }} /&gt; &lt;Components.BodyText text={ this.state.type === 'Selfie' ? ( '$' + this.props.selfie + ' per selfie or screenshot' ) : this.state.type === 'Video' || this.state.type === 'Voice' ? ( '$ ' + this.props[this.props.type] + ' per 5 minutes' ) : ( this.props[this.props.type] ) } style={{ fontSize: 14, marginBottom: 20, color: 'white', textAlign: 'center' }} /&gt; &lt;Components.TransparentInput placeholder={'Edit...'} placeholderColor={'white'} style={{ borderRadius: 20, justifyContent: 'center', height: this.props.type === 'bio' ? width * 0.25 : width * 0.1, width: width * 0.6, marginBottom: 10, padding: 5 }} ref={'input'} multiline={this.props.type === 'bio' ? true : false} onChangeText={(text) =&gt; { this.setState({ text: text.trim() }); }} /&gt; {this.props.info != '' ? ( &lt;Components.BodyText text={this.props.info} fontSize={14} style={{ color: 'white' }} /&gt; ) : null} &lt;ActivityIndicator animating={this.props.loading} color={Colors.PRIMARY_GREEN} size={'small'} /&gt; // For specific firebase error forcing re-authentication {this.props.info.includes('sensitive') ? ( &lt;Components.Button text={'Re-Authenticate'} type={'alert'} onPress={() =&gt; this.props.navigation.navigate('Login')} /&gt; ) : null} &lt;View style={{ flexDirection: 'row', justifyContent: 'space-evenly', marginTop: 10 }}&gt; &lt;Components.Button onPress={() =&gt; this.closeModal()} type={'secondary'} text={'Close'} fontSize={16} style={{ marginRight: 20 }} /&gt; &lt;Components.Button onPress={() =&gt; this.onSave(this.state.type)} type={'primary'} text={'Save'} fontSize={16} /&gt; &lt;/View&gt; &lt;/View&gt; &lt;/Modal&gt; ); case 'ProfileImg': return ( &lt;Modal visible={this.state.visible} transparent={true} animationType={'slide'} onRequestClose={() =&gt; this.closeModal} &gt; &lt;View style={styles.modalContainer}&gt; &lt;TouchableOpacity onPress={this.openImgPicker} style={[ styles.transparentTouchable, { marginVertical: 20 } ]} &gt; &lt;Components.BodyText text={this.state.img != '' ? 'Image selected' : 'Tap to Select Image'} style={{ color: 'white', fontWeight: 'bold' }} /&gt; &lt;/TouchableOpacity&gt; {this.props.info != '' ? ( &lt;Components.BodyText text={this.props.info} fontSize={14} style={{ color: 'white' }} /&gt; ) : null} &lt;ActivityIndicator animating={this.props.loading} color={Colors.PRIMARY_GREEN} size={'small'} /&gt; &lt;View style={{ flexDirection: 'row', justifyContent: 'space-evenly', marginTop: 10 }}&gt; &lt;Components.Button onPress={() =&gt; this.closeModal()} type={'secondary'} text={'Close'} fontSize={16} style={{ marginRight: 20 }} /&gt; &lt;Components.Button onPress={() =&gt; this.onSave(this.state.type)} type={'primary'} text={'Save'} fontSize={16} /&gt; &lt;/View&gt; &lt;/View&gt; &lt;/Modal&gt; ); case 'AdultRated': return ( &lt;Modal visible={this.state.visible} transparent={true} animationType={'slide'} onRequestClose={() =&gt; this.setState({ visible: false })} &gt; &lt;View style={styles.modalContainer}&gt; &lt;Components.BodyText text={ this.state.rating == null ? ( 'Your current Adult Content rating: ' + '\n' + this.props.data ) : ( "You're about to set Adult-Rated for: " + '\n' + this.state.rating ) } style={{ color: 'white', textAlign: 'center', fontWeight: 'bold', fontSize: 16 }} /&gt; &lt;Components.Button onPress={() =&gt; this.setState({ rating: true })} type={'alert'} text={'Set for Adults'} fontSize={16} style={{ margin: 15 }} /&gt; &lt;Components.Button onPress={() =&gt; this.setState({ rating: false })} type={'alert'} text={'Set for Everyone'} fontSize={16} style={{ margin: 15 }} /&gt; {this.props.info != '' ? ( &lt;Components.BodyText text={this.props.info} fontSize={14} style={{ color: 'white' }} /&gt; ) : null} &lt;ActivityIndicator animating={this.props.loading} color={Colors.PRIMARY_GREEN} size={'small'} /&gt; &lt;View style={{ flexDirection: 'row', justifyContent: 'space-evenly', marginTop: 15 }}&gt; &lt;Components.Button onPress={() =&gt; this.setState({ visible: false })} type={'secondary'} text={'Close'} fontSize={16} style={{ marginRight: 20 }} /&gt; &lt;Components.Button onPress={() =&gt; this.onSave(this.state.type)} type={'primary'} text={'Save'} fontSize={16} /&gt; &lt;/View&gt; &lt;/View&gt; &lt;/Modal&gt; ); case 'Categories': return ( &lt;Modal visible={this.state.visible} transparent={true} animationType={'slide'} onRequestClose={() =&gt; this.setState({ visible: false })} &gt; &lt;View style={styles.modalContainer}&gt; &lt;Components.BodyText text={this.state.type + ':'} style={{ color: 'white', fontSize: 20, fontWeight: 'bold', textAlign: 'center' }} /&gt; &lt;Components.BodyText text={'Tap a category to delete'} style={{ color: 'white', fontSize: 12, textAlign: 'center', marginBottom: 20 }} /&gt; &lt;FlatList data={this.state.categories} style={{ marginVertical: 20 }} horizontal={false} numColumns={2} keyExtractor={(item) =&gt; { return ( item.toString() + new Date().getTime().toString() + Math.floor(Math.random() * Math.floor(new Date().getTime())).toString() ); }} renderItem={({ item, index }) =&gt; ( &lt;TouchableOpacity onPress={() =&gt; { this.setState({ categories: this.state.categories.filter((category) =&gt; { if (item != category) { return true; } else { return false; } }) }); }} style={styles.transparentTouchable} &gt; &lt;Components.BodyText text={index + 1 + '. ' + item} style={{ fontSize: 16, color: 'white' }} /&gt; &lt;/TouchableOpacity&gt; )} /&gt; &lt;View style={{ flexDirection: 'row', justifyContent: 'space-evenly', marginTop: 25, marginBottom: 15, alignItems: 'center' }} &gt; &lt;Components.TransparentInput placeholder={'Add a category...'} placeholderColor={'white'} style={{ height: width * 0.1, width: width * 0.33, marginRight: 20 }} onChangeText={(text) =&gt; { this.setState({ text }); }} returnKeyType={'done'} onSubmitEditing={() =&gt; this.addCategory()} ref={'input'} /&gt; &lt;TouchableOpacity onPress={() =&gt; { this.addCategory(); }} &gt; &lt;Image source={require('../assets/img/white-plus.png')} resizeMode={'contain'} style={{ height: width * 0.09, width: width * 0.09 }} /&gt; &lt;/TouchableOpacity&gt; &lt;/View&gt; {this.props.info != '' ? ( &lt;Components.BodyText text={this.props.info} fontSize={14} style={{ color: 'white' }} /&gt; ) : null} &lt;ActivityIndicator animating={this.props.loading} color={Colors.PRIMARY_GREEN} size={'small'} /&gt; &lt;View style={{ flexDirection: 'row', justifyContent: 'space-evenly', marginTop: 15 }}&gt; &lt;Components.Button onPress={() =&gt; this.closeModal()} type={'secondary'} text={'Close'} fontSize={16} style={{ marginRight: 20 }} /&gt; &lt;Components.Button onPress={() =&gt; this.onSave(this.state.type)} type={'primary'} text={'Save'} fontSize={16} /&gt; &lt;/View&gt; &lt;/View&gt; &lt;/Modal&gt; ); case 'Activate': return ( &lt;Modal visible={this.state.visible} transparent={true} animationType={'slide'} onRequestClose={() =&gt; this.closeModal} &gt; &lt;View style={styles.modalContainer}&gt; &lt;Components.BodyText text={this.state.type + ' your account'} style={{ color: 'white', fontSize: 20, fontWeight: 'bold', textAlign: 'center', marginBottom: 5 }} /&gt; &lt;Components.BodyText text={ 'Profile must be complete to activate account. Activation status determines whether profile is accessbile in the Discover section' } style={{ color: 'white', fontSize: 14, textAlign: 'center', marginBottom: 5 }} /&gt; {this.props.info != '' ? ( &lt;Components.BodyText text={this.props.info} fontSize={14} style={{ color: 'white' }} /&gt; ) : null} &lt;ActivityIndicator animating={this.props.loading} color={Colors.PRIMARY_GREEN} size={'small'} /&gt; &lt;View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginBottom: 15 }} &gt; &lt;Components.Button onPress={() =&gt; this.onSave('Deactivate')} type={'action'} text={'De-Activate'} fontSize={16} style={{ marginRight: 20, height: width * 0.1 }} /&gt; &lt;Components.Button onPress={() =&gt; this.onSave(this.state.type)} type={'primary'} text={'Activate'} fontSize={16} style={{ height: width * 0.1 }} /&gt; &lt;/View&gt; &lt;Components.Button onPress={() =&gt; this.closeModal()} type={'secondary'} text={'Close'} fontSize={16} style={{ height: width * 0.1 }} /&gt; &lt;/View&gt; &lt;/Modal&gt; ); case 'Password': return ( &lt;Modal visible={this.state.visible} transparent={true} animationType={'slide'} onRequestClose={() =&gt; this.closeModal} &gt; &lt;View style={styles.modalContainer}&gt; &lt;Components.BodyText text={'Reset Password'} style={{ color: 'white', fontWeight: 'bold', fontSize: 18, textAlign: 'center' }} /&gt; {this.props.info != '' ? ( &lt;Components.BodyText text={this.props.info} fontSize={14} style={{ color: 'white', textAlign: 'center', marginVertical: 20 }} /&gt; ) : null} &lt;ActivityIndicator animating={this.props.loading} color={Colors.PRIMARY_GREEN} size={'small'} /&gt; &lt;View style={{ flexDirection: 'row', justifyContent: 'space-evenly', marginTop: 10 }}&gt; &lt;Components.Button onPress={() =&gt; this.closeModal()} type={'secondary'} text={'Close'} fontSize={16} style={{ marginRight: 20 }} /&gt; &lt;Components.Button onPress={() =&gt; this.props.sendPwdLink(this.props.email)} type={'primary'} text={'Reset'} fontSize={16} /&gt; &lt;/View&gt; &lt;/View&gt; &lt;/Modal&gt; ); case 'PhoneNumber': return ( &lt;Modal visible={this.state.visible} transparent={true} animationType={'slide'} onRequestClose={() =&gt; this.closeModal} &gt; &lt;View style={styles.modalContainer}&gt; &lt;Components.BodyText text={'Update Phone Number'} style={{ color: 'white', fontWeight: 'bold', fontSize: 20 }} /&gt; {this.props.verificationId == null ? ( &lt;View style={{ alignItems: 'center' }}&gt; &lt;Components.TransparentInput placeholder={'Enter new phone number'} placeholderColor={'white'} style={{ height: width * 0.1, width: width * 0.45, marginTop: 20, marginBottom: 5 }} onChangeText={(text) =&gt; { this.setState({ text: text.trim() }); }} returnKeyType={'done'} ref={'input'} /&gt; &lt;Components.BodyText text={ "Remember to include a '+', your country code, followed by your number. No spaces or hyphens." } style={{ color: 'white', textAlign: 'center', paddingHorizontal: 20 }} /&gt; {this.props.info != '' ? ( &lt;Components.BodyText text={this.props.info} fontSize={14} style={{ marginTop: 25, color: 'white' }} /&gt; ) : null} &lt;ActivityIndicator animating={this.props.loading} color={Colors.PRIMARY_GREEN} size={'small'} /&gt; &lt;View style={{ flexDirection: 'row', justifyContent: 'space-evenly', marginTop: 15 }} &gt; &lt;Components.Button onPress={() =&gt; this.closeModal()} type={'secondary'} text={'Close'} fontSize={16} style={{ marginRight: 20 }} /&gt; &lt;Components.Button onPress={() =&gt; { this.onSave(this.state.type); }} type={'primary'} text={'Send Code'} fontSize={16} /&gt; &lt;/View&gt; &lt;/View&gt; ) : ( &lt;View style={{ alignItems: 'center' }}&gt; &lt;Components.TransparentInput placeholder={'Enter confirmation code'} placeholderColor={'white'} style={{ height: width * 0.1, width: width * 0.45 }} onChangeText={(text) =&gt; { this.setState({ text: text.trim() }); }} returnKeyType={'done'} ref={'input'} /&gt; {this.props.info != '' ? ( &lt;Components.BodyText text={this.props.info} fontSize={14} style={{ color: 'white' }} /&gt; ) : null} &lt;ActivityIndicator animating={this.props.loading} color={Colors.PRIMARY_GREEN} size={'small'} /&gt; &lt;View style={{ flexDirection: 'row', justifyContent: 'space-evenly', marginTop: 15 }} &gt; &lt;Components.Button onPress={() =&gt; this.closeModal()} type={'secondary'} text={'Close'} fontSize={16} style={{ marginRight: 20 }} /&gt; &lt;Components.Button onPress={() =&gt; this.onSave('ConfirmCode')} type={'primary'} text={'Confirm Code'} fontSize={16} /&gt; &lt;/View&gt; &lt;/View&gt; )} &lt;/View&gt; &lt;/Modal&gt; ); } }; render () { return &lt;View&gt;{this.renderModal()}&lt;/View&gt;; } } const styles = StyleSheet.create({ modalContainer: { width: width * 0.8, backgroundColor: Colors.PRIMARY_DARK, borderRadius: 20, borderWidth: 2, borderColor: Colors.PRIMARY_GREEN, alignItems: 'center', alignSelf: 'center', shadowColor: '#333', shadowOffset: { width: 30, height: 30 }, shadowOpacity: 0.9, shadowRadius: 30, elevation: 15, position: 'absolute', top: height * 0.25, paddingTop: 15, paddingBottom: 25 }, transparentTouchable: { margin: 5, borderWidth: 1, borderColor: Colors.PRIMARY_OFF_WHITE, borderRadius: width, paddingHorizontal: width * 0.025, paddingVertical: width * 0.015 } }); const mapDispatchToProps = { updateBio, resetInfo, updateUsername, updateEmail, updateCategories, updateAdultRated, updateProfileImg, updatePassword, sendPwdLink, sendVerificationCode, compareCode }; const mapStateToProps = ({ profile, auth }) =&gt; { const { activated, profileImg, legalName, username, email, phoneNumber, bio, adultRated, categories, verified, info, loading, docId, selfie, video, voice, verificationId } = profile; const { user, error } = auth; return { activated, profileImg, legalName, username, email, phoneNumber, bio, adultRated, categories, verified, info, user, loading, docId, selfie, video, voice, error, verificationId }; }; export default connect(mapStateToProps, mapDispatchToProps)(AccountModal); </code></pre>
[]
[ { "body": "<ul>\n<li>We can create a method to serve dynamically the redundant <code>TouchableOpacity</code> block as below:</li>\n</ul>\n<pre class=\"lang-js prettyprint-override\"><code>&lt;TouchableOpacity\n style={{\n padding: width * 0.05,\n borderBottomWidth: 1,\n borderBottomColor: Colors.PRIMARY_OFF_WHITE\n }}\n onPress={() =&gt; this.setModal(setModal)}\n &gt;\n &lt;Components.BodyText style={{ fontSize: 18 }} text={textContent} /&gt;\n &lt;/TouchableOpacity&gt;\n</code></pre>\n<ul>\n<li>Destructuring the <code>State</code> and <code>Props</code> using ES6 destructuring.</li>\n</ul>\n<pre><code>const {visible, modalData, modalType} = this.state;\nconst {navigation} = this.props;\n</code></pre>\n<ul>\n<li>To keep <code>main</code> render clean we can further extract the <code>IMG</code>, <code>ROW</code> JSX into a method <code>__renderImgNameRow</code></li>\n</ul>\n<pre class=\"lang-js prettyprint-override\"><code>import React from 'react';\nimport { StyleSheet, ScrollView, View, Dimensions, Image } from 'react-native';\nimport * as Colors from '../assets/colors';\nimport * as Components from '../components';\nimport { onProfileChange } from '../actions/Profile';\nimport { TouchableOpacity } from 'react-native-gesture-handler';\nimport { connect } from 'react-redux';\nconst { width } = Dimensions.get('window');\n\nclass AccountScreen extends React.Component {\n constructor (props) {\n super(props);\n this.state = {\n visible: false,\n modalType: null,\n modalData: ''\n };\n this.listener = props.onProfileChange(this.props.email);\n }\n setModal = (type) =&gt; {\n this.setState({ visible: !this.state.visible, modalType: type, modalData: this.props[type] });\n };\n renderConditionalOptions = () =&gt; {\n if (this.props.role === 'a') {\n return (\n &lt;View&gt;\n {this.props.activated !== true ? (\n this.__renderLowerTouchables('activate', 'Activate/De-Activate')\n ) : null}\n {this.__renderLowerTouchables('adultRated', 'Change Content Rating')}\n {this.__renderLowerTouchables('categories', 'Modify Categories')}\n\n &lt;TouchableOpacity\n style={{\n padding: width * 0.05,\n borderBottomWidth: 1,\n borderBottomColor: Colors.PRIMARY_OFF_WHITE\n }}\n onPress={() =&gt; this.verificationProcess}\n &gt;\n &lt;Components.BodyText style={{ fontSize: 18 }} text={'Get Verified'} /&gt;\n &lt;/TouchableOpacity&gt;\n &lt;/View&gt;\n );\n }\n };\n\n __renderLowerTouchables = (setModal, textContent) =&gt; {\n return (\n &lt;TouchableOpacity\n style={{\n padding: width * 0.05,\n borderBottomWidth: 1,\n borderBottomColor: Colors.PRIMARY_OFF_WHITE\n }}\n onPress={() =&gt; this.setModal(setModal)}\n &gt;\n &lt;Components.BodyText style={{ fontSize: 18 }} text={textContent} /&gt;\n &lt;/TouchableOpacity&gt;\n )\n }\n\n __renderImgNameRow = () =&gt; {\n return (\n &lt;View style={{ justifyContent: 'space-evenly', alignItems: 'center', flexDirection: 'row' }}&gt;\n &lt;TouchableOpacity\n onPress={() =&gt; this.setModal('profileImg')}\n style={{\n alignItems: 'center',\n justifyContent: 'center',\n borderColor: Colors.PRIMARY_GREEN,\n borderWidth: 5,\n borderRadius: width * 0.7,\n backgroundColor: Colors.PRIMARY_OFF_WHITE,\n width: width * 0.35,\n height: width * 0.35\n }}\n &gt;\n &lt;Image\n style={{ borderRadius: width * 0.5, height: width * 0.33, width: width * 0.33 }}\n source={\n this.props.profileImg != '' ? (\n { uri: this.props.profileImg }\n ) : (\n require('../assets/img/white-user.png')\n )\n }\n resizeMode={'contain'}\n /&gt;\n &lt;/TouchableOpacity&gt;\n\n &lt;View style={{ alignItems: 'center' }}&gt;\n &lt;Components.BodyText\n text={this.props.legalName}\n style={{\n fontSize: 22,\n fontWeight: 'bold',\n marginTop: width * 0.01\n }}\n /&gt;\n {/* Edit Username */}\n &lt;TouchableOpacity\n onPress={() =&gt; this.setModal('username')}\n style={{\n borderWidth: 1,\n borderColor: Colors.PRIMARY_OFF_WHITE,\n borderRadius: width,\n paddingHorizontal: width * 0.025,\n paddingVertical: width * 0.015,\n marginTop: width * 0.01\n }}\n &gt;\n &lt;Components.BodyText\n text={'@' + this.props.username}\n style={{ textAlign: 'center', fontSize: 16 }}\n /&gt;\n &lt;/TouchableOpacity&gt;\n &lt;/View&gt;\n &lt;/View&gt;\n )\n }\n\n render () {\n const {visible, modalData, modalType} = this.state;\n const {navigation} = this.props;\n return (\n &lt;ScrollView style={styles.container}&gt;\n {/* HEADER CONTAINER CONTAINER */}\n &lt;View style={styles.headerContainer}&gt;\n {/* IMG / NAME ROW */}\n {__renderImgNameRow()}\n &lt;/View&gt;\n {/* LOWER CONTAINER */}\n &lt;View\n style={style.lowerContainer}\n &gt;\n {this.__renderLowerTouchables('email', 'Update Email')}\n {this.__renderLowerTouchables('password', 'Change Password')}\n {this.__renderLowerTouchables('phoneNumber', 'Update Phone Number')}\n {/* CONDITIONAL OPTIONS */}\n {this.renderConditionalOptions()}\n &lt;/View&gt;\n\n {visible &amp;&amp; (\n &lt;Components.AccountModal\n visible={visible}\n data={modalData}\n type={modalType}\n closeModal={this.setModal}\n navigation={navigation}\n /&gt;\n )}\n &lt;/ScrollView&gt;\n );\n }\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n //justifyContent: 'space-between',\n backgroundColor: Colors.PRIMARY_OFF_WHITE\n },\n headerContainer: {\n borderBottomLeftRadius: 25,\n borderBottomRightRadius: 25,\n width: width,\n backgroundColor: 'white',\n shadowColor: '#333',\n shadowOffset: {\n width: 3,\n height: 3\n },\n shadowOpacity: 0.5,\n shadowRadius: 10,\n elevation: 15,\n paddingVertical: width * 0.05,\n marginBottom: 30\n },\n lowerContainer: {\n borderTopLeftRadius: 25,\n borderTopRightRadius: 25,\n borderBottomLeftRadius: 25,\n borderBottomRightRadius: 25,\n backgroundColor: 'white',\n width: width,\n marginBottom: width * 0.05\n }\n});\n\nconst mapStateToProps = ({ profile }) =&gt; {\n const {\n role,\n activated,\n profileImg,\n legalName,\n username,\n email,\n phoneNumber,\n bio,\n adultRated,\n categories,\n verified\n } = profile;\n\n return {\n role,\n activated,\n profileImg,\n legalName,\n username,\n email,\n phoneNumber,\n bio,\n adultRated,\n categories,\n verified\n };\n};\n\nconst mapDispatchToProps = { onProfileChange };\n\nexport default connect(mapStateToProps, mapDispatchToProps)(AccountScreen);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-19T13:37:42.037", "Id": "485947", "Score": "2", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-19T12:37:20.410", "Id": "248135", "ParentId": "236365", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T17:42:30.210", "Id": "236365", "Score": "2", "Tags": [ "javascript", "design-patterns", "react.js" ], "Title": "React-Native Account screen with a modal for updating details" }
236365
<p>I'm trying to construct a simple database for use by 2 persons only (myself and other guy), right now, we're using excel table with 4 fields "requisition, origin date, request date and authorized date", but I want to take it to the next level :D. So, I'm building this small database app to emulate that, the file will be shared and I'm not worried about not being able to load the file if it's in use by him ( or viceversa). This database consists of 2 classes "Element" and "Records", element carries each row data, and records handles vectors of elements, it's the connection with the outer world for elements.</p> <p>I need help on this to know, if this is much code, or a little bit of code, or how can it be improved?, I'm not worried about speed or disk space or access time, this database will contain at much 5,000 records.</p> <p>Later on, this code will be used on winapi.</p> <p>This is the code, I'm using visual studio:</p> <p><strong>Element.h</strong></p> <pre><code>#pragma once #include &lt;cstdint&gt; #include &lt;ctime&gt; class Element { public: Element(uint32_t requi, time_t originDate, time_t requestDate, time_t authorizedDate, uint64_t amount, bool hasTax, bool authorized = false); void SetId(uint32_t id) { this-&gt;id = id; } uint32_t GetId() const { return id; } bool operator&lt;(const Element&amp; rhs) const { return requi &lt; rhs.requi; } uint32_t GetRequi() const { return requi; } time_t GetOriginDate() const { return originDate; } time_t GetRequestDate() const { return requestDate; } time_t GetAuthorizedDate() const { return authorizedDate; } uint64_t GetAmount() const { return amount; } bool IsTaxed() const { return hasTax; } bool IsAuthorized() const { return authorized; } bool operator&lt;(const Element&amp; rhs) { return requi &lt; rhs.requi; } bool operator&gt;(const Element&amp; rhs) { return requi &gt; rhs.requi; } bool operator==(const Element&amp; rhs) { return requi == rhs.requi; } void Authorize(); void Print(); private: uint32_t id; uint32_t requi; time_t originDate; time_t requestDate; time_t authorizedDate; uint64_t amount; bool hasTax; bool reviewed = true; bool authorized = false; }; </code></pre> <p><strong>Element.cpp</strong></p> <pre><code>#include "Element.h" #include &lt;iostream&gt; Element::Element(uint32_t requi, time_t originDate, time_t requestDate, time_t authorizedDate, uint64_t amount, bool hasTax, bool authorized) : requi(requi), originDate(originDate), requestDate(requestDate), authorizedDate(authorizedDate), amount(amount), hasTax(hasTax), authorized(authorized) { } void Element::Authorize() { std::time(&amp;authorizedDate); authorized = true; } void Element::Print() // not used at the moment { std::cout &lt;&lt; "Id: " &lt;&lt; id &lt;&lt; ", Requi: " &lt;&lt; requi &lt;&lt; ", Monto: $ " &lt;&lt; amount &lt;&lt; std::endl; } </code></pre> <p><strong>Records.h</strong></p> <pre><code>#pragma once #include &lt;string&gt; #include &lt;vector&gt; #include "Element.h" class Records { public: friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const Element&amp; rhs) { out &lt;&lt; "Id: " &lt;&lt; rhs.GetId() &lt;&lt; ", Requi: " &lt;&lt; rhs.GetRequi() &lt;&lt; ", Monto: $ " &lt;&lt; int(rhs.GetAmount() / 100) &lt;&lt; "." &lt;&lt; int(rhs.GetAmount() % 100) &lt;&lt; (rhs.IsTaxed() ? " mas IVA":" neto (no aplica IVA)"); return out; } void Insert(Element&amp; element); void SaveToFile(); void LoadFromFile(); void ListRequi(); private: std::vector&lt;Element&gt; elements; unsigned int nRecords = 0; }; </code></pre> <p><strong>Records.cpp</strong></p> <pre><code>#include "Records.h" #include &lt;cassert&gt; #include &lt;fstream&gt; #include &lt;algorithm&gt; #include &lt;iterator&gt; #include &lt;iostream&gt; void Records::Insert(Element &amp; element) { //autoincrement record count and use it as indes (id) element.SetId(++nRecords); elements.emplace_back(element); } void Records::SaveToFile() { std::ofstream file("datos.txt", std::ios::binary); assert(file); if (file) { nRecords = (unsigned int)elements.size(); file.write(reinterpret_cast&lt;char*&gt;(&amp;nRecords), sizeof(nRecords) ); if (nRecords &gt; 0) { for (auto&amp; e : elements) { uint32_t tmpId = e.GetId(); uint32_t tmpRequi = e.GetRequi(); time_t tmpOrigin = e.GetOriginDate(); time_t tmpRequest = e.GetRequestDate(); time_t tmpAuth = e.GetAuthorizedDate(); uint64_t tmpAmount = e.GetAmount(); bool tmpTaxed = e.IsTaxed(); bool tmoAuthorized = e.IsAuthorized(); file.write(reinterpret_cast&lt;char*&gt;(&amp;tmpId), sizeof(tmpId)); file.write(reinterpret_cast&lt;char*&gt;(&amp;tmpRequi), sizeof(tmpRequi)); file.write(reinterpret_cast&lt;char*&gt;(&amp;tmpOrigin), sizeof(tmpOrigin)); file.write(reinterpret_cast&lt;char*&gt;(&amp;tmpRequest), sizeof(tmpRequest)); file.write(reinterpret_cast&lt;char*&gt;(&amp;tmpAuth), sizeof(tmpAuth)); file.write(reinterpret_cast&lt;char*&gt;(&amp;tmpAmount), sizeof(tmpAmount)); file.write(reinterpret_cast&lt;char*&gt;(&amp;tmpTaxed), sizeof(tmpTaxed)); file.write(reinterpret_cast&lt;char*&gt;(&amp;tmoAuthorized), sizeof(tmoAuthorized)); } } } } void Records::LoadFromFile() { std::ifstream file("datos.txt", std::ios::binary); assert(file); if (file) { unsigned int nTmpRecords = 0; nRecords = 0; file.read(reinterpret_cast&lt;char*&gt;(&amp;nTmpRecords), sizeof(nTmpRecords)); if (nTmpRecords &gt; 0) { elements.clear(); for (unsigned int i = 0; i &lt; nTmpRecords &amp;&amp; file.good(); ++i) { uint32_t tmpId = 0; uint32_t tmpRequi = 0; time_t tmpOrigin = 0; time_t tmpRequest = 0; time_t tmpAuth = 0; uint64_t tmpAmount = 0; bool tmpTaxed; bool tmpAuthorized; file.read(reinterpret_cast&lt;char*&gt;(&amp;tmpId), sizeof(tmpId)); file.read(reinterpret_cast&lt;char*&gt;(&amp;tmpRequi), sizeof(tmpRequi)); file.read(reinterpret_cast&lt;char*&gt;(&amp;tmpOrigin), sizeof(tmpOrigin)); file.read(reinterpret_cast&lt;char*&gt;(&amp;tmpRequest), sizeof(tmpRequest)); file.read(reinterpret_cast&lt;char*&gt;(&amp;tmpAuth), sizeof(tmpAuth)); file.read(reinterpret_cast&lt;char*&gt;(&amp;tmpAmount), sizeof(tmpAmount)); file.read(reinterpret_cast&lt;char*&gt;(&amp;tmpTaxed), sizeof(tmpTaxed)); file.read(reinterpret_cast&lt;char*&gt;(&amp;tmpAuthorized), sizeof(tmpAuthorized)); Element tmpElement(tmpRequi, tmpOrigin, tmpRequest, tmpAuth, tmpAmount, tmpTaxed, tmpAuthorized); tmpElement.SetId(tmpId); elements.emplace_back(tmpElement); } } } } void Records::ListRequi() { if (elements.size() &gt; 0) { std::sort(elements.begin(), elements.end()); //test code //auto result = std::find_if(elements.begin(), elements.end(), // [](const Element&amp; e) // { // return e.GetId() == 2; // }); //if (result != elements.end()) //{ // std::cout &lt;&lt; result-&gt;GetRequi() &lt;&lt; std::endl; //} std::copy(elements.begin(), elements.end(), std::ostream_iterator&lt;Element&gt;(std::cout, "\n") ); } } </code></pre> <p>This is just to test the database app, it will save to a file named "datos.txt".</p> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include "Records.h" #include &lt;algorithm&gt; #include &lt;ctime&gt; int main() { //test code to insert elements to records and save to file { time_t tRequest = 0; time_t tElaboration = 0; // get today's date and time std::time(&amp;tRequest); std::time(&amp;tElaboration); Records reg; reg.Insert(Element(22132, tElaboration, tRequest, 0, 1586450, true)); reg.Insert(Element(22340, tElaboration, tRequest, 0, 123490, false)); reg.Insert(Element(45398, tElaboration, tRequest, 0, 58674, true)); reg.Insert(Element(21518, tElaboration, tRequest, 0, 879965, true)); reg.SaveToFile(); std::cout &lt;&lt; "The following records has been saved: \n"; reg.ListRequi(); } std::cout &lt;&lt; "======================================\n"; //test code to load elements to memory from file { Records reg; reg.LoadFromFile(); std::cout &lt;&lt; "\nThe following records has been loaded \n"; reg.ListRequi(); } std::cin.get(); return 0; } </code></pre>
[]
[ { "body": "<h2>Serialisation</h2>\n\n<p>What you have is OK. It works, but your serialisation code is verbose, brittle, manual, and hard to maintain. </p>\n\n<p>This is a very common problem. Plenty of libraries out there, including this very good and <a href=\"https://github.com/google/libnop\" rel=\"nofollow noreferrer\">popular one from Google: libnop</a>. </p>\n\n<p>I refactored your code using that. The number of lines of code dropped significantly and became more robust and maintainable. See below:</p>\n\n<h2>Other notable changes</h2>\n\n<ul>\n<li><code>Insert(Element&amp;)</code> was broken, because it was not accepting rvalues. Added an overload</li>\n<li>The <code>friend operator&lt;&lt;()</code> for <code>Element</code> was in the wrong class. It was in <code>Records</code>. </li>\n<li>Added a default constuctor for <code>Element</code> because <code>libnop</code> needs it. This means you can potentially have an uninitialised object. Also the existing constructor left <code>id</code> uninitiliased. Give this some thought. </li>\n<li>I know this is subjective, but: code formatting. Yours was very \"verbose\". Consider the style you are using. </li>\n</ul>\n\n<pre><code>\n// Element.h\n\n#pragma once\n\n#include &lt;cstdint&gt;\n#include &lt;ctime&gt;\n#include &lt;nop/serializer.h&gt;\n\nclass Element {\npublic:\n Element() = default;\n\n Element(uint32_t requi, time_t originDate, time_t requestDate,\n time_t authorizedDate, uint64_t amount, bool hasTax,\n bool authorized = false);\n\n void SetId(uint32_t id) { this-&gt;id = id; }\n\n [[nodiscard]] uint32_t GetId() const { return id; }\n [[nodiscard]] uint32_t GetRequi() const { return requi; }\n [[nodiscard]] time_t GetOriginDate() const { return originDate; }\n [[nodiscard]] time_t GetRequestDate() const { return requestDate; }\n [[nodiscard]] time_t GetAuthorizedDate() const { return authorizedDate; }\n [[nodiscard]] uint64_t GetAmount() const { return amount; }\n [[nodiscard]] bool IsTaxed() const { return hasTax; }\n [[nodiscard]] bool IsAuthorized() const { return authorized; }\n\n bool operator&lt;(const Element&amp; rhs) const { return requi &lt; rhs.requi; }\n bool operator&gt;(const Element&amp; rhs) const { return requi &gt; rhs.requi; }\n bool operator==(const Element&amp; rhs) const { return requi == rhs.requi; }\n bool operator!=(const Element&amp; rhs) const { return requi != rhs.requi; }\n\n void Authorize();\n\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const Element&amp; el) {\n out &lt;&lt; \"Id: \" &lt;&lt; el.GetId() &lt;&lt; \", Requi: \" &lt;&lt; el.GetRequi() &lt;&lt; \", Monto: $ \"\n &lt;&lt; int(el.GetAmount() / 100) &lt;&lt; \".\" &lt;&lt; int(el.GetAmount() % 100)\n &lt;&lt; (el.IsTaxed() ? \" mas IVA\" : \" neto (no aplica IVA)\");\n return out;\n }\n\nprivate:\n uint32_t id;\n uint32_t requi;\n time_t originDate;\n time_t requestDate;\n time_t authorizedDate;\n uint64_t amount;\n bool hasTax;\n bool reviewed = true;\n bool authorized = false;\n NOP_STRUCTURE(Element, id, requi, originDate, requestDate, authorizedDate,\n amount, hasTax, reviewed, authorized);\n};\n\n// Element.cpp\n\n#include \"Element.h\"\n\nElement::Element(uint32_t requi, time_t originDate, time_t requestDate,\n time_t authorizedDate, uint64_t amount, bool hasTax,\n bool authorized)\n : requi(requi), originDate(originDate), requestDate(requestDate),\n authorizedDate(authorizedDate), amount(amount), hasTax(hasTax),\n authorized(authorized) {}\n\nvoid Element::Authorize() {\n std::time(&amp;authorizedDate);\n authorized = true;\n}\n\n// Records.h\n\n#pragma once\n\n#include \"Element.h\"\n#include &lt;nop/serializer.h&gt;\n#include &lt;nop/utility/die.h&gt;\n#include &lt;nop/utility/stream_reader.h&gt;\n#include &lt;nop/utility/stream_writer.h&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n\nclass Records {\npublic:\n void Insert(Element&amp; element);\n void Insert(Element&amp;&amp; element) { Insert(element); } // support rvalues\n\n void SaveToFile(const std::string&amp; filename);\n void LoadFromFile(const std::string&amp; filename);\n void ListRequi();\n\nprivate:\n std::vector&lt;Element&gt; elements;\n};\n\n// Records.cpp\n\n#include \"Records.h\"\n#include &lt;algorithm&gt;\n#include &lt;fstream&gt;\n#include &lt;iostream&gt;\n#include &lt;iterator&gt;\n\nvoid Records::Insert(Element&amp; element) {\n element.SetId(elements.size() +\n 1); // autoincrement record count and use it as indes (id)\n elements.emplace_back(element);\n}\n\nvoid Records::SaveToFile(const std::string&amp; filename) {\n using Writer = nop::StreamWriter&lt;std::ofstream&gt;;\n nop::Serializer&lt;Writer&gt; serializer{filename};\n serializer.Write(elements) || nop::Die(std::cerr);\n}\n\nvoid Records::LoadFromFile(const std::string&amp; filename) {\n using Reader = nop::StreamReader&lt;std::ifstream&gt;;\n nop::Deserializer&lt;Reader&gt; deserializer{filename};\n deserializer.Read(&amp;elements) || nop::Die(std::cerr);\n}\n\nvoid Records::ListRequi() {\n if (elements.size() &gt; 0) {\n std::sort(elements.begin(), elements.end());\n std::copy(elements.begin(), elements.end(),\n std::ostream_iterator&lt;Element&gt;(std::cout, \"\\n\"));\n }\n}\n\n// main.cpp\n\n#include \"Records.h\"\n#include &lt;algorithm&gt;\n#include &lt;ctime&gt;\n#include &lt;iostream&gt;\n\nint main() {\n const auto filename = std::string{\"datos.txt\"};\n\n {\n time_t tRequest = 0;\n time_t tElaboration = 0;\n // get today's date and time\n std::time(&amp;tRequest);\n std::time(&amp;tElaboration);\n\n Records reg;\n reg.Insert(Element(22132, tElaboration, tRequest, 0, 1586450, true));\n reg.Insert(Element(22340, tElaboration, tRequest, 0, 123490, false));\n reg.Insert(Element(45398, tElaboration, tRequest, 0, 58674, true));\n reg.Insert(Element(21518, tElaboration, tRequest, 0, 879965, true));\n reg.SaveToFile(filename);\n std::cout &lt;&lt; \"The following records have been saved:\\n\";\n reg.ListRequi();\n }\n\n {\n Records reg;\n reg.LoadFromFile(filename);\n std::cout &lt;&lt; \"\\nThe following records have been loaded:\\n\";\n reg.ListRequi();\n }\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T18:44:02.113", "Id": "463482", "Score": "0", "body": "This is clever, I never thought of addint and rvalue supporter for Insert method.\nNever heard of libop but, it looks nice, let me try it.\nThank you very much for your comment!, I need to update my code :D\nThank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T18:57:04.773", "Id": "463483", "Score": "0", "body": "@VitalZero\nThanks. It was fun finding out about `libnop` for myself. Since you're new: If you found the answer useful, please upvote and accept it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T20:55:56.310", "Id": "463502", "Score": "0", "body": "Tried to use libnop, but it gave me tons of errors, everything seems to be fine except for \"#if __has_cpp_attribute(clang::fallthrough)\" code which seems to be a typo" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T21:15:47.543", "Id": "463504", "Score": "0", "body": "@VitalZero Has for me to diagnose. You should search for \"error message libnop\" and the name and version of the compiler you are using. That attribute is documented here: https://clang.llvm.org/docs/LanguageExtensions.html Are you compiling with at least C++14 support ? https://github.com/google/libnop" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T21:40:38.290", "Id": "463507", "Score": "0", "body": "Well, most of the problem comes from NOP_STRUCTURE not being recognized as a MACRO but is being recognized as a member function of Element class, so, it's expecting the definition. Actually it gives me 4 errors and 7 warnings. I'm using c++14.\nE2512 is for the clang::fallthrough and the rest is C4146.\n\nI found a post about error (not specific) that says libnop doesn't support MSVC :(\n\nhttps://github.com/google/libnop/issues/4" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T21:48:47.990", "Id": "463509", "Score": "0", "body": "@VitalZero But that's a completely unrelated runtime error, and not what you are seeing. I am not very good at MSVC, but I tried just now and got the whole app running in 15mins. It \"just works\" if I extract the \"nop\" folder into project dir (which is in the include path). I am using MSVC Community version 16.4.0. Which I believe is the latest." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T22:03:21.890", "Id": "463511", "Score": "0", "body": "I did that, and it didnt work, I moved it to another location, added it to additonal include folders, and nothing :(\nIt was a good dream, tho :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T22:20:17.073", "Id": "463514", "Score": "0", "body": "@VitalZero Just try another serilisation lib. There are loads. Google is your friend." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T22:39:27.313", "Id": "463515", "Score": "0", "body": "@VitalZero this might fix it. It solved a related issue for me: https://docs.microsoft.com/en-us/cpp/preprocessor/preprocessor-experimental-overview?view=vs-2019 Passing that switch addresses many of MSVC's macro incompatibilities" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T23:00:52.487", "Id": "463516", "Score": "0", "body": "Nice, let me check, thank you!! :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T06:51:00.440", "Id": "463525", "Score": "0", "body": "I tried and MS \"solution\" didnt work. Now, I was getting an error about a number and unary operator not signed, or something like that in the file \"encoding.h\" at line 784 in nop. I opened that file and changed that line from \"else if (value >= -2147483648 && value <= 2147483647)\" to \"else if (value >= (-2147483647 -1) && value <= 2147483647)\" (which is supposed to check min and max values for int32. that made the error go away, but still had the warnings \"not enough args for macro _NOP_FIRST_ARG of type function\" which leads me to \"#if __has_cpp_attribute(clang::fallthrough)\" at \"compiler.h\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T06:54:04.290", "Id": "463526", "Score": "0", "body": "It compiles, runs and writes the file (and reads it). but, it only writes 10 bytes and the bytes it reads back, are pure garbage. I don't know how you got it to work :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T07:20:28.887", "Id": "463528", "Score": "0", "body": "@VitalZero That's the stage I was at when I sent you the macro switch (ie compile run, write and read, but garbage and 10bytes). I didn't notice initially that it was reading garbage. The experimental macro processor switch fixed that issue. But I am on 16.4.0. You? Can you upgrade? Bl...dy MSVC! You're close! It should be 100bytes. I had the same error too: \"not enough args for macro _NOP_FIRST_ARG of type function\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T07:46:29.390", "Id": "463529", "Score": "0", "body": "@VitalZero Just further upgraded mine to 16.4.4. Still works fine with that switch. https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes#16.4.4" } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T04:25:52.587", "Id": "236458", "ParentId": "236368", "Score": "2" } } ]
{ "AcceptedAnswerId": "236458", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T18:32:09.300", "Id": "236368", "Score": "3", "Tags": [ "c++", "database", "stl" ], "Title": "Records and elements class, small \"database\" c++, no sql" }
236368
<p>Hi so like in my question, i wrote some part of code for shopify to get recent orders for past 30 day and i wondering if it is really readable, or maybe i schould change something?</p> <p>I mean maybe there is a better way to achive same result.</p> <p>Or maybe i schould use different names? change position for function?</p> <pre><code>$(document).ready(function() { const collection = []; //set minimum recent order limit to show const minimumOrders = 2; //set number of days for recent orders const numberOfDays = 30; let date = new Date(); date.setDate(date.getDate() - numberOfDays) let startDate = date.toISOString(); function insertData(item, quality){ //part of code that will be executed for cert page if($( "input[value='"+item+"']" )){ $( "input[value='"+item+"']" ).parent().append("&lt;em class='text-success'&gt;"+quality+" purchased recently&lt;/em&gt;"); } //part of code that will be executed for checkouts if($("tr[data-variant-id='"+item+"']")){ $("tr[data-variant-id='"+item+"'] &gt; .product__description").append("&lt;em class='text-success'&gt;"+quality+" purchased recently&lt;/em&gt;"); } } function countOrders(){ $.getJSON('/admin/api/2020-01/orders.json', function (data ) { ordersEl = data.orders; ordersEl.forEach( function(element, index) { if(element.created_at &gt; startDate) { element.line_items.forEach( function(item, index) { if(collection.hasOwnProperty(item.variant_id)){ newValue = collection[item.variant_id]['quantity'] + item.quantity; collection[item.variant_id]['quantity'] = newValue; } }); } }); for(el in collection) { if(collection[el]['quantity'] &gt; minimumOrders){ insertData(el, collection[el]['quantity']) } } }); } $.getJSON('/cart.json', function (data ) { data.items.forEach( function(element, index) { collection[element.id] = []; collection[element.id]['quantity'] = 0; }); countOrders(); }); }); </code></pre> <p>every comment, suggestion will be relevant</p> <p>i do arrow functions and i think there is something more i can do but... the code just stop working...</p> <p>i would like to change that one :</p> <pre><code>for(el in collection) { if(collection[el]['quantity'] &gt; minimumOrders){ insertData(el, collection[el]['quantity']) } } </code></pre> <p>for:</p> <pre><code>collection.map( el =&gt; ((collection[el]['quantity'] &gt; minimumOrders) ? insertData(el, collection[el]['quantity']) : null) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T10:48:56.840", "Id": "463288", "Score": "0", "body": "Please don't edit your code after it has been reviewed." } ]
[ { "body": "<ul>\n<li>Use const &amp; let instead of vars</li>\n<li>Create Docblock for functions</li>\n<li>Arrow functions ES6</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T19:38:37.143", "Id": "463176", "Score": "0", "body": "i add a part of code that i would liek to change also... but after i change it code just stop working can you check it out where i make a errow?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T07:34:25.330", "Id": "463268", "Score": "0", "body": "@Piotr Arrow functions are ES6 you need to make sure you code will be transpiled to ES5" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T19:08:04.853", "Id": "236372", "ParentId": "236370", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T18:55:58.823", "Id": "236370", "Score": "1", "Tags": [ "jquery" ], "Title": "shopify get jquery code more readable, usable" }
236370
<p>I've designed a single-file safe integer library in C++. It catches undefined behavior prior to integer overflows or underflows and throws the respective exceptions. I intend this to be portable, to not rely on undefined behavior, and to rely as little on implementation-defined behavior as possible.</p> <p><code>safe_integer.hpp</code>:</p> <pre><code>/* * Copyright © 2020 James Larrowe * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program 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. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;. */ #ifndef SAFE_INTEGER_HPP # define SAFE_INTEGER_HPP 1 #include &lt;limits&gt; #include &lt;stdexcept&gt; #include &lt;type_traits&gt; template&lt;typename I, typename std::enable_if&lt;std::is_integral&lt;I&gt;::value, bool&gt;::type = true&gt; class safe_int { I val; public: typedef I value_type; static constexpr I max = std::numeric_limits&lt;I&gt;::max(); static constexpr I min = std::numeric_limits&lt;I&gt;::min(); safe_int(I i) : val { i } { }; operator I() const { return val; } I &amp;operator=(I v) { val = v; } safe_int operator+() { return *this; } safe_int operator-() { if(val &lt; -max) throw std::overflow_error(""); return safe_int(-val); } safe_int &amp;operator++() { if(val == max) throw std::overflow_error(""); ++val; return *this; } safe_int &amp;operator--() { if(val == min) throw std::underflow_error(""); --val; return *this; } safe_int operator++(int) { if(val == max) throw std::overflow_error(""); return safe_int(val++); } safe_int operator--(int) { if(val == min) throw std::underflow_error(""); return safe_int(val--); } safe_int &amp;operator+=(I rhs) { if( val &gt; 0 &amp;&amp; rhs &gt; max - val ) throw std::overflow_error(""); else if( val &lt; 0 &amp;&amp; rhs &lt; min - val ) throw std::underflow_error(""); val += rhs; return *this; } safe_int &amp;operator-=(I rhs) { if( val &gt;= 0 &amp;&amp; rhs &lt; -max ) throw std::overflow_error(""); if( val &lt; 0 &amp;&amp; rhs &gt; max + val ) throw std::overflow_error(""); else if( val &gt; 0 &amp;&amp; rhs &lt; min + val ) throw std::underflow_error(""); val -= rhs; return *this; } safe_int &amp;operator*=(I rhs) { if(val &gt; 0) { if(rhs &gt; max / val) throw std::overflow_error(""); } else if(val &lt; 0) { if(val == -1) { if(rhs &lt; -max) throw std::overflow_error(""); goto no_overflow; } if(rhs &gt; min / val) throw std::underflow_error(""); } no_overflow: val *= rhs; return *this; } safe_int &amp;operator/=(I rhs) { if( rhs == -1 &amp;&amp; val &lt; -max ) throw std::underflow_error(""); else if(rhs == 0) throw std::domain_error(""); val /= rhs; return *this; } safe_int &amp;operator%=(I rhs) { if( rhs == -1 &amp;&amp; val &lt; -max ) throw std::underflow_error(""); else if(rhs == 0) throw std::domain_error(""); val %= rhs; return *this; } safe_int operator+(I rhs) { return safe_int(val) += rhs; } safe_int operator-(I rhs) { return safe_int(val) -= rhs; } safe_int operator*(I rhs) { return safe_int(val) *= rhs; } safe_int operator/(I rhs) { return safe_int(val) /= rhs; } safe_int operator%(I rhs) { return safe_int(val) %= rhs; } safe_int &amp;operator+=(safe_int rhs) { return *this += static_cast&lt;I&gt;(rhs); } safe_int &amp;operator-=(safe_int rhs) { return *this -= static_cast&lt;I&gt;(rhs); } safe_int &amp;operator*=(safe_int rhs) { return *this *= static_cast&lt;I&gt;(rhs); } safe_int &amp;operator/=(safe_int rhs) { return *this /= static_cast&lt;I&gt;(rhs); } safe_int &amp;operator%=(safe_int rhs) { return *this %= static_cast&lt;I&gt;(rhs); } safe_int operator+(safe_int rhs) { return safe_int(val) += static_cast&lt;I&gt;(rhs); } safe_int operator-(safe_int rhs) { return safe_int(val) -= static_cast&lt;I&gt;(rhs); } safe_int operator*(safe_int rhs) { return safe_int(val) *= static_cast&lt;I&gt;(rhs); } safe_int operator/(safe_int rhs) { return safe_int(val) /= static_cast&lt;I&gt;(rhs); } safe_int operator%(safe_int rhs) { return safe_int(val) %= static_cast&lt;I&gt;(rhs); } }; #endif </code></pre> <p>This should work on non-two's complement systems and with any integer type.</p> <p>Here's a little example:</p> <pre><code>#include "safe_integer.hpp" int main(void) { safe_int&lt;int&gt; i = 0; i -= -0x80000000; return 0; } </code></pre> <p>Output:</p> <pre><code>terminate called after throwing an instance of 'std::overflow_error' what(): Aborted </code></pre> <p>What I'm particularly interested in:</p> <ul> <li><p>Are there any corner cases I've missed?</p></li> <li><p>Is there any undefined behavior (probably not)?</p></li> <li><p>Is there any way I can simplify all of the (somewhat redundant) operator overloads?</p></li> </ul> <p>What I'm <em>not</em> interested in:</p> <ul> <li>efficiency. I agree that my solution may not perform well but my personal opinion is that leaving the checks in unconditionally and not using undefined behavior to get a faster result are worth the cost.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-10T17:22:03.400", "Id": "521225", "Score": "1", "body": "FYI: There's a Boost library for this stuff, [safe_numerics](https://github.com/boostorg/safe_numerics)." } ]
[ { "body": "<p>You can get rid of the <code>goto</code> in <code>operator*=</code> by adding an <code>else</code> to the <code>if (val == -1)</code> statement.</p>\n\n<p>The <code>%</code> operator cannot underflow, as the result always has a magnitude less than the rhs value. So you don't need your underflow check (which is incorrect anyways, as it would throw rather than return a 0).</p>\n\n<p>An \"underflow\" represents a number that is too small to represent, and is typically applied to floating point types. A calculation that gives a number that is negative and too large to store in the result (i.e., is less than <code>min</code>) is still an overflow, as the result has overflowed the storage space available. So all those places that you throw an <code>underflow_error</code> should be <code>overflow_error</code> (unless you're changing the usage of underflow to represent too large of a negative value).</p>\n\n<p>How does the code behave if I instantiate a <code>safe_int&lt;unsigned&gt;</code>? The evaluation of <code>-max</code> in that case will not give the correct result, and possibly cause a compiler warning (for negation of an unsigned value).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T00:49:17.983", "Id": "463243", "Score": "0", "body": "I'm curious because you always say negation of unsigned values may cause a compiler warning: Does your compiler warn you about this? It should just convert the negative value into an unsigned one using the documented conversion rules, no warning necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T04:33:22.787", "Id": "463256", "Score": "0", "body": "@S.S.Anne MSVC can issue \"warning C4146: unary minus operator applied to unsigned type, result still unsigned\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T11:57:00.243", "Id": "463295", "Score": "0", "body": "That's ridiculous. I've never heard of GCC doing such a thing, nor would I ever like to. But anyway, I've fixed that by adding `std::is_signed<I> &&` inside the loop." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T21:34:02.127", "Id": "236380", "ParentId": "236376", "Score": "7" } }, { "body": "<h2>Code Review</h2>\n<pre><code>/*\n * Copyright © 2020 James Larrowe\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;.\n */\n</code></pre>\n<p>You should probably note that this code is now also available under the Creative Commons license which you agreed to by posting it on this page. See the base of the page for details.</p>\n<blockquote>\n<p>user contributions licensed under cc <a href=\"https://creativecommons.org/licenses/by-sa/4.0/\" rel=\"noreferrer\">by-sa 4.0</a> with <a href=\"https://stackoverflow.blog/2009/06/25/attribution-required/\">attribution required</a>. rev 2020.1.30.35920</p>\n</blockquote>\n<hr />\n<p>In the old days this was not legal (the space after the hash). But I am not sure if this has been updated.</p>\n<pre><code># define SAFE_INTEGER_HPP 1\n</code></pre>\n<p>Anyway it looks untidy :-)</p>\n<hr />\n<p>Here you have undefined behavior.</p>\n<pre><code> I &amp;operator=(I v) { val = v; }\n</code></pre>\n<p>You are supposed to return a reference yet don't return anything.</p>\n<p>Also I am concerned about the return type. Why are you returning a reference to the internal integer? Should that not be a reference to the <code>safe_int</code>? Is this some kind of pre-mature optimization?</p>\n<p>It has to be an <code>int</code> so passing by value seems OK until you come along and adapt the class for some other type (might be useful for <code>std::complex&lt;int&gt;</code>?). Then passing by value is no longer a good solution.</p>\n<p>Assume somebody will use your class in a way you have not anticipated and thus program defensively. Pass parameters by const reference unless you know that forever it is only going to be an int and you can't know that because its an <code>I</code>.</p>\n<hr />\n<p>Are you sure that's a a safe test?</p>\n<pre><code> safe_int operator-()\n {\n if(val &lt; -max)\n throw std::overflow_error(&quot;&quot;);\n\n return safe_int(-val);\n }\n</code></pre>\n<p>What about signed integer?<br />\nDo all systems use integers where the <code>std::abs(min) &gt; max</code>? Not sure I know that answer.</p>\n<hr />\n<p>Hard to spot that <code>&amp;</code>.</p>\n<pre><code> safe_int &amp;operator++()\n</code></pre>\n<p>In C++ (unlike C) the <code>&amp;</code> and the <code>*</code> are usually placed with the type information. So it would normally be written as:</p>\n<pre><code> safe_int&amp; operator++()\n</code></pre>\n<hr />\n<p>You could think of no other way of writing that without the <code>goto</code>?</p>\n<pre><code> safe_int &amp;operator*=(I rhs)\n {\n goto no_overflow;\nno_overflow:\n val *= rhs;\n return *this;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T16:00:24.620", "Id": "463325", "Score": "0", "body": "Eh, don't care about licensing. People can use it with the GPL or CC-by-SA 4.0, as long as they use it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T16:01:00.760", "Id": "463326", "Score": "0", "body": "Space after hash is fine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T16:03:44.507", "Id": "463328", "Score": "0", "body": "Unary `-` on `val` only overflows when `val` is `min` and `min` is less than `-max`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T16:05:09.913", "Id": "463329", "Score": "0", "body": "Fixed `goto`. I think I wrote that one when I was tired." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T16:05:55.893", "Id": "463330", "Score": "0", "body": "`operator=` is a bug. I'll fix that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T12:32:30.343", "Id": "463450", "Score": "1", "body": "\"In the old days this was not legal (the space after the hash). But I am not sure if this has been updated.\" Yeah it was updated in the fancy new ISO standardization from 1989/1990 :)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T15:22:27.980", "Id": "236422", "ParentId": "236376", "Score": "5" } }, { "body": "<p>A useful idea; thanks for sharing it with us.</p>\n<h1>Limitations and bugs</h1>\n<p>I have a nagging doubt about the implicit conversion to/from <code>value_type</code>. There are cases where we could have unchecked arithmetic when we expected it to be checked. For example, given:</p>\n<pre><code>safe_int&lt;int&gt; i = std::numeric_limits&lt;int&gt;::max();\nint j = i;\n</code></pre>\n<p>With the above, I find that <code>i + j</code> throws, but <code>j + i</code> continues with its undefined behaviour. I think we'd prefer both expressions to throw.</p>\n<p>I admit I was slightly surprised that the above didn't reach an ambiguous overload. However, <code>long j = i</code> causes <code>i + j</code> to be ambiguous and <code>j + i</code> to be unchecked; that's no better IMO.</p>\n<p>All in all, I think the safety would be greatly improved if we declare the conversion to unsafe with the <code>explicit</code> keyword:</p>\n<pre><code>explicit operator value_type() const noexcept { return val; }\nvalue_type value() const noexcept{ return val; }\n</code></pre>\n<p>The <code>value()</code> accessor is useful as it allows us to avoid numerous <code>static_cast</code> operators (which always need closer inspection).</p>\n<hr />\n<p>We're missing promotions from narrower <code>safe_int</code> types. For example, this code ought to be valid, but isn't:</p>\n<pre><code>safe_int&lt;int&gt; i = std::numeric_limits&lt;int&gt;::max();\nsafe_int&lt;long&gt; j = i;\n</code></pre>\n<p>We need some converting constructors such as these (I'll use Concepts syntax, as it's easier to read than lots of <code>std::enable_if</code> - adapt as necessary if that's not available to you):</p>\n<pre><code>template&lt;typename T&gt;\n requires std::is_assignable_v&lt;value_type&amp;,T&gt;\nsafe_int(T t = {})\n noexcept(std::is_nothrow_assignable_v&lt;value_type&amp;,T&gt;)\n : val{t}\n{}\n\ntemplate&lt;typename T&gt;\n requires std::is_assignable_v&lt;value_type&amp;,T&gt;\nsafe_int(safe_int&lt;T&gt; t)\n noexcept(std::is_nothrow_assignable_v&lt;value_type&amp;,T&gt;)\n : val{static_cast&lt;value_type&gt;(t)}\n{}\n</code></pre>\n<p>We also need binary operations that promote to <code>safe_int</code> of the common type of the arguments (for <code>i+j</code> and <code>j+i</code> to both work); this is my quick attempt:</p>\n<pre><code>template&lt;typename T, typename U&gt;\nsafe_int&lt;std::common_type_t&lt;T,U&gt;&gt; operator+(safe_int&lt;T&gt; a, safe_int&lt;U&gt; b)\n{\n using V = std::common_type_t&lt;T,U&gt;;\n return safe_int&lt;V&gt;(std::move(a)) + safe_int&lt;V&gt;(std::move(b));\n}\n\ntemplate&lt;typename T, typename U&gt;\n requires std::is_integral_v&lt;U&gt;\nsafe_int&lt;std::common_type_t&lt;T,U&gt;&gt; operator+(safe_int&lt;T&gt; a, U b)\n{\n using V = std::common_type_t&lt;T,U&gt;;\n return safe_int&lt;V&gt;(std::move(a)) + safe_int&lt;V&gt;(b);\n}\n\ntemplate&lt;typename T, typename U&gt;\n requires std::is_integral_v&lt;U&gt;\nsafe_int&lt;std::common_type_t&lt;T,U&gt;&gt; operator+(U a, safe_int&lt;T&gt; b)\n{\n return std::b + a;\n}\n</code></pre>\n<hr />\n<h1>Style</h1>\n<p>This seems old-fashioned:</p>\n<blockquote>\n<pre><code>typedef I value_type;\n</code></pre>\n</blockquote>\n<p>Modern C++ authors prefer <code>using</code>:</p>\n<pre><code>using value_type = I;\n</code></pre>\n<p>Instead of <code>static_cast</code> of arguments to the assignment operators, just use the <code>val</code> member directly:</p>\n<pre><code>safe_int &amp;operator+=(safe_int rhs)\n{\n return *this += rhs.val;\n}\n</code></pre>\n<p>There's a stray <code>;</code> after the converting constructor.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T12:22:05.983", "Id": "463447", "Score": "0", "body": "Thanks -- my compiler doesn't support C++20, nor concepts. I'm not terribly familiar with them, so do you mind writing it out for the \"lots of `enable_if`\" approach?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T12:27:15.763", "Id": "463449", "Score": "0", "body": "I don't have time right now for that (and that's why the code I show isn't thoroughly tested - it's just intended as a guide to the right direction). The Concepts syntax isn't too hard to follow - just look for the lines with `requires`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-08T00:22:55.677", "Id": "464309", "Score": "0", "body": "Thanks -- I've implemented most of these. How can I write two constructors that covert from bigger types and check for narrowing?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T11:09:34.013", "Id": "236464", "ParentId": "236376", "Score": "3" } } ]
{ "AcceptedAnswerId": "236380", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T20:38:38.587", "Id": "236376", "Score": "6", "Tags": [ "c++", "c++11", "integer" ], "Title": "Safe Integer Library in C++" }
236376
<p>Will you review the syntax, structure, and logic of my code. It can be tested using the main.</p> <pre><code>using iTextSharp.text.pdf; using iTextSharp.text; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AddCopyRightPDF { class Program { static void Main(string[] args) { string PDFPath = "D:\\SamplePDF\\SamplePDF.PDF"; string PDFPathUpdated = "D:\\SamplePDF\\SamplePDFUpdated.PDF"; byte[] b = AddCopyrighttoPDF(PDFPath); System.IO.File.WriteAllBytes(PDFPathUpdated, b); } public static byte[] AddCopyrighttoPDF(string path) { byte[] b = null; string CopyRighText; try { CopyRighText = "Copyright © " + DateTime.Now.Year + " All Rights Reserved."; PdfStamper pdfStamper = null; PdfReader pdfReader = null; try { using (MemoryStream ms = new MemoryStream()) { pdfReader = new PdfReader(new RandomAccessFileOrArray(path), System.Text.ASCIIEncoding.UTF8.GetBytes("1111")); pdfStamper = new PdfStamper(pdfReader, ms); for (int i = 1; i &lt;= pdfReader.NumberOfPages; i++) { if (i &gt; 1) { Rectangle pageSizeWithRotation = pdfReader.GetPageSizeWithRotation(i); PdfContentByte overContent = pdfStamper.GetOverContent(i); overContent.BeginText(); BaseFont baseFont = BaseFont.CreateFont("Helvetica", "Cp1250", false); overContent.SetFontAndSize(baseFont, 7F); overContent.SetRGBColorFill(0, 0, 0); float n2 = 15F; float n3 = pageSizeWithRotation.Height - 10F; overContent.ShowTextAligned(0, CopyRighText, n2, n3, 0F); overContent.EndText(); } } pdfStamper.FormFlattening = true; pdfStamper.Close(); b = ms.ToArray(); ms.Flush(); ms.Close(); } } catch { b = null; } finally { if (pdfReader != null) { pdfReader.Close(); } } } catch { b = null; } return b; } } } </code></pre>
[]
[ { "body": "<p><strong>From top to bottom</strong></p>\n\n<p>Since <code>AddCopyrighttoPDF()</code> is a <code>public</code> method you should validate its argument <code>path</code>. </p>\n\n<p>Variables should be named using <code>camelCase</code> casing and should be spelled correctly <code>string CopyRighText;</code> -> <code>string copyrightText;</code></p>\n\n<blockquote>\n<pre><code>try\n{\n\n CopyRighText = \"Copyright © \" + DateTime.Now.Year + \" All Rights Reserved.\";\n PdfStamper pdfStamper = null;\n PdfReader pdfReader = null; \n</code></pre>\n</blockquote>\n\n<p>why are these 3 lines of code inside a <code>try..catch</code> block? Which exception could here happen? The <code>try..cacth</code> block can be removed. </p>\n\n<p>You are using an <code>using</code> statement for the <code>MemoryStream</code> which is a good thing, but both <code>PdfReader</code> and <code>PdfStamper</code> are implementing the <code>IDisposable</code> interface as well hence they should be enclosed in an <code>using</code> block as well. </p>\n\n<blockquote>\n<pre><code>for (int i = 1; i &lt;= pdfReader.NumberOfPages; i++)\n{\n if (i &gt; 1)\n { \n</code></pre>\n</blockquote>\n\n<p>If the loop would start at <code>int i = 2</code> the <code>if</code> block would become superflous which saves one indentation-level of thecode. </p>\n\n<p><code>BaseFont baseFont</code> should be created outside of the loop and reused. </p>\n\n<p><code>float n2 = 15F;</code> should be named better and should be a constant. </p>\n\n<p><code>float n3</code> should be named better. </p>\n\n<p><code>overContent.ShowTextAligned(0, CopyRighText, n2, n3, 0F);</code> here <code>0F</code> should be extracted into a constant as well. </p>\n\n<p>Disposing of the <code>MemoryStream</code>, which happens when the end of the <code>using</code> block is reached will <code>Flush()</code> and <code>Close()</code> it as well. </p>\n\n<p>Implementing the mentioned points will lead to </p>\n\n<pre><code>private const float copyrightFontHeight = 7F;\nprivate const float copyrightHorizontalPosition = 15F;\nprivate const float copyrightVerticalBorder = 10F;\nprivate const float copyrightRotationNone = 0F;\npublic static byte[] AddCopyrighttoPDF(string path)\n{\n if (string.IsNullOrEmpty(path)) { return null; }\n\n string copyrightText = \"Copyright © \" + DateTime.Now.Year + \" All Rights Reserved.\";\n\n try\n {\n BaseFont baseFont = BaseFont.CreateFont(\"Helvetica\", \"Cp1250\", false);\n using (MemoryStream ms = new MemoryStream())\n using (PdfReader pdfReader = new PdfReader(new RandomAccessFileOrArray(path), System.Text.ASCIIEncoding.UTF8.GetBytes(\"1111\")))\n using (PdfStamper = new PdfStamper(pdfReader, ms))\n {\n for (int i = 2; i &lt;= pdfReader.NumberOfPages; i++)\n {\n Rectangle pageSizeWithRotation = pdfReader.GetPageSizeWithRotation(i);\n PdfContentByte overContent = pdfStamper.GetOverContent(i);\n overContent.BeginText();\n overContent.SetFontAndSize(baseFont, copyrightFontHeight);\n overContent.SetRGBColorFill(0, 0, 0);\n float copyrightVerticalPosition = pageSizeWithRotation.Height - copyrightVerticalBorder;\n overContent.ShowTextAligned(0, copyrightText, copyrightHorizontalPosition, copyrightVerticalPosition, copyrightRotationNone);\n overContent.EndText();\n }\n\n pdfStamper.FormFlattening = true;\n pdfStamper.Close();\n return ms.ToArray();\n }\n }\n catch { } //empty because if we just want to swallow the exception\n\n return null;\n} \n</code></pre>\n\n<p>This should behave exactly like your former code. Thats why its not throwing an <code>ArguemntNullException</code> if <code>path == null</code> and why its not throwing an <code>ArgumentException</code> if <code>path</code> is whitespace only. </p>\n\n<p>I couldn't find the C# documentation of <code>BaseFont</code> but if <code>BaseFont</code> is implementing <code>IDisposable</code> as well, it should be enclosed in an <code>using</code> block as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T07:13:25.937", "Id": "236399", "ParentId": "236377", "Score": "1" } } ]
{ "AcceptedAnswerId": "236399", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T20:42:31.287", "Id": "236377", "Score": "1", "Tags": [ "c#" ], "Title": "Add Copyright to PDF File" }
236377
<p>This is a simple poker counter.</p> <p>It lets players decide their actions and makes the currency calculations for them.</p> <p>While adding a bit of console animation.</p> <p>Can I achieve the same results with simpler code??</p> <pre><code>from string import ascii_lowercase def get_player_names(): ''' Returns a List Of Playrer Names Got From User Input ''' i = 0 player_names = [] print('Enter Player Names...') print('Press Enter To Indicate That You\'re Done') while True: player = input() if player == '': break player_names.append(player) i += 1 print('-'*40) print(f'Player#{i} Is Set To: "{player}"') print('-'*40) return player_names def list_sequence(sequence): i = 0 lengths = [len(item) for item in sequence] if type(sequence) is dict: print('-'*40) print('Current Currency:') for key in sequence: i += 1 proportional_space = ' ' * ( (max(lengths) - len(key)) + 2 ) print('-'*20) print(f'{i})-{key}{proportional_space}: {sequence.get(key, 0)}') print('-'*40) else: print('Current List Of Players:') print('-'*26) for item in sequence: i += 1 print(f'Player#{i} ---&gt; "{item}"') print() def start_currency(player_names): player_currency_dict = \ {player: 100 for player in player_names} #player_currency_dict[player_names[0]] = 1 return player_currency_dict def list_player_statues(player_currency, player_statues): i = 0 lengths = [len(player) for player in player_currency] for player in player_currency: i += 1 currency = player_currency[player] state = players_statues[player] #formating proportional_length_factor= ( max(lengths) - len(player) ) + 1 proportional_space = ' ' * proportional_length_factor remaining_space = 9 - len(player) - len(str(currency)) - proportional_length_factor - (3-len(str(currency))) proportional_hyphen = '-'*remaining_space #------------------------------------------------------------------------------------ print('_'*15 + '||' + '_'*25) print(f'{i}.{player}{proportional_space}: {"0"*(3-len(str(currency)))}{currency} {proportional_hyphen} || {"-"*5}&gt; {state}') print('_'*40) player_names = ['Dante', 'Sam', 'Kat', 'Nancy'] #player_names = get_player_names() player_currency = start_currency(player_names) players_statues = {player: 'Stand By' for player in player_names} list_sequence(player_names) print('Each Player Gets 100 Currency For The Game') list_sequence(player_currency) confirm = input('Press Enter To Continue...') print() player_bids = {player: 10 for player in player_names} total_bid = 10 * len(player_names) player_currency = {player: player_currency.get(player) -10 for player in player_names} round_over = '' while len(player_names) &gt; 0: for player in player_names: player_folded = players_statues[player] == 'Folded' player_is_out = players_statues[player] == 'Out' if player_folded or player_is_out: continue players_statues[player] = 'Current Turn' #next player player_index = player_names.index(player) + 1 print(player_index) if player_index &gt;= len(player_names): player_index = 0 next_player = player_names[player_index] print(next_player) players_statues[next_player] = 'Next Turn' #------------------------------------------------ list_player_statues(player_currency, players_statues) print() print('-'*40) print(f"{'~'*10} {player}'s Turn {'~'*10}") print('-'*40) #getting action for each player while True: action = input() #print(player_bids[player]) #print(max(player_bids)) if action == 'ck' and player_bids[player] == max(player_bids.values()): bid = 0 players_statues[player] = 'Check' break elif action == 'c': bid = max(player_bids.values()) - player_bids[player] players_statues[player] = 'Called' break elif action == 'r': while True: amount = input('Raise By?') is_numeric = amount.isnumeric() if is_numeric: amount = int(amount) bid = max(player_bids.values()) + amount - player_bids[player] players_statues[player] = f'Raised By {amount}' break print('Please Enter a Number..') print() break elif action == 'f': bid = 0 break else: bid = 0 if player_bids[player] != max(player_bids.values()): print("You Cant't check since a player raised the bid") else: print('List Of Available Actions:') print('"ck": Check \n"c": Call \n"r": Raise \n"f": Fold') #---------------------------------------------------------------------- player_currency[player] -= bid player_bids[player] += bid total_bid += bid print() print() print(f'Current Bid: {max(player_bids.values())}') print(f'Current Round Total: {total_bid}') print() print() list_player_statues(player_currency, players_statues) round_over = input('Is The Round Over?') if round_over in ['yes', 'y']: winner = input('Who Won?') player_currency[winner] += total_bid total_bid = 0 player_bids = {player: 10 for player in player_names} player_statues = {player: 'Stand By' for player in player_names} list_player_statues(player_currency, players_statues) <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>I am not certain what you are asking, so I will mention three ideas about your code and hope it helps.</p>\n\n<p><strong>Worry mostly about your function level</strong></p>\n\n<pre><code>def list_sequence(sequence):\n</code></pre>\n\n<p>This is a tricky function, mostly because it is really:</p>\n\n<pre><code>def print_players_or_currency(player_list_or_currency_dict)\n</code></pre>\n\n<p>You should rarely need to look at the type of an object (with <code>type()</code> or <code>isinstance()</code>) and only when doing meta-programming. Make two functions.</p>\n\n<p><strong>Play with f-strings formatting</strong></p>\n\n<pre><code> for key in sequence:\n i += 1\n proportional_space = ' ' * ( (max(lengths) - len(key)) + 2 )\n print('-'*20) \n print(f'{i})-{key}{proportional_space}: {sequence.get(key, 0)}') \n</code></pre>\n\n<p>could be shorter:</p>\n\n<pre><code>for i, (key, value) in enumerate(sequence.items()):\n print(f\"{'':-&gt;20}\\n{i+1:2}-{key:&lt;{max(lengths)}}: {value}\")\n</code></pre>\n\n<p><strong>Always use a main() function</strong></p>\n\n<p>You have about a hundred lines at the top level. The problem is that the top level creates questions about global variables, ordering declarations and so on. It is far better to throw all hundred lines inside a <code>main</code> function and call it. While this might seem odd to insist on, remember that the Python interpreter just runs lines of code from top to bottom while keeping track of name spaces. This means that <code>def foo(): ....</code> is just a statement. The problem is that the top level code creates global variables, can only call functions if the <code>def</code> was seen first, and so on. Save confusion: put all your code inside a function and just have imports and a <code>main()</code> at the top level.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T06:48:41.000", "Id": "463266", "Score": "0", "body": "fixed, thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T05:11:06.907", "Id": "236389", "ParentId": "236378", "Score": "3" } }, { "body": "<h1>Tracking Players</h1>\n\n<p>There are a few instances where I see you are iterating over <code>players</code> in order to retrieve values from multiple dictionaries (<code>player_currency_dict</code> and <code>player_statues</code>). This is a hint that maybe that information should be stored in the same dictionary of <code>players</code>. I'd also keep the players' last bet in there as well:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># should look like this\nplayers = {'name': [amount, state, last_bet], ...}\n</code></pre>\n\n<p>This way, it's really easy to keep track of those three pieces of information. To build this, you can swap out your <code>get_player_names</code> and <code>start_currency</code> functions for one simple function:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_player_dict(players):\n \"\"\"\n Simply return a dictionary that holds players as keys and\n a list of [currency, state, last_bet]. This is a list so that you may\n edit those values\n \"\"\"\n return {player: [100, 'Standby', 0] for player in players}\n</code></pre>\n\n<p>To get all of that information, you can use <code>dict.items()</code> in a loop like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># for keeping the list together\nfor name, status in players.items():\n # do things\n\n\n# for full unpacking \nfor name, (money, state, last_bet) in players.items():\n # do things\n</code></pre>\n\n<h2>Why keep the list together?</h2>\n\n<p>I want to use a list because I can modify it in-place. This will be more clear later, but as a short example, I can do something like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>sample = {'Steve': [100, 'Standby', 0]}\n\ndef bet_10(my_list):\n my_list[0] -= 10\n my_list[2] += 10\n\nbet_10(sample['Steve'])\nsample\n{'Steve': [90, 'Standby', 10]}\n</code></pre>\n\n<h1>Displaying Game State</h1>\n\n<p>There are some functions you define that focus on displaying information. While this is a good use-case for a function, some of the formatting can be trimmed down. First, if you are trying to fill a string with a value, you can use <code>ljust</code> or <code>rjust</code> to fill to the right or left, respectively:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>'abc'.ljust(7)\n'abc '\n\n'abc'.rjust(7)\n' abc'\n</code></pre>\n\n<p>Also, magic numbers are usually a code smell. If you need to adjust them, I'd suggest passing them as parameters to make things a bit more flexible:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def show_players(players, name=20, currency=10, state=10, bet=10):\n \"\"\"\n Pass the players dict and the padding for the four values,\n or just use the defaults\n \"\"\"\n sts = (n.ljust(v) for n, v in zip(\n (\"Name\", \"Currency\", \"State\", \"Bet\"), (name, currency, state, bet))\n )\n header = \" {} | {} | {} | {}\".format(*sts)\n print(header)\n for i, (n, (c, s, l)) in enumerate(players.items(), start=1):\n print('_'*len(header))\n n = n.ljust(name)\n c = str(c).ljust(currency)\n s = s.ljust(state)\n l = str(l).ljust(bet)\n print(f\"{i}. {n} | {c} | {s} | {l}\")\n\n\n# Example\nshow_players(players)\n Name | Currency | State | Bet\n______________________________________________________________\n1. Dante | 100 | Standby | 0\n______________________________________________________________\n2. Sam | 100 | Standby | 0\n______________________________________________________________\n3. Kat | 100 | Standby | 0\n</code></pre>\n\n<p>I might prefer to show all of the info, that way, at the end of each turn I can display the state of the game and re-use this every time</p>\n\n<h1>The Game*</h1>\n\n<p>The core workings of your game execute in global scope and don't leverage a lot of functions. This makes changing code a bit more difficult. In pseudo-code, I would imagine this game would look something like:</p>\n\n<pre><code># Each Round\nloop {\n # each iteration would be a turn\n foreach player in players{\n # Each player that hasn't folded gets a chance to bet\n case {\n player -&gt; Raise\n player -&gt; Fold\n player -&gt; Call\n player -&gt; Check\n } \n }\n\n if all(bets match or all-in){\n break loop\n } else {\n continue\n }\n\n}\n\n</code></pre>\n\n<p>Hopefully the notation isn't too wonky. This will be the basic structure for breaking down your main script.</p>\n\n<h1>Round Loop</h1>\n\n<p>You will want a loop to track each round of play. Each round will have a <code>pool</code>, which is the total money being bet by all players. It will also need a <code>bid</code> amount which you've noted already as the highest bet. You can just use another <code>while</code> loop to go through the players until an end condition is hit:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def play_round(players):\n \"\"\"\n Loop over players in players dictionary and play\n a turn for each player. The win condition is defined by\n one of two criteria:\n For all players that have not folded they either:\n A) are All-In\n B) Have last_bet matching bid\n\n The pool (total) of money gambled is returned\n\n \"\"\"\n bid, pool = 0, 0\n while True:\n for name, status in players.items():\n show_players(players)\n\n curr, state, last_bet = status\n # skip over non-eligible players\n if state == 'Fold' or state == 'Out':\n continue\n\n print(f\"It is {name}'s turn!\")\n print(f\"The current bid is {bid}\")\n\n # will need some sort of take_turn function\n player_bet = take_turn(name, status, bid)\n\n # add the appropriate bet to the pool of cash\n pool += player_bet\n # the bid is the max of the bid or the bet that was made\n bid = max(bid, player_bet)\n\n # Everyone's bet either matches current bid, is all-in, or has folded\n if all(\n curr==0 or last_bet==bid\n for curr, state, last_bet in players.values()\n if state != 'Fold'\n ):\n print('All bets match, ending round')\n break\n\n # return the pool to outer scope\n return pool\n</code></pre>\n\n<h1>Player Turns</h1>\n\n<p>Each player will need a turn. This replaces the loop that gets each action (well, moves it more than replaces it) with a function. Really, there are four major actions a player can take: Check, Raise, Call, or Fold. Raise and Call will be pretty similar to one another, so that might be a function on its own. You can easily handle this with an <code>if/else</code> block:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def take_turn(name, status, bid):\n \"\"\"\n A player is allowed the option to do one of five things:\n Raise -&gt; Raise bid by integer amount\n Call -&gt; Bet the same as the bid\n Fold -&gt; Quit the hand\n Check -&gt; Bet nothing (only applicable if bid is 0)\n All-In -&gt; Bet everything they have\n\n Return amt to be added to the bid pool\n \"\"\"\n\n # set opts as a dictionary for easy membership-testing\n # of user-selected options\n opts = {\n 'c': 'check',\n 'r': 'raise',\n 'b': 'call',\n 'a': 'all-in',\n 'f': 'fold'\n }\n curr, state, last_bet = status\n if state == \"All-In\":\n print(f\"Player {name} is already All-In\")\n return 0\n\n while True:\n action = input(f\"Which action would you choose? \"\n f\"({', '.join(map(': '.join, opts.items()))})\").strip().lower()\n\n # This is a fast check to make sure inputs are valid\n # Loop again if not in options dictionary\n if action not in opts:\n print(\"Invalid option, please try again\")\n continue\n\n # Otherwise, continue forward\n elif action == 'c':\n # If the player's last bet is not equal to the current one,\n # they are unable to check.\n if last_bet != bid:\n print(f\"Cannot check, bid was raised to {bid}\")\n continue\n\n print(f\"Player {name} has checked\")\n amt = 0\n\n elif action == 'a':\n print(f\"Player {name} is going All-In\")\n amt = all_in(status)\n\n elif action == 'f':\n status[1] = 'Fold'\n print(f\"Player {name} has folded\")\n amt = 0\n\n else:\n try:\n # We've abstracted Call and Raise into the same function\n # for ease of use\n amt = handle_action(name, status, action, bid)\n except (ValueError, TypeError):\n continue\n\n return amt\n</code></pre>\n\n<p>Now, we know we will want to return the bartered amount to the <code>round</code> loop so the money can be added to the <code>pool</code>. Here we just need to keep track of the current <code>bid</code> and the <code>player</code> itself. Now, the way <code>handle_action</code> is written depends on how the betting code is written, but in general, it's a way to handle two similar cases. Both are detailed below.</p>\n\n<h2>Betting</h2>\n\n<p>We will want a function for players to bet amounts of money. Using the general form from the example <code>bet_10</code> function, you could re-organize it into something like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def player_bet(player, amount):\n \"\"\"\n use this to modify who bet what amount by deducting amount from the\n first value in the list representing the player in-place:\n\n &gt;&gt;&gt; players = {'Steve': [100, 'Standby', 0]}\n &gt;&gt;&gt; player_bet(players['Steve'], 50)\n &gt;&gt;&gt; players\n {'Steve': [50, 'Standby', 50]}\n\n &gt;&gt;&gt; player_bet(players['Steve'], 75)\n ValueError\n 'Player does not have that amount to bet! Player has 50'\n \"\"\"\n curr, state, last_bet = player\n if curr &lt; amount:\n raise ValueError(\n f\"Player does not have that amount to bet! Player has {curr}\"\n )\n elif state == 'All-In':\n raise TypeError(\"Player that is All-In cannot bet\")\n\n # decrement held money\n player[0] -= amount\n # while increasing the amount that was bet\n player[2] += amount\n</code></pre>\n\n<p>Using the fact that we are passing in <code>player</code> by reference, we can edit the values in-place so that we don't have to return anything. I am raising an exception for not having enough money because I don't want players who may have mis-typed a number to accidentally go All-In. I also might want going all in to be a special case of betting for the purpose of being explicit. This could be a matter of taste, but an <code>all_in</code> function might look like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def all_in(player):\n \"\"\"\n Take the amount that the player has left and\n return it, this is just in case we aren't immediately\n sure what the bet is going to be. Use a try-except so that\n going all-in is a bit more explicit and not accidental\n\n &gt;&gt;&gt; players = {'Steve': [100, 'Standby', 0]}\n &gt;&gt;&gt; initial_bet = 150\n &gt;&gt;&gt; pool = 150\n &gt;&gt;&gt;\n &gt;&gt;&gt; try:\n ... player = players['Steve']\n ... player_bet(initial_bet)\n ... except ValueError:\n ... pool += all_in(player)\n\n &gt;&gt;&gt; pool\n 250\n &gt;&gt;&gt; players\n {'Steve': [0, 'All-In', 100]}\n \"\"\"\n curr, *_ = player\n # set held funds to zero\n player[0] -= curr\n # add that to bet funds\n player[2] += curr\n # set status to All In\n player[1] = 'All In'\n return curr\n</code></pre>\n\n<p>I want to return <code>currency</code> because I don't want to have to worry about how much a player has when I call that function.</p>\n\n<h2><code>handle_action</code></h2>\n\n<p>Now we can roll <code>Call</code> and <code>Raise</code> into a function that I've called <code>handle_action</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def handle_action(name, status, action, bid):\n \"\"\"\n A function to help keep take_turn function from being too difficult to read,\n especially since Raise and Call are almost the same event\n \"\"\"\n curr, state, last_bet = status\n\n # the if/elif statement here helps define two parameters\n # amt and message, and raise any exceptions otherwise\n if action == 'r':\n try:\n amt = int(\n input(\"Raise by how much? \")\n )\n # int function raises a TypeError on bad input\n except TypeError:\n print(\"Please input an integer amount of money\")\n raise\n else:\n message = f\"Player {name} has raised bet by {amt}\"\n\n elif action == 'b':\n amt = bid - last_bet\n message = f\"Player {name} has called current bet of {bid}\"\n\n # Now, try the player_bet function since amt and message are set\n # and return amt only if player_bet was called successfully\n try:\n player_bet(status, amt)\n print(status)\n print(message)\n except ValueError as e:\n # Player will need to explicitly select 'a' as an option\n # to go all-in\n print(e)\n print(f\"You do not have enough, if you want to go all-in, select 'a'\")\n raise\n except TypeError as e:\n print(e)\n raise\n\n return amt\n\n</code></pre>\n\n<h1>Main Function</h1>\n\n<p>You usually want a <code>main</code> function to run your program. In this case, <code>main</code> will be the game loop that runs each round. I've put as many comments as I can to try to be clear, this is already a pretty long answer as is:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def main(players):\n\n while True:\n pool = play_round(players)\n\n # Show results after round\n show_players(players)\n print(\"Round Over\")\n\n # If all remaining players folded for some reason, this will allow the program\n # to handle that case and skip the while loop\n is_winner = any(x not in ('Fold', 'Out') for _, x, _ in players.values())\n\n while is_winner:\n # I like to sanitize input by at least stripping off\n # possible leading/trailing whitespace someone may have inadvertently\n # entered\n winner = input(\"Who was the winner? \").strip()\n try:\n winner = players[winner]\n # Prevent cheating! People who are out or folded cannot win...\n if winner[1] in ('Fold', 'Out'):\n print(\"That can't be! Must be a different winner...\")\n continue\n\n # add the pool to the winner's available cash pile\n winner[0] += pool\n except KeyError:\n # selected winner wasn't in the players dictionary\n print(\"Unrecognized player, please try again\")\n else:\n break\n else:\n # if `is_winner` is False, the while loop will skip to\n # this else statement\n print(\"How on earth was there no winner??\")\n\n play_again = input('Play Again? [y/n] ').lower().strip() == 'y'\n if not play_again:\n print(\"Ok, goodbye\")\n sys.exit(0)\n\n # Mark players with no money left as out\n no_money_left = [name for name, (money, *_) in players.items() if not money]\n if no_money_left:\n l = '\\n '.join(no_money_left)\n print(f\"The following players are Out: {l}\")\n for player in no_money_left:\n # sets state in-place\n players[player][1] = 'Out'\n\n # reset previous bets and states to default values for players\n # who are still in for the next round\n for player, status in players.items():\n _, state, _ = status\n status[2] = 0\n if state != 'Out':\n status[1] = 'Standby'\n</code></pre>\n\n<h1>if <strong>name</strong> == \"<strong>main</strong>\"</h1>\n\n<p>Usually, most programs will want a <code>__name__ == \"__main__\"</code> guard. This guard will only be <code>True</code> if the program is called like <code>python poker.py</code> but <em>not</em> if it is imported like <code>from poker import main</code>. Also, it might be helpful to pass the players names as <code>sys</code> args:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == \"__main__\":\n import sys\n\n players = get_player_dict(sys.argv[1:])\n if not players:\n # since this is a cli-game anyways, might be helpful to display a \n # use message if they called it with no players\n usage()\n sys.exit(0)\n\n main(players)\n</code></pre>\n\n<p>Where <code>usage</code> might look like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def usage():\n print(\"Call this script by passing the names of players as\")\n print(\"sys-args like so:\")\n print(\" python poker.py Alice James Steve Laura \")\n</code></pre>\n\n<h1>Odds and Ends</h1>\n\n<h2>Checking types of objects</h2>\n\n<p>It is more pythonic to use <code>isinstance</code> rather than <code>type(obj) == &lt;type&gt;</code></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>d = {}\n\n# do this\nif isinstance(d, dict):\n\n# not this\nif type(d) == dict:\n</code></pre>\n\n<p>And <code>is</code> is a keyword to stay away from, as it doesn't do exactly what you think it does, even though in this case it gives <code>True</code>, that's not always the case. Take this for example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>a = []\nb = []\na is b\nFalse\n\n# however\na == b\nTrue\n</code></pre>\n\n<h2>Checking for emptiness of a container</h2>\n\n<p>Checking to see if a <code>dict</code>, <code>list</code>, <code>set</code>, <code>tuple</code>, <code>string</code>, etc is empty should be done using its native <code>__bool__</code> implementation like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>d = {}\n\nif not d:\n # empty\n</code></pre>\n\n<h2>Tracking an index in a loop</h2>\n\n<p>Any time you see this kind of code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>i = 0\nfor item in collection:\n # do something\n i += 1\n</code></pre>\n\n<p>It should be refactored to use <code>enumerate</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for i, item in enumerate(collection):\n # do something\n</code></pre>\n\n<h2>Multi-Line Statements</h2>\n\n<p>Any time you have a statement that is going on for too long, you can use parentheses rather than <code>\\</code> to wrap a long line:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>x = (1 + 2 + 3 + 4\n+ 5 + 6 + 7)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T06:23:28.820", "Id": "236396", "ParentId": "236378", "Score": "3" } } ]
{ "AcceptedAnswerId": "236396", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-29T20:50:02.140", "Id": "236378", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "Simpler Poker Counter" }
236378
<p>With some effort I've managed to build a very simple (maybe too simple haha) navigation bar for a website. </p> <p>Is it possible to make a transition on the dropwdown list from height:0 to some suitable height? I've tried and it seems not to be possible. <strong>No javascript for now</strong></p> <p>Any advice or extra tweak I could add? All is greatly welcome!</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code> /* reset */ ul { list-style: none; margin: 0; padding: 0; } /* automatically take height of the elements */ .main { background-color: brown; overflow: auto; /* automatically adjusts height to anchors */ } .main__lis { margin-left: 20px; float: left; /* float the list items of the main ul */ } a { display: block; padding: 10px; text-decoration: none; } .dropdown ul { width: 120px; text-align: left; position: absolute; background-color: pink; display: none; box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2); } .dropdown:hover ul { display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;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;Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;nav&gt; &lt;ul class='main'&gt; &lt;li class='main__lis'&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li class='main__lis'&gt;&lt;a href="#"&gt;News&lt;/a&gt;&lt;/li&gt; &lt;li class='main__lis dropdown'&gt; &lt;a href="#"&gt;Dropdown&lt;/a&gt; &lt;ul class='dropdown_ul'&gt; &lt;li&gt;&lt;a href="#"&gt;link 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;link 3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T05:31:26.390", "Id": "463258", "Score": "1", "body": "Are you wanting feedback on the design (probably off topic here), or just code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T23:37:39.683", "Id": "463572", "Score": "0", "body": "@dwjohnston just code. Any design advice would be welcome though." } ]
[ { "body": "<p>You probably want to reset the margin and padding of <code>li</code> items, too.</p>\n\n<p>Using <code>float</code> to layout elements horizontally is outdated. Using <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox\" rel=\"nofollow noreferrer\">flexbox</a> should be preferred nowadays. That would also make <code>overflow: auto</code> redundant.</p>\n\n<p>Prefer a child combinator instead of a descendant combinator if possible: <code>.dropdown &gt; ul</code>.</p>\n\n<p>A dropdown on hover isn't usable on a touch screen.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T15:34:46.957", "Id": "463322", "Score": "0", "body": "why that sentence about combinators?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T16:01:02.243", "Id": "463327", "Score": "0", "body": "A descendant combinator is more work for the browser. It has to look at all elements above each `ul` element to look for an element with the class `dropdown`, but with a child combinator it only needs to look the direct parent element." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T16:05:56.077", "Id": "463331", "Score": "0", "body": "Nice one. Thanks. btw I know about flexbox but wouldn't floats be preferable as a matter of support?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T17:13:35.277", "Id": "463350", "Score": "0", "body": "Even if you need to support older browsers like IE9, then you still should use flexbox and add a separate stylesheet for them." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T09:43:26.897", "Id": "236407", "ParentId": "236386", "Score": "1" } }, { "body": "<p>all a tags have a padding of 10 according to you css. the <code>&lt;li&gt;</code> tags have anchor tags @RoTaRa's suggestion \"Prefer a child combinator instead of a descendant combinator if possible: <code>.dropdown &gt; ul.</code>\" make sure, you use <code>!important</code> for the new padding; i.e. <code>padding: 0px!important;</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T15:56:00.807", "Id": "463324", "Score": "1", "body": "If you use `!important` like that, then you are structuring your CSS wrong. `!important` must always be the last resort." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-12T12:09:43.287", "Id": "502093", "Score": "0", "body": "If it works without !important, then, by all means, don't add it. but if another class is overriding your style, then last resort" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T10:38:58.433", "Id": "236410", "ParentId": "236386", "Score": "0" } } ]
{ "AcceptedAnswerId": "236407", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T02:41:59.263", "Id": "236386", "Score": "2", "Tags": [ "html", "css" ], "Title": "Simple navbar in pure HTML5 and CSS3" }
236386
<p>I'm timing out on Codewars' Prime Streaming kata. Below is my code:</p> <pre class="lang-js prettyprint-override"><code>"use strict"; let _base = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]; let _bufferSize = 1000 class Primes { static get base() { return _base; } static get bufferSize() { return _bufferSize; } static set bufferSize (value) { _bufferSize = value; } static sieve(array) { for (let p of Primes.base) { array = array.filter(n =&gt; n % p !== 0); } return array; } static sieve_2(array) { } static * stream() { const candidates = []; for (let i = 73; i &lt; 5001; i += 2) candidates.push(i); Primes.base.push(...Primes.sieve(candidates)); const buffer = Primes.base.slice(); while (true) { let current; while (buffer.length &gt; 0) { current = buffer.shift(); yield current; } let [lower, upper] = [current + 2, current + Primes.bufferSize]; let basket = []; for (let i = lower; i &lt;= upper; i += 2) basket.push(i); buffer.push(...Primes.sieve(basket)); } } } </code></pre> <p>As far as I can tell, changing the buffer size affected nothing. I first generate primes less than <code>5001</code> because their upper bound on primes they test is somewhere below 16 million, and I wasn't enthused about doing the investigation work to find a precise bound, so I just went with a loose one.</p>
[]
[ { "body": "<p>Your current code, if I understand it, starts by sieving each target without recognizing that if the target is less than the highest cache (or <code>_base</code>) then it is prime if and only if it in the cache.</p>\n\n<p>One option is to keep your primes in a single cache (<code>_base</code>), make sure that the cache is high as your target, and check if your target is in your cache.</p>\n\n<p>The rough code would have only two functions: one ensures that base array is high enough, and the other returns the value. Something like:</p>\n\n<pre><code>const primes = [2, 3, 5];\n\nfunction ensure_primes(until_n) {\n let n = primes.slice(-1) + 1;\n while (n &lt;= until_n) {\n if (primes.every(prime =&gt; n % prime != 0)) {\n primes.push(n)\n }\n n += 1;\n }\n}\n\nfunction is_prime(target) {\n ensure_primes(target);\n return target in primes\n}\n</code></pre>\n\n<p>Is this what you were asking?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T06:06:27.557", "Id": "236392", "ParentId": "236388", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T03:43:43.783", "Id": "236388", "Score": "2", "Tags": [ "javascript", "algorithm", "programming-challenge", "time-limit-exceeded", "primes" ], "Title": "Codewars: Prime Streaming (PG-13)" }
236388
<p>I'm very new to Haskell and I was trying to implement a DFT which is very imperative into Haskell and I wanted to get a feedback. More specially how can I avoid so many helper functions and I avoid limiting to <code>Double</code> everywhere. Thank you.</p> <p>My DFT algorithm:</p> <pre><code> void dft(double[] inreal , double[] inimag, double[] outreal, double[] outimag) { int n = inreal.length; for (int k = 0; k &lt; n; k++) { // For each output element double sumreal = 0; double sumimag = 0; for (int t = 0; t &lt; n; t++) { // For each input element double angle = 2 * Math.PI * t * k / n; sumreal += inreal[t] * Math.cos(angle) + inimag[t] * Math.sin(angle); sumimag += -inreal[t] * Math.sin(angle) + inimag[t] * Math.cos(angle); } outreal[k] = sumreal; outimag[k] = sumimag; } } </code></pre> <p>My Haskell code:</p> <pre><code>-- Length of the array ownLength :: [t] -&gt; Int ownLength [] = 0 ownLength (_: xs) = 1 + ownLength xs dft_resolve_nested :: [((Double, Double), Double)] -&gt; Double -&gt; Int -&gt; [(Double, Double)] dft_resolve_nested [] _ _ = [] dft_resolve_nested (((x, y), t) : xs) k n = do let angle = 2.0 * pi * ( t) * ( k) / (fromIntegral n) let sumreal = x * (cos angle) + y * (sin angle) let sumimag = - x * (sin angle) + y * (cos angle) (sumreal, sumimag) : (dft_resolve_nested xs k n) tuples_sum :: [(Double, Double)] -&gt; (Double, Double) tuples_sum [] = (0, 0) tuples_sum ((x1, y1) : xs) = do let (x2, y2) = tuples_sum xs (x1 + x2, y1 + y2) dft_resolve :: [((Double, Double), Double)] -&gt; [(Double, Double)] dft_resolve [] = [] dft_resolve ls = do let n = ownLength ls let (((x, y), k) : xs) = ls let (xr, yr) = tuples_sum (dft_resolve_nested ls k n) (xr, yr) : (dft_resolve xs) dft :: [(Double, Double)] -&gt; [(Double, Double)] dft [] = [] dft ls = dft_resolve (zip ls [0..]) -- Main driver main = do print (dft [(1,2), (3,4)]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-10T17:36:20.003", "Id": "464590", "Score": "0", "body": "You do not need to simulate a Complex type, Haskell provides `Data.Complex`. It also has the function `cis` which is the exponential function of a purely imaginary number." } ]
[ { "body": "<p>Why are you reimplementing <code>length</code> O_o?</p>\n\n<pre><code>dft_resolve_nested :: Double -&gt; Int -&gt; [((Double, Double), Double)] -&gt; [(Double, Double)]\ndft_resolve_nested _ _ [] = []\ndft_resolve_nested k n (((x, y), t) : xs) = do\n let angle = 2.0 * pi * t * k / fromIntegral n\n let sumreal = x * cos angle + y * sin angle\n let sumimag = - x * sin angle + y * cos angle\n (sumreal, sumimag) : dft_resolve_nested k n xs\n\ntuples_sum :: [(Double, Double)] -&gt; (Double, Double)\ntuples_sum [] = (0, 0)\ntuples_sum ((x1, y1) : xs) = do\n let (x2, y2) = tuples_sum xs\n (x1 + x2, y1 + y2)\n\ndft_resolve :: [((Double, Double), Double)] -&gt; [(Double, Double)]\ndft_resolve [] = []\ndft_resolve ls@((_, k) : xs) = do\n let (xr, yr) = tuples_sum $ dft_resolve_nested ls k $ length ls\n (xr, yr) : dft_resolve xs\n\n-- Main driver\nmain = print $ dft_resolve $ zip [(1,2), (3,4)] [0..]\n</code></pre>\n\n<p>The explicit recursion can be done by library functions.</p>\n\n<pre><code>dft_resolve_nested :: Double -&gt; Int -&gt; ((Double, Double), Double) -&gt; (Double, Double)\ndft_resolve_nested k n ((x, y), t) = do\n let angle = 2.0 * pi * t * k / fromIntegral n\n sumreal = x * cos angle + y * sin angle\n sumimag = - x * sin angle + y * cos angle\n in (sumreal, sumimag)\n\ntuples_sum :: (Double, Double) -&gt; (Double, Double) -&gt; (Double, Double)\ntuples_sum (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)\n\ndft_resolve :: [((Double, Double), Double)] -&gt; (Double, Double)\ndft_resolve ls@((_, k) : _) = foldr tuples_sum (0,0) $\n map (dft_resolve_nested k $ length ls) ls\n\n-- Main driver\nmain = print $ map dft_resolve $ tails $ zip [(1,2), (3,4)] [0..]\n</code></pre>\n\n<p>Many of these names can be removed. You were also only ever restricted to <code>Double</code> by your own type signatures :). (You may want to tell it what <code>Floating</code> instance to use somewhere, though.)</p>\n\n<pre><code>import Data.NumInstances.Tuple\n\nmain :: IO ()\nmain = print\n [ sum\n [ ( x * cos angle + y * sin angle\n , -x * sin angle + y * cos angle\n )\n | (t, (x, y)) &lt;- ls\n , let angle = 2 * pi * t * k / genericLength ls\n ]\n | (k, ls) &lt;- zip [0..] $ tails [(1,2), (3,4)]\n ]\n</code></pre>\n\n<p>Edit: <code>Data.Complex</code> specializes in this sort of math:</p>\n\n<pre><code>import Data.Complex\n\nmain :: IO ()\nmain = print\n [ sum [z / cis angle ** t | (t, z) &lt;- ls]\n | (k, ls) &lt;- zip [0..] $ tails [1:+2, 3:+4]\n , let angle = 2 * pi * k / genericLength ls\n ]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-10T17:37:49.740", "Id": "464591", "Score": "0", "body": "`Data.NumInstances.Tuple` is an ugly hack. It would be more straightforward to use `Data.Complex` here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-11T11:27:17.280", "Id": "464721", "Score": "0", "body": "DNT is a straightforward mechanical greedy refactoring step. DC is a perfect fit that usually doesn't come into play, and I will endeavour to associate it with trigonometry from here on out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-11T15:16:47.893", "Id": "464770", "Score": "0", "body": "(**) on Complex numbers is a very bad idea. It is not well-defined and pretty slow. Better use `cis (angle*t)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-11T15:17:50.323", "Id": "464771", "Score": "0", "body": "Also Complex division is not necessary. You can just write `z * cis (-angle*t)`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T23:12:59.643", "Id": "236443", "ParentId": "236394", "Score": "2" } } ]
{ "AcceptedAnswerId": "236443", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T06:12:49.560", "Id": "236394", "Score": "1", "Tags": [ "haskell", "functional-programming" ], "Title": "Trying to convert imperetive code to functional -Haskell" }
236394
<p>I have 1-bit monochrome image which I have to put into a BYTE buffer. The monochrome image is kept to a dynamic memory of OLE_COLOR. I have to copy the color data to BYTE buffer. Before moving into trial and error, I would like to share if my algorithm is something that will do as I am expecting worth a review.</p> <pre><code> const long stride = 4; const long height = 32; const gsl::span&lt;const OLE_COLOR&gt; textureColors = {colorParam, gsl::narrow_cast&lt;gsl::span&lt;OLE_COLOR&gt;::index_type&gt;(width * height)}; std::vector&lt;BYTE&gt; texture; texture.resize(gsl::narrow_cast&lt;size_t&gt;(stride * height)); gsl::span&lt;BYTE&gt; colors = {texture}; for (long y = 0; y &lt; height; ++y) { const auto bitmapRow = textureColors.subspan(y, gsl::narrow_cast&lt;gsl::span&lt;OLE_COLOR&gt;::index_type&gt;(width)); const auto textureRow = colors.subspan(y * stride, stride); for (long s = 0; s &lt; stride; ++s) { auto&amp; destColors = *textureRow.subspan(s, 1).data(); for (int b = 0; b &lt; 8; ++b) { const auto srcColor = *bitmapRow.subspan(s * 8 + b, 1).data(); destColors += gsl::narrow_cast&lt;BYTE&gt;((destColors &lt;&lt; b) | srcColor); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T10:07:42.400", "Id": "463285", "Score": "0", "body": "Yes. The code is working. But I have faced other issues later using this data which is not related to this issue. Yes, I have to resize. You can see I have put the allocated memory to gsl::span I have access that memory later in loop for write." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T10:14:08.610", "Id": "463286", "Score": "0", "body": "@Juho Did you mean something like the getColors() ? I have edited." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T12:05:49.003", "Id": "463296", "Score": "0", "body": "Are you sure this works? `getColors` returns a `span` (non-owning view) of a local variable `texture`, that won't exist outside of the scope of `getColors`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T12:56:52.680", "Id": "463301", "Score": "0", "body": "I have restored back the original code. Someone suggested as review but looks like removed his comments already. The above code is working code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T17:39:07.053", "Id": "463478", "Score": "1", "body": "I would like to take a closer look. I need to know what headers you are including. Something for gsl? this? https://github.com/microsoft/GSL and something for OLE_COLOR? (sorry I am on Linux but can switch if required) If you can turn your algorithm into an executable with a `main()` and provide maybe a binary blob of the input image via an external link. Ideally also a blob file of the output image. Basically you need a \"test-harness\" to test your code. That will be essential for validating your algorithm, and for us to review it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T07:43:59.993", "Id": "236400", "Score": "0", "Tags": [ "c++", "algorithm" ], "Title": "Packing algorithm of 1-Bit monochrome image data to BYTE buffer" }
236400
<p>I'm new here and also into programming, I've made this small paper-scissors-rock project, and I would like to get it reviewed and know, how can I maybe:</p> <ul> <li>simplify my code</li> <li>make it perform better </li> </ul> <pre class="lang-cs prettyprint-override"><code>using System; using System.Threading; namespace PaperScissorsStoneGame { class Program { static void Main(string[] args) { /* this is the intetactive PaperScissorsStone Game * you will play interactively with the computer and * the first who earns 3 points won! */ PlayWithTheUser(); } /// &lt;summary&gt; /// interactive ShiFuMi game played with the computer and a user. /// &lt;/summary&gt; public static void PlayWithTheUser() { // runs the loop if userInput doesn't respect format bool isCorrect = true; int userInput = 0; string nameOfUser = ""; do { // display this message only when the user inputs the right format if (isCorrect == true) { Console.WriteLine("you are going to play with the computer to Shi-Fu-Mi a.k.a as PaperScissorsStone Game" + "\n"); Thread.Sleep(1000); } Console.WriteLine("are you ready? 1: yes 2: no"); // warning message in case of a non correct input format try { userInput = Convert.ToInt32(Console.ReadLine()); // if the conversion is possible it assigns true if (isCorrect = true &amp; userInput == 1) { Console.WriteLine("alright start off by entering your name please ! "); nameOfUser = Console.ReadLine(); } } catch (FormatException e) { Console.WriteLine(e.Message + "\n"); isCorrect = false; } } while (isCorrect == false); Console.WriteLine($" Alright {nameOfUser} use 1 for scissor, 2 for paper , 3 for rock" + "\n"); //5 seconds timer before beginning the game for (int i = 5; i &gt;= 0; i--) { if (i == 5) { Console.Write(" time: " + i); Thread.Sleep(1000); } else if (i &lt;= 4 &amp;&amp; i &gt;= 1) { Console.Write(" " + i + " "); Thread.Sleep(1000); } else { Console.Write("Go !" + "\n"); } } do { // if user inputs an incorrect format, it displays a warning message int userCommand = 0; try { userCommand = Convert.ToInt32(Console.ReadLine()); } catch (FormatException) { Console.WriteLine("please enter a number between 1 to 3"); } Random rand = new Random(); int computerCommand = rand.Next(1, 4); // says who's the winner according to the input switch (userCommand) { // user choose scissors case 1: if (computerCommand == 1) { Console.WriteLine($"computer = scissors {nameOfUser} = scissors: that's even!"); } else if (computerCommand == 2) { Console.WriteLine($"computer = paper {nameOfUser} = scissors: you won!"); } else if (computerCommand == 3) { Console.WriteLine($"computer = rock {nameOfUser} = scissors: You lost!"); } break; // user choose paper case 2: if (computerCommand == 1) { Console.WriteLine(($"computer = scissors {nameOfUser} = paper: You lost!")); } else if (computerCommand == 2) { Console.WriteLine($"computer = paper { nameOfUser} = paper: that's even!"); } else if (computerCommand == 3) { Console.WriteLine($"computer = rock {nameOfUser} = paper: You won!"); } break; // user choose rock case 3: if (computerCommand == 1) { Console.WriteLine($"computer = scissors {nameOfUser} = rock: You won!"); } else if (computerCommand == 2) { Console.WriteLine($"computer = paper {nameOfUser} = rock: You lost!"); } else if (computerCommand == 3) { Console.WriteLine($"computer = rock {nameOfUser} = rock: that's even!"); } break; default: break; } } while (true); } } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>I can see a few big wins in terms of making this easier to read and understand;</p>\n\n<p><strong>Smaller Functions</strong></p>\n\n<p>At the moment, you have a <code>PlayWithTheUser()</code> function which is very long and contains all of the program logic directly. This would be better split out into several separate functions, so that your initial play function looks more like;</p>\n\n<pre><code>public static void Play() {\n EnsureUserReady();\n var name = GetUserName();\n while (true) {\n PlayRound(name);\n }\n}\n</code></pre>\n\n<p>In this, each of the functions <code>EnsureUserReady()</code>, <code>GetUserName()</code>, and <code>PlayRound()</code> would be doing what their names suggest (roughly the separate sections of your initial code, potentially each split out further). </p>\n\n<p>The idea is that any function only really does one thing at whichever level of abstraction it is working on. So e.g. <code>PlayRound()</code> is a single thing in terms of the outer function, but probably splits itself into a few separate functions: e.g. <code>GetUserPlay()</code> (which takes in the user input), <code>GetComputerPlay()</code> (which outputs the computer's choice - maybe easy now, but it could get more nuanced if you wanted), and <code>DetermineWinner(userPlay, computerPlay)</code> (which prints the output).</p>\n\n<p><strong>Enums</strong></p>\n\n<p>C# has an enum type, which is perfect for this type of small-number-of-valid-choices thing. So instead of using integers that mean rock, paper, and scissors, you can define;</p>\n\n<pre><code>public enum Play {\n Rock,\n Paper,\n Scissors\n}\n</code></pre>\n\n<p>(This should be given a better name, but I can't think of one off the top of my head.)</p>\n\n<p>This can then be used for comparison a lot more easily, and it's a lot clearer to check if a variable is equal to <code>Play.Rock</code> than if it is equal to <code>1</code>, for example.</p>\n\n<p>It does mean that you'll need to do something a little different to parse input into this type. There are integers underlying enum values, so they can be entered that way if you specify in the enum which integer should map to which value, but you may want to consider having the user entering a string or a letter and parse that (as it's going to be a bit easier for the user to remember which option they are choosing that way).</p>\n\n<p><strong>Start/End control</strong></p>\n\n<p>You've got a comment in the code that says it will be first to 3 points, but at the moment that isn't tracked in the code - it will just continue forever. There should either be a way for the user to exit at a point they choose, or a defined end (or possibly both).</p>\n\n<p>This might mean checking at the end of each round whether the user wants to continue, and probably means keeping track of the total scores. Exactly how you want to implement this will vary based on exactly what you want to do.</p>\n\n<p>Somewhat relatedly, using <code>while (true)</code> is always a bit worrying in terms of being an infinite loop if there<code>s nothing guaranteed to break out of it. It is clearer (and safer in terms of accidentally introducing bugs) to refactor to have</code>while (condition)` where condition is then updated within the loop (whether that's a counter, or a toggle for whether the user wants to continue, or a property of the score, or something else).</p>\n\n<hr>\n\n<p>So, those are some things to start off with. There's a lot you could decide you wanted to change based on exactly what you might want to do (e.g. cleaning up the win/lose checking, taking the game out into a separate class which might be stateful to keep track of scores etc), but the above should give you a good set of first pass improvements.</p>\n\n<p>In terms of learning - I suggest you try things and see where you get, and then look for another review.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T11:31:36.923", "Id": "236411", "ParentId": "236409", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T10:19:26.093", "Id": "236409", "Score": "2", "Tags": [ "c#", "rock-paper-scissors" ], "Title": "play paper-scissors-rock with the user" }
236409
<p>I'm in the process of implementing a fully generic service to filter out entries (of any type), which are contained in a <code>ICollection</code>. As it is generic, without any constraints, the properties must be accessed through reflection. I'm not fully happy with the performance, even though it respects the minimum response times. </p> <p>Here's the definition:</p> <pre><code>public interface IPowerSearchService { /// &lt;summary&gt; /// Gets the filtered entries by applying the rules defined by &lt;see cref="expression" /&gt; to the items received in &lt;see cref="collection" /&gt;. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;The type of the object/interface to filter.&lt;/typeparam&gt; /// &lt;param name="collection"&gt;The collection containg all items.&lt;/param&gt; /// &lt;param name="expression"&gt;The expression.&lt;/param&gt; /// &lt;returns&gt;All items respecting the &lt;see cref="expression"/&gt;.&lt;/returns&gt; IEnumerable&lt;T&gt; GetFilteredEntries&lt;T&gt;(ICollection&lt;T&gt; collection, IPowerSearchExpressionNode expression); } </code></pre> <p>Note that there is no constraint whatsover for <code>T</code>.</p> <p>With interfaces:</p> <pre><code>public interface IPowerSearchExpressionNode { IPowerSearchConditionBase Left { get; set; } IPowerSearchConditionBase Right { get; set; } PowerSearchOperator Operator { get; set; } } public interface IPowerSearchConditionBase { bool IsLeaf { get; } } public interface IPowerSearchConditionLeaf: IPowerSearchConditionBase { PowerSearchOperation Operation { get; } string FieldName { get; } object Value { get; } } public interface IPowerSearchConditionExpression: IPowerSearchConditionBase { IPowerSearchExpressionNode Expression { get; } } </code></pre> <p>and implementations:</p> <pre><code>internal class PowerSearchExpressionNode : IPowerSearchExpressionNode { public IPowerSearchConditionBase Left { get; set; } public IPowerSearchConditionBase Right { get; set; } public PowerSearchOperator Operator { get; set; } } internal abstract class PowerSearchConditionBase : IPowerSearchConditionBase { protected PowerSearchConditionBase(bool isLeaf) { IsLeaf = isLeaf; } public bool IsLeaf { get; } } internal class PowerSearchConditionLeaf : PowerSearchConditionBase, IPowerSearchConditionLeaf { public PowerSearchConditionLeaf() : base(true) { } public PowerSearchOperation Operation { get; set; } public string FieldName { get; set; } public object Value { get; set; } } internal class PowerSearchConditionExpression : PowerSearchConditionBase, IPowerSearchConditionExpression { public PowerSearchConditionExpression() : base(false) { } public IPowerSearchExpressionNode Expression { get; set; } } [Flags] public enum PowerSearchOperation { Is = 0, IsNot = 1, Contains = 2, DoesNotContain = 4, StartsWith = 8, DoesNotStartWith = 16 } [Flags] public enum PowerSearchOperator { Or = 0, And = 1 } </code></pre> <p>Full implementation of <code>PowerSearchService</code>:</p> <pre><code>public class PowerSearchService : IPowerSearchService { private readonly IDictionary&lt;PropertyCacheKey, PropertyInfo&gt; _propertiesCache = new ConcurrentDictionary&lt;PropertyCacheKey, PropertyInfo&gt;(); public IEnumerable&lt;T&gt; GetFilteredEntries&lt;T&gt;(ICollection&lt;T&gt; collection, IPowerSearchExpressionNode expression) { var leftResult = GetFilteredEntries(collection, expression.Left); var rightResult = GetFilteredEntries(collection, expression.Right); // Do NOT consider the operator if either the left or right condition are null if (expression.Left == null) { return rightResult; } if (expression.Right == null) { return leftResult; } switch (expression.Operator) { case PowerSearchOperator.And: return leftResult.Intersect(rightResult); case PowerSearchOperator.Or: return leftResult.Union(rightResult); default: throw new NotSupportedException($"Operator {expression.Operator} is not supported for power search expressions not being leafs."); } } private IEnumerable&lt;T&gt; GetFilteredEntries&lt;T&gt;(ICollection&lt;T&gt; collection, IPowerSearchConditionBase condition) { // How it works: // 1) Return an empty list if the condition is null // 2) Return the matching results if we have a leaf condition // 3) Do a recursive call if we have an expression condition return condition == null ? Enumerable.Empty&lt;T&gt;() : condition.IsLeaf ? collection.Where(p =&gt; MatchesCondition((IPowerSearchConditionLeaf) condition, p)) : GetFilteredEntries(collection, ((IPowerSearchConditionExpression) condition).Expression); } private bool MatchesCondition&lt;T&gt;(IPowerSearchConditionLeaf condition, T obj) { var entityValues = GetPropertyValues(obj, condition.FieldName).Distinct(); return entityValues.Any(entityValue =&gt; MatchesSingleContition(condition, entityValue)); } [SuppressMessage("ReSharper", "MergeCastWithTypeCheck")] [SuppressMessage("ReSharper", "PossibleNullReferenceException")] [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] private bool MatchesSingleContition(IPowerSearchConditionLeaf condition, object obj) { var searchValue = condition.Value; var entityStringValue = obj as string; var searchStringValue = searchValue as string; switch (condition.Operation) { case PowerSearchOperation.Contains: ThrowNotSupportedExceptionIfNotString(searchValue, PowerSearchOperation.Contains); return entityStringValue != null &amp;&amp; CultureInfo.InvariantCulture.CompareInfo.IndexOf(entityStringValue, searchStringValue, CompareOptions.IgnoreCase) &gt;= 0; case PowerSearchOperation.DoesNotContain: ThrowNotSupportedExceptionIfNotString(searchValue, PowerSearchOperation.Contains); return entityStringValue == null || CultureInfo.InvariantCulture.CompareInfo.IndexOf(entityStringValue, searchStringValue, CompareOptions.IgnoreCase) &lt; 0; case PowerSearchOperation.Is: if (entityStringValue != null &amp;&amp; searchStringValue != null) { return searchStringValue.Equals(entityStringValue, StringComparison.InvariantCultureIgnoreCase); } return searchValue != null &amp;&amp; searchValue.Equals(obj); case PowerSearchOperation.IsNot: if (entityStringValue != null &amp;&amp; searchStringValue != null) { return !searchStringValue.Equals(entityStringValue, StringComparison.InvariantCultureIgnoreCase); } return searchValue == null || !searchValue.Equals(obj); case PowerSearchOperation.StartsWith: ThrowNotSupportedExceptionIfNotString(searchStringValue, PowerSearchOperation.StartsWith); return entityStringValue != null &amp;&amp; entityStringValue.StartsWith(searchStringValue, StringComparison.InvariantCultureIgnoreCase); case PowerSearchOperation.DoesNotStartWith: ThrowNotSupportedExceptionIfNotString(searchStringValue, PowerSearchOperation.DoesNotStartWith); return entityStringValue == null || !entityStringValue.StartsWith(searchStringValue, StringComparison.InvariantCultureIgnoreCase); default: throw new NotSupportedException($"PowerSearchOperation {condition.Operation} is not supported"); } } private IEnumerable&lt;object&gt; GetPropertyValues(object src, string propertyName) { if (src == null) { throw new ArgumentException("Value cannot be null.", nameof(src)); } if (propertyName == null) { throw new ArgumentException("Value cannot be null.", nameof(propertyName)); } while (true) { if (propertyName.Contains(".")) { var propertyNameElements = propertyName.Split(new[] {'.'}, 2); // Replace src by a list, in order to use all values of a property being contained in a enumerable if (src is IEnumerable srcEnumerable) { var tmpSrc = new List&lt;object&gt;(); foreach (var element in srcEnumerable) { var propertyValue = GetPropertyValues(element, propertyNameElements[0]); tmpSrc.AddRange(propertyValue.Where(pv =&gt; pv != null)); } src = tmpSrc; } else { // Use the single property value src = GetPropertyValues(src, propertyNameElements[0]); } propertyName = propertyNameElements[1]; } else { // Support a src being a list (enumerable) if (src is IEnumerable srcEnumerable) { foreach (var element in srcEnumerable) { // The elements contained in a enumerable can be objects or enumerabels; forward them correctly. yield return element is IEnumerable ? GetPropertyValues(element, propertyName) : GetPropertyValue(element, propertyName); } break; } // Handle properties having a value yield return GetPropertyValue(src, propertyName); break; } } } private object GetPropertyValue(object src, string propertyName) { var propertyCacheKey = new PropertyCacheKey(src.GetType(), propertyName); if (!_propertiesCache.TryGetValue(propertyCacheKey, out var propertyInfo)) { var srcType = src.GetType(); propertyInfo = srcType.GetProperty(propertyName); if (propertyInfo == null) { throw new NotSupportedException($"The property {propertyName} does not exist for type {srcType.Name}"); } _propertiesCache.Add(propertyCacheKey, propertyInfo); } return propertyInfo.GetValue(src, null); } private void ThrowNotSupportedExceptionIfNotString(object value, PowerSearchOperation operation) { if (!(value is string)) { throw new NotSupportedException($"{operation} is only supported for values of type {nameof(String)}. Type was {value?.GetType()}"); } } [SuppressMessage("ReSharper", "MemberCanBePrivate.Local")] private class PropertyCacheKey { public PropertyCacheKey(Type type, string propetyName) { Type = type; PropetyName = propetyName; } private bool Equals(PropertyCacheKey other) =&gt; Type == other.Type &amp;&amp; PropetyName == other.PropetyName; public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((PropertyCacheKey) obj); } public override int GetHashCode() { unchecked { return ((Type != null ? Type.GetHashCode() : 0) * 397) ^ (PropetyName != null ? PropetyName.GetHashCode() : 0); } } public Type Type { get; } public string PropetyName { get; } } } </code></pre> <p>A profiling session with JetBrains dotTrace shows following: <a href="https://i.stack.imgur.com/kLEoL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kLEoL.png" alt="enter image description here"></a></p> <p>The above result has been generated with following console test app. If useful I can also include the <code>Product</code> class along with the other required classes.</p> <pre><code>public class Program { private const int NbTestProducts = 500000; public static void Main(string[] args) { // Arrange var products = GetTestProducts().ToList(); var powerSearchService = new PowerSearchService(); const string productNameSearchValue = "uct-1"; IPowerSearchExpressionNode expression = new PowerSearchExpressionNode { Left = new PowerSearchConditionLeaf { FieldName = nameof(Product.Name), Value = productNameSearchValue, Operation = PowerSearchOperation.Contains }, Operator = PowerSearchOperator.Or, Right = new PowerSearchConditionExpression { Expression = new PowerSearchExpressionNode { Left = new PowerSearchConditionLeaf { Operation = PowerSearchOperation.StartsWith, FieldName = $"{nameof(Product.Type)}.{nameof(ProductType.Name)}", Value = "Type-3" }, Operator = PowerSearchOperator.Or, Right = new PowerSearchConditionLeaf { Operation = PowerSearchOperation.StartsWith, FieldName = $"{nameof(Product.Substances)}.{nameof(Substance.Name)}", Value = "stance-4-5" } } } }; // Act var stopwatch = new Stopwatch(); stopwatch.Start(); var filteredProducts = powerSearchService.GetFilteredEntries(products, expression) .ToList(); stopwatch.Stop(); var resume = $"Found {filteredProducts.Count} products out of {products.Count} in {stopwatch.ElapsedMilliseconds}ms:"; // Show result in console System.Console.WriteLine(resume); //filteredProducts.ForEach(System.Console.WriteLine); // Log result in file //File.WriteAllText($"filteredProducts-{DateTime.Now:yyyy-MM-ddTHH-mm-ss}.txt", resume + Environment.NewLine + string.Join(Environment.NewLine, filteredProducts)); //System.Console.ReadKey(); } private static IEnumerable&lt;Product&gt; GetTestProducts() { for (var i = 0; i &lt; NbTestProducts; i++) { yield return new Product { Name = $"Product-{i}", Type = new ProductType { Name = $"Type-{i}" }, Substances = { new Substance {Name = $"Substance-1-{i}"}, new Substance {Name = $"Substance-2-{i}"}, new Substance {Name = $"Substance-3-{i}"}, new Substance {Name = $"Substance-4-{i}"}, new Substance {Name = $"Substance-5-{i}"}, new Substance {Name = $"Substance-6-{i}"} } }; } } } </code></pre> <p>Do you see any possibilities to optimize execution?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T14:48:13.587", "Id": "463314", "Score": "0", "body": "Can you post PowerSearchOperation also you are missing the interfaces for Conditional classes and ExpressionNode." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T14:57:00.387", "Id": "463318", "Score": "0", "body": "@CharlesNRice Sure, I've added a new interfaces section (including the missing interfaces) and added the missing enums to the implementations block" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T11:32:39.757", "Id": "463443", "Score": "0", "body": "Have you tried delegates Fun<T> or Predicate<T> or Expression<T> ? i think you can make use of them in your implementation to minimize use of Reflection." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T13:35:12.860", "Id": "463454", "Score": "0", "body": "@iSR5 No I haven't. How do you think they might be useful?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T14:44:47.667", "Id": "464923", "Score": "0", "body": "I started to review this awhile ago but then felt like I was just recreating dynamic linq. Might be worth looking into that." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T13:16:01.663", "Id": "236414", "Score": "2", "Tags": [ "c#", "linq", "generics", ".net-core" ], "Title": "Generic search service to filter entries in lists" }
236414
<p>I use a change of groupbox locations depending on the number of weeks in the month. Is there any possibility for me to improve the functionality of this code a little bit, is it slow to load on this part? Thank you all for your help.</p> <pre><code>FormWindowState LastWindowState = FormWindowState.Minimized; private void Form1_Resize(object sender, EventArgs e) { // When window state changes if (WindowState != LastWindowState) { LastWindowState = WindowState; if (numberOfWeek == 4) { groupBoxFifthWeek.Hide(); groupBoxSixthWeek.Hide(); if (WindowState == FormWindowState.Maximized) { groupBoxFirstWeek.Location = new Point(1685, 140); groupBoxSecondWeek.Location = new Point(1685, 325); groupBoxThirdWeek.Location = new Point(1685, 510); groupBoxFourthWeek.Location = new Point(1685, 700); } if (WindowState == FormWindowState.Normal) { groupBoxFirstWeek.Location = new Point(978, 105); groupBoxSecondWeek.Location = new Point(978, 220); groupBoxThirdWeek.Location = new Point(978, 345); groupBoxFourthWeek.Location = new Point(978, 468); } } else if (numberOfWeek == 5) { groupBoxFifthWeek.Show(); groupBoxSixthWeek.Hide(); if (WindowState == FormWindowState.Maximized) { groupBoxFirstWeek.Location = new Point(1685, 120); groupBoxSecondWeek.Location = new Point(1685, 265); groupBoxThirdWeek.Location = new Point(1685, 415); groupBoxFourthWeek.Location = new Point(1685, 570); groupBoxFifthWeek.Location = new Point(1685, 720); } if (WindowState == FormWindowState.Normal) { groupBoxFirstWeek.Location = new Point(978, 89); groupBoxSecondWeek.Location = new Point(978, 187); groupBoxThirdWeek.Location = new Point(978, 284); groupBoxFourthWeek.Location = new Point(978, 383); groupBoxFifthWeek.Location = new Point(978, 484); } } else { groupBoxSixthWeek.Show(); if (WindowState == FormWindowState.Maximized) { groupBoxFirstWeek.Location = new Point(1685, 105); groupBoxSecondWeek.Location = new Point(1685, 230); groupBoxThirdWeek.Location = new Point(1685, 357); groupBoxFourthWeek.Location = new Point(1685, 482); groupBoxFifthWeek.Location = new Point(1685, 610); groupBoxSixthWeek.Location = new Point(1685, 737); } if (WindowState == FormWindowState.Normal) { groupBoxFirstWeek.Location = new Point(978, 79); groupBoxSecondWeek.Location = new Point(978, 162); groupBoxThirdWeek.Location = new Point(978, 244); groupBoxFourthWeek.Location = new Point(978, 328); groupBoxFifthWeek.Location = new Point(978, 412); groupBoxSixthWeek.Location = new Point(978, 496); } } } } </code></pre>
[]
[ { "body": "<p>I don't think there is much you can do in here performance-wise. However, you could improve the readability of your code with a few little things. </p>\n\n<p>I'd personally use a switch statement instead of repeated else/if. It's simpler to read, we know right from the start that all conditions are based on \"numberOfWeek\".</p>\n\n<p>Maybe there is something we could do repeated Maximized or Minimized conditions and groupBox locations assignments, but I don't really know right now.</p>\n\n<p>Also, I'd return early if the WindowState is equal to LastWindowState. It makes code clearer, and we don't need to go all the way down your class to see that, in case WindowState hasn't changed, you do nothing.</p>\n\n<pre><code> private void Form1_Resize(object sender, EventArgs e)\n {\n if (WindowState == LastWindowState)\n {\n return;\n }\n\n LastWindowState = WindowState;\n\n switch (numberOfWeek)\n {\n case 4:\n groupBoxFifthWeek.Hide();\n groupBoxSixthWeek.Hide();\n if (WindowState == FormWindowState.Maximized)\n {\n groupBoxFirstWeek.Location = new Point(1685, 140);\n groupBoxSecondWeek.Location = new Point(1685, 325);\n groupBoxThirdWeek.Location = new Point(1685, 510);\n groupBoxFourthWeek.Location = new Point(1685, 700);\n }\n if (WindowState == FormWindowState.Normal)\n {\n groupBoxFirstWeek.Location = new Point(978, 105);\n groupBoxSecondWeek.Location = new Point(978, 220);\n groupBoxThirdWeek.Location = new Point(978, 345);\n groupBoxFourthWeek.Location = new Point(978, 468);\n }\n break;\n\n case 5:\n groupBoxFifthWeek.Show();\n groupBoxSixthWeek.Hide();\n\n if (WindowState == FormWindowState.Maximized)\n {\n groupBoxFirstWeek.Location = new Point(1685, 120);\n groupBoxSecondWeek.Location = new Point(1685, 265);\n groupBoxThirdWeek.Location = new Point(1685, 415);\n groupBoxFourthWeek.Location = new Point(1685, 570);\n groupBoxFifthWeek.Location = new Point(1685, 720);\n }\n if (WindowState == FormWindowState.Normal)\n {\n groupBoxFirstWeek.Location = new Point(978, 89);\n groupBoxSecondWeek.Location = new Point(978, 187);\n groupBoxThirdWeek.Location = new Point(978, 284);\n groupBoxFourthWeek.Location = new Point(978, 383);\n groupBoxFifthWeek.Location = new Point(978, 484);\n }\n break;\n\n default:\n groupBoxSixthWeek.Show();\n if (WindowState == FormWindowState.Maximized)\n {\n groupBoxFirstWeek.Location = new Point(1685, 105);\n groupBoxSecondWeek.Location = new Point(1685, 230);\n groupBoxThirdWeek.Location = new Point(1685, 357);\n groupBoxFourthWeek.Location = new Point(1685, 482);\n groupBoxFifthWeek.Location = new Point(1685, 610);\n groupBoxSixthWeek.Location = new Point(1685, 737);\n }\n if (WindowState == FormWindowState.Normal)\n {\n groupBoxFirstWeek.Location = new Point(978, 79);\n groupBoxSecondWeek.Location = new Point(978, 162);\n groupBoxThirdWeek.Location = new Point(978, 244);\n groupBoxFourthWeek.Location = new Point(978, 328);\n groupBoxFifthWeek.Location = new Point(978, 412);\n groupBoxSixthWeek.Location = new Point(978, 496);\n }\n break;\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T14:52:27.977", "Id": "236419", "ParentId": "236415", "Score": "3" } }, { "body": "<p>since in the suggested code you're creating new point object on each pass; you could create some static points in a collection and use them instead of creating new ones each time.</p>\n\n<p>Example:</p>\n\n<pre><code>Static IDictionary&lt;WindowState,IList&lt;Point&gt; points = new \nDictionary&lt;WindowState,IList&lt;Point&gt;(){\n{ FormWindowState.Maximized, new List&lt;Point&gt;{\n {new Point(1685, 105)},\n {new Point(1685, 230)} //....\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-05T07:23:45.150", "Id": "463967", "Score": "0", "body": "thanks for your suggestion, what whole change would be made based on my code?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T19:00:56.870", "Id": "236477", "ParentId": "236415", "Score": "1" } } ]
{ "AcceptedAnswerId": "236419", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T14:22:02.033", "Id": "236415", "Score": "2", "Tags": [ "c#" ], "Title": "Improving code functionality" }
236415
<p>I am a new python programmer. I have created the code to put API data from pipedrive to Snowflake database. Here are the steps in my code.</p> <ol> <li>Delete the csv file if it exists.</li> <li>Make an API call put all the paginated data in a list. </li> <li>Create a csv file from the list.</li> <li>Truncate the table in Snowflake.</li> <li>Remove data from Snowflake stage table</li> <li>Put the data in Snowflake stage table.</li> <li>Copy data from stage table to a normal table.</li> </ol> <p>I would love to get some feedback on it as I will create more scripts based on this code.</p> <p>Here is my code.</p> <pre class="lang-py prettyprint-override"><code>import requests from module import usr, pwd, acct, db, schem, api_token import snowflake.connector import datetime import time from datetime import datetime import csv import os import contextlib end_point = 'persons' limit = 500 start = 0 start_time = time.time() csvfile = r'C:/Users/User1/PycharmProjects/Pipedrive/persons.csv' def snowflake_connect(): mydb = snowflake.connector.connect( user=usr, password=pwd, account=acct, database=db, schema=schem, ) cursor = mydb.cursor() return cursor def snowflake_truncate(cursor): print("Truncating table PERSONS_NEW: {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) cursor.execute('TRUNCATE TABLE PERSONS_NEW') print("PERSONS_NEW truncated: {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) return cursor def snowflake_insert(cursor): cursor.execute("remove @persons_test pattern='.*.csv.gz'") for c in cursor: print(c, datetime.now().strftime("%Y-%m-%d %H:%M:%S")) cursor.execute('put file://{} @persons_test auto_compress=true'.format(csvfile)) for c in cursor: print(c, datetime.now().strftime("%Y-%m-%d %H:%M:%S")) cursor.execute("""COPY INTO MARKETING.PIPEDRIVE_MASTER.persons_new FROM @persons_test/persons.csv.gz file_format=(TYPE=csv field_delimiter=',' skip_header=0 FIELD_OPTIONALLY_ENCLOSED_BY = '"') on_error = 'abort_statement'""") for c in cursor: print(c, datetime.now().strftime("%Y-%m-%d %H:%M:%S")) def get_persons(start): url = 'https://company.pipedrive.com/v1/{}?user_id=0&amp;start={}&amp;limit={}&amp;api_token={}'.format(end_point, start, limit, api_token) response = requests.request("GET", url).json() while (response['additional_data']['pagination']['more_items_in_collection']): url = 'https://company.pipedrive.com/v1/{}?user_id=0&amp;start={}&amp;limit={}&amp;api_token={}'.format(end_point, start, limit, api_token) response = requests.request("GET", url).json() read_persons(response) start = start + 500 def read_persons(response): for data in response['data']: id = data['id'] activities_count = data['activities_count'] if data['add_time'] == '': add_time = None else: add_time = data['add_time'] closed_deals_count = data['closed_deals_count'] company_id = data['company_id'] done_activities_count = data['done_activities_count'] followers_count = data['followers_count'] label = data['label'] last_activity_date = data['last_activity_date'] last_activity_id = data['last_activity_id'] last_incoming_mail_time = data['last_incoming_mail_time'] last_name = data['last_name'] last_outgoing_mail_time = data['last_outgoing_mail_time'] lost_deals_count = data['lost_deals_count'] name = data['name'] next_activity_date = data['next_activity_date'] next_activity_id = data['next_activity_id'] next_activity_time = data['next_activity_time'] notes_count = data['notes_count'] open_deals_count = data['open_deals_count'] if data['org_id'] == None: org_id = None else: org_id = data['org_id']['value'] org_name = data['org_name'] fieldnames = [id, activities_count, add_time, cc_email, closed_deals_count, company_id, done_activities_count, followers_count, label, last_activity_date, last_activity_id, last_incoming_mail_time, last_name, last_outgoing_mail_time, lost_deals_count, name, next_activity_date, next_activity_id, next_activity_time, notes_count, open_deals_count, org_id, org_name] write_csv(fieldnames) def delete_existing_csv(): with contextlib.suppress(FileNotFoundError): os.remove(csvfile) def write_csv(fieldnames): with open(csvfile, "a", encoding="utf-8", newline='') as fp: wr = csv.writer(fp, delimiter=',') wr.writerow(fieldnames) if __name__ == "__main__": delete_existing_csv() print("Creating CSV file: {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) get_persons(start) print("CSV file succesfully created: {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) cursor = snowflake_connect() snowflake_truncate(cursor) snowflake_insert(cursor) cursor.close() end_time = time.time() elapsed_time = round(end_time - start_time, 2) print("Job sucessfully completed in: {} seconds".format(elapsed_time)) </code></pre>
[]
[ { "body": "<p>The script looks pretty good to me.</p>\n\n<p>The biggest issue is that if you plan to execute this code multiple times, it's not really efficient. I think you should check for existing persons in Snowflake, and then only add the persons that are not yet in there. I'm not sure how Snowflake works so I can't help you with that, but my approach would be to create a <code>Person</code> class, create a <code>__hash__</code> and an <code>__eq__</code> method, and put all existing persons in a <code>set</code>. Then for each person you read from Pipedrive, check if it is in the Persons set, and if it's not, add it to Snowflake. This would prevent costly <code>truncate</code> operations plus a lot of <code>insert</code> operations, in case you have a lot of persons in your Pipedrive.</p>\n\n<p>Next, add some comments. The code should be self-explanatory so you could incorporate the steps you mentioned above as comments.</p>\n\n<p>Finally, regarding global variables (PEP dictates they be capitalized):</p>\n\n<ul>\n<li>Rename <code>limit</code> to <code>PIPEDRIVE_PAGINATION_LIMIT</code></li>\n<li>Remove the <code>start</code> variable and initialize <code>get_persons(start=0)</code></li>\n<li>Put <code>start_time</code> under <code>if __name__ == \"__main__\"</code></li>\n<li>Rename <code>csv_file</code> to <code>PIPEDRIVE_PERSONS_CSV</code></li>\n</ul>\n\n<p>For the commenting and global variables stuff, try linting your code, for example using <code>pylint</code>. It'll give you hints on what you can improve about your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T15:30:28.660", "Id": "463319", "Score": "0", "body": "Thanks for the feedback. I will change my variables according to PEP. I know multiple truncates and inserts are not efficient in general. But in this case I have only few thousands rows of data. This data can change. So instead of keeping track of updates for more than 30 columns (here I just put a small set of fields) for a small data set I decided to truncate and load. It takes average 11 seconds to do that with Snowflake stage table." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T14:52:31.830", "Id": "236420", "ParentId": "236416", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T14:22:15.833", "Id": "236416", "Score": "3", "Tags": [ "python", "python-3.x", "csv", "api", "database" ], "Title": "Get data from pipedrive API and insert it into Snowflake" }
236416
<p>This method splits up two comma separated items, if they exist, and increments the amount if the are already in the list; otherwise add the item to the list</p> <p>I want to know if this code can be optimized some more. Any suggestions?</p> <p>The method below works 100% fine but I feel like it is not neatly done.</p> <pre><code>private void SeperateJoinedDisposables(IEnumerable&lt;Models.Container&gt; joinedDisposables) { if (!joinedDisposables.Any()) return; foreach (var item in joinedDisposables.ToList()) { var amount = item.Amount; var container = item.Container; var disposable1 = container.Substring(0, container.IndexOf(",")); var disposable2 = container.Substring(container.IndexOf(",") + 1); DisposablesModel.Containers.Remove(item); var disposableCointians1 = DisposablesModel.Containers.FirstOrDefault(x =&gt; x.Container.ToUpper().Contains(disposable1.ToUpper())); var disposableCointians2 = DisposablesModel.Containers.FirstOrDefault(x =&gt; x.Container.ToUpper().Contains(disposable2.ToUpper())); if (disposableCointians1 != null) disposableCointians1.Amount = (int.Parse(disposableCointians1.Amount) + int.Parse(amount)).ToString(); else DisposablesModel.Containers.Add(new Models.Container { Amount = amount, Container = disposable1 }); if (disposableCointians2 != null) disposableCointians2.Amount = (int.Parse(disposableCointians2.Amount) + int.Parse(amount)).ToString(); else DisposablesModel.Containers.Add(new Models.Container { Amount = amount, Container = disposable2 }); } } </code></pre> <p>Here is my model class</p> <pre><code> public class DisposablesModel { public string Barcode { get; set; } public string RushColor { get; set; } public string RushDescription { get; set; } public string Pollution { get; set; } public int NumberOfSamples { get; set; } public List&lt;Container&gt; Containers { get; set; } public bool IsSubcontracted { get; set; } } public class Container { public string Amount { get; set; } public string Container { get; set; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T23:27:29.933", "Id": "463395", "Score": "0", "body": "is `items.Container` a typo? `item` is of type `Models.Container`, therefore it can't have a member of the same name." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T08:28:06.247", "Id": "463430", "Score": "1", "body": "It would be great question if you just provided a sample input and include `Models.Container` class as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-07T11:57:05.057", "Id": "464244", "Score": "0", "body": "I've included the model class in the edited version. @iSR5" } ]
[ { "body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><p>The class \"Container\" has a property named \"Container\"? That is... confusing, to say the least. Hence you having to name it <code>item</code> when iterating through it, which is unclear (and thus bad). </p></li>\n<li><p>\"Cointians\" has two typos.</p></li>\n<li><p>If you need to have a case insensitive <code>Contains()</code>, there are better ways to do it than use <code>ToUpper()</code>: <a href=\"https://stackoverflow.com/a/54686459/648075\">https://stackoverflow.com/a/54686459/648075</a></p></li>\n<li><p>Do not copy-paste logic when it is the same for two cases; instead move it to a method and call it.</p></li>\n<li><p>Why is the property Amount a <code>string</code> instead of an <code>int</code>? Your code constantly needs to converts <code>string</code>s to <code>int</code>s and vice versa; why not use the proper types instead and avoid all that?</p></li>\n<li><p>Is the Container of a Container always a comma-separated string of two items? Why then not make it a <code>List&lt;string&gt; Names</code>?</p></li>\n</ul>\n\n<hr>\n\n<p>Most impotantly: due to the bad names, I have trouble figuring out what your code actually does. </p>\n\n<p>That <code>joinedDisposables</code> is a list of <code>Container</code>s is unclear, and due to \"Container\" being both the name of a class as well as one of its properties the code becomes even more unclear. </p>\n\n<p>I have the impression that once your <code>Container</code> class has a \"proper\" structure, much of this code can be replaced by simple LINQ queries; it's just that the bad names and the bad structures obfuscate so much it makes things hard to grasp.</p>\n\n<p>To me it looks like <code>public List&lt;Container&gt; Containers { get; set; }</code> should be a <code>Dictionary&lt;string, int&gt;</code>, and that what you pass to <code>SeperateJoinedDisposables</code> should be a <code>List&lt;string&gt;</code> where each <code>string</code> is a comma separated list. And then your code would be something like this:</p>\n\n<pre><code>Dictionary&lt;string, int&gt; Containers = new Dictionary&lt;string, int&gt;();\n\nprivate void Parse(List&lt;string&gt; commaSeparatedValues)\n{\n foreach (var commaSeparatedValue in commaSeparatedValues)\n {\n foreach (var value in commaSeparatedValue.Split(','))\n {\n var normalisedValue = value.ToLower();\n\n if (!Containers.TryGetValue(normalisedValue, out int count))\n {\n count = 0;\n }\n\n count++;\n Containers[normalisedValue] = count;\n }\n }\n}\n</code></pre>\n\n<p>To me this code expresses far more clearly the intent of what you're trying to do -- if I correctly understand the purpose of your code, of course. </p>\n\n<p>But then I don't know where <code>IEnumerable&lt;Models.Container&gt; joinedDisposables</code> comes from and how it is constructed and why it is constructed that way, so I can only assume a \"better\" solution based on limited knowledge.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-10T09:42:00.990", "Id": "464532", "Score": "0", "body": "IEnumerable<Models.Container> joinedDisposables comes from an Api call and can sometimes contain elements that are comma separated and if so it would never be more than 2 elements that is split by a comma." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-07T15:37:29.640", "Id": "236844", "ParentId": "236418", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T14:45:20.767", "Id": "236418", "Score": "3", "Tags": [ "c#", "iterator" ], "Title": "Splits up two comma separated items, if they exist" }
236418
<p>Could the aggregate functions after using grouping functions like groupby() and resample() be looped for cleaner code</p> <p>____DateTime.____ | Steps | day_segment<br> 2017-10-25 00:00:00| 4 | night<br> 2017-10-25 00:01:00| 7 | night<br> 2017-10-25 00:02:00| 10 | night<br> 2017-10-25 00:03:00| 26 | night<br> .<br> .<br> .<br> 2017-10-25 10:04:00| 80 | morning<br> 2017-10-25 10:05:00| 45 | morning<br> 2017-10-25 10:06:00| 53 | morning </p> <h2>DataFrame: data</h2> <pre class="lang-py prettyprint-override"><code>day_segments = ['morning','afternoon','evening','night'] #all_steps is a list input from the user all_steps = ['sumallsteps','maxallsteps','minallsteps','avgallsteps','stdallsteps'] finalDataset = pd.DataFrame() #Descriptive Statistics Features: for day_segment in day_segments: resampledData = pd.DataFrame() resampledData = data.loc[data['day_segment'] == str(day_segment)] if("sumallsteps" in all_steps): finalDataset["step_" + str(day_segment) + "_sumallsteps"] = resampledData['steps'].resample('D').sum() if("maxallsteps" in all_steps): finalDataset["step_" + str(day_segment) + "_maxallsteps"] = resampledData['steps'].resample('D').max() if("minallsteps" in all_steps): finalDataset["step_" + str(day_segment) + "_minallsteps"] = resampledData['steps'].resample('D').min() if("avgallsteps" in all_steps): finalDataset["step_" + str(day_segment) + "_avgallsteps"] = resampledData['steps'].resample('D').mean() if("stdallsteps" in all_steps): finalDataset["step_" + str(day_segment) + "_stdallsteps"] = resampledData['steps'].resample('D').std() finaDataset.to_csv('data'+str(day_segment)+'.csv',index=True) </code></pre> <h2>IS THERE A WAY TO MAKE THE 'IF' STATEMENTS AND ITS FUNCTIONS SHORTER? LOOP IT IN A DICTIONARY SOMEHOW?</h2> <p>There are more assignments like this in my code so I would want to know if there is a way I could just loop the aggregate functions</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T16:19:04.930", "Id": "463334", "Score": "0", "body": "Using agg() you could loop through the all_steps and aggregate functions using a dict" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T16:35:57.273", "Id": "463342", "Score": "0", "body": "Add more context where you iterate over `day_segment` list" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T17:04:40.500", "Id": "463345", "Score": "0", "body": "@WillacyMe great! I will look into agg()" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T17:05:00.283", "Id": "463346", "Score": "1", "body": "@RomanPerekhrest just added a loop!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T10:39:51.973", "Id": "463438", "Score": "1", "body": "@EchhitJoshi: But your loop does not really do as you would expect, all day segments use exactly the same data. In contrast to e.g. the morning using only the, you know, morning. That sounds to me like your code is not yet finished?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T08:26:41.247", "Id": "463680", "Score": "0", "body": "Welcome to Code Review! This question lacks any indication of what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T15:38:30.943", "Id": "463730", "Score": "0", "body": "@Graipher Sorry for the confusion, I added a 'day segment' column so now we can loop through the 'day_segments' list and subset data and process it. I wanted to know if all the 'if' statements which look similar can be done in a couple of lines without the repetition as is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T16:13:50.013", "Id": "463731", "Score": "0", "body": "@TobySpeight Thank you Toby! I added some more context. I still do not know how to exactly word the question/title, I will as soon as I think of a way exactly pinpoint the problem in a couple of words" } ]
[ { "body": "<p>Try to get a good book or tutorial about pandas. The things you want to do is relatively easy with <code>groupby.agg</code></p>\n\n<pre><code>for segment, segment_data in df.groupby(\"day_segment\"):\n aggregated_data = segment_data.resample(\"D\").agg(\n [\"sum\", \"mean\", \"std\", \"min\", \"max\"]\n )\n aggregated_data_renamed = aggregated_data.copy()\n aggregated_data_renamed.columns = aggregated_data.columns.droplevel(0).map(\n lambda x: f\"step_{segment}_{x}allsteps\"\n )\n\n filename = f\"data{segment}.csv\"\n aggregated_data_renamed.to_csv(filename, index=True)\n</code></pre>\n\n<p>This uses <code>mean</code> instead of <code>avg</code>. If this is a problem, you can add another rename function call somewhere</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T16:40:31.387", "Id": "236594", "ParentId": "236424", "Score": "4" } }, { "body": "<p>I think what you want can be done by using <code>groupby</code> correctly.</p>\n\n<p>First, let's generate some sample data:</p>\n\n<pre><code>def to_seconds(t):\n return (t.hour * 60 + t.minute) * 60 + t.second\n\nlabels = [\"night\", \"morning\", \"afternoon\", \"evening\"]\nbins = to_seconds(pd.to_datetime([\"00:00:00\", \"06:00:00\", \"12:00:00\", \"18:00:00\", \"23:59:59\"]))\n\ndate = pd.date_range(\"2020-02-01 00:00:00\", \"2020-02-03 23:59:59\", freq=\"H\")\ndf = pd.DataFrame({\"date\": date, \"steps\": np.random.randint(0, 100, len(date))})\ndf[\"day_segment\"] = pd.cut(to_seconds(df.date.dt), bins, labels=labels, right=False)\n# date steps day_segment\n# 0 2020-02-01 00:00:00 8 night\n# 1 2020-02-01 01:00:00 43 night\n# 2 2020-02-01 02:00:00 23 night\n# 3 2020-02-01 03:00:00 84 night\n# 4 2020-02-01 04:00:00 32 night\n# .. ... ... ...\n# 67 2020-02-03 19:00:00 36 evening\n# 68 2020-02-03 20:00:00 76 evening\n# 69 2020-02-03 21:00:00 51 evening\n# 70 2020-02-03 22:00:00 99 evening\n# 71 2020-02-03 23:00:00 4 evening\n</code></pre>\n\n<p>And then you just need to group by <code>(date, day_segment)</code>:</p>\n\n<pre><code>df.groupby([date.date, \"day_segment\"]).steps.agg([\"sum\", \"max\", \"min\", \"std\", \"mean\"])\n# sum max min std mean\n# day_segment \n# 2020-02-01 night 263 84 8 29.403515 43.833333\n# morning 243 91 1 39.943710 40.500000\n# afternoon 364 88 28 26.919633 60.666667\n# evening 247 99 0 32.021347 41.166667\n# 2020-02-02 night 300 90 1 33.148152 50.000000\n# morning 278 96 1 37.011710 46.333333\n# afternoon 340 97 25 28.465183 56.666667\n# evening 418 95 9 33.773757 69.666667\n# 2020-02-03 night 458 92 60 13.894843 76.333333\n# morning 211 68 15 21.949184 35.166667\n# afternoon 426 95 36 21.042814 71.000000\n# evening 281 99 4 36.207274 46.833333\n</code></pre>\n\n<p>The list of aggregation functions can be built from the user input via some dictionary translation and the writing to file can be done by filtering on the day_segment:</p>\n\n<pre><code>stats.reset_index(level=0).loc[\"evening\"]\n# level_0 sum max min std mean\n# day_segment \n# evening 2020-02-01 247 99 0 32.021347 41.166667\n# evening 2020-02-02 418 95 9 33.773757 69.666667\n# evening 2020-02-03 281 99 4 36.207274 46.833333\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T16:47:03.517", "Id": "236595", "ParentId": "236424", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T16:03:27.413", "Id": "236424", "Score": "2", "Tags": [ "python", "pandas" ], "Title": "Reduce repetition in Pandas DataFrame column assignments" }
236424
<h3>Background</h3> <p>Apologies for "burying the lead." The questions are in the next section.</p> <p>In my application, the purpose of inheritance is to abstract away complicated logic in the base class template, so that the writer of a derived class template doesn't need to worry about it. This logic, however, will depend on these simpler methods in the derived class.</p> <p>What I have now is the base class template, something like <code>base1</code> below, has the complicated function <code>f2</code>, and this calls the to-be-defined, user-provided function <code>f1</code>. I make <code>f1</code> pure virtual so that <code>gcc</code> spits out compiler errors if someone forgot to define it.</p> <p>This works great, but I've starting considering what it would be like to rewrite <code>base1</code> into something like <code>base2</code>. From the user perspective, they don't need to worry about the weirdness of the base class inheriting stuff, so lack of familiarity with the <a href="https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern" rel="nofollow noreferrer">curiously recurring template pattern</a> wouldn't be an issue.</p> <p>The downside to this would be a slightly higher burden being placed on the writer of the derived class template. The inheritance part changes from <code>public base1&lt;a&gt;</code> to something that looks a little more intimidating: <code>public base2&lt;derived2&lt;a&gt;&gt;</code>. So is there any speed gain that makes it worth it?</p> <h3>A baby example</h3> <pre><code>#include &lt;iostream&gt; // option 1 template&lt;typename a&gt; class base1 { public: virtual double f1() = 0; void f2() { std::cout &lt;&lt; f1() &lt;&lt; "\n"; } }; template&lt;typename a&gt; class derived1 : public base1&lt;a&gt; { public: virtual double f1() { return 1.0; } }; // option 2 template&lt;typename derived&gt; class base2 { public: void f2() { std::cout &lt;&lt; static_cast&lt;derived*&gt;(this)-&gt;f1() &lt;&lt; "\n"; } }; template&lt;typename a&gt; class derived2 : public base2&lt;derived2&lt;a&gt;&gt; { public: double f1() {return 1.0;} }; int main() { derived1&lt;int&gt; thing1; thing1.f2(); derived2&lt;int&gt; thing2; thing2.f2(); return 0; } </code></pre> <h3>Questions:</h3> <ol> <li>Is it even polymorphism if there are no virtual functions, just pure virtual functions?</li> <li>Is there a vtable situation when there are just <strong>pure</strong> virtual functions? I've heard this is what makes static polymorphism faster (which might not even apply to this situation).</li> <li>What is different, from the compiler's perspective, about these two methods?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T17:19:15.990", "Id": "463352", "Score": "2", "body": "While this question is interesting, it seems too hypothetical. Code review is for working code that actually does something." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T21:10:19.363", "Id": "463378", "Score": "0", "body": "@pacmaninbw I have a library that uses the first pattern. This library advertises its speed, so that’s why I’m looking into this. I can share an example from there, if you’d like." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T00:16:30.097", "Id": "463401", "Score": "0", "body": "@pacmaninbw I suspect the real example is a) too complex to put in a CR and b) possibly proprietary? The info given is sufficient to address the question at hand? See below?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T03:25:51.050", "Id": "463406", "Score": "2", "body": "Sorry Taylor, Code Review does not allow hypothetical examples. The code you presented in its current form is not meaningfully reviewable. We only review real, working code. If you edit your question to contain your actual code, we can review it for improvements. See [What topics can I ask about?](https://codereview.stackexchange.com/help/on-topic) for reference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T15:09:01.130", "Id": "463461", "Score": "0", "body": "@Taylor Check to see if anyone has asked something like this on Stack Overflow, if not that is the place to ask this question." } ]
[ { "body": "<h2>CRTP</h2>\n\n<p><em>Caveat: It's not quite clear what the <code>&lt;a&gt;</code> template parameter is doing/</em></p>\n\n<p>For my understanding your option1 defeats the purpose of CRTP. That is, if it's even trying to do CRTP. It's not clear due to the template parameter <code>&lt;a&gt;</code> which appears to have no purpose. Fact is, Option1 It's working just like normal polymorphism, see below. </p>\n\n<p>In the context of polymorphism the purpose of CRTP is usually to avoid vtable calls / runtime dispatch. The point is to convert runtime polymorphism to compile time polymorphism. Your Option 1 does not do that, as far as I can see.</p>\n\n<p>In terms of \"what's different between these 2 Options\", I have put a modified version of <a href=\"https://godbolt.org/z/2RWyqz\" rel=\"nofollow noreferrer\">your code on godbolt</a>. Modified only to be able to turn on <code>-O3</code> without the compiler removing the programme. The inheritance code is the same. You can clearly see that Derived1 has a vtable, and Derived2 does not. </p>\n\n<p>Your Option1 also seems to lose one of the strengths of runtime polymorphism. With normal polyphism where <code>Derived</code> inherits from <code>Base</code> (no CRTP, not even your option1), all Derived classes inherit from the one base. Which means we can make a <code>std::vector&lt;Base*&gt;</code> or <code>std::vector&lt;unique_ptr&lt;Base&gt;&gt;</code>, ie hold pointers to many different types of objects in the same container. We can't do that with compile time / CRTP type polymorphism. But your Option1 suffers from Vtable and we still can't put them all in a <code>vector</code> because they don't have a common base. (ie <code>Base&lt;int&gt;*</code> and <code>Base&lt;D2&gt;*</code> won't go in the same <code>vector</code>. Unless <code>&lt;a&gt;</code> will one of a limited set loike <code>int</code> and <code>float</code> which can then fit a vector - again, not clear). Fact is that \"proper\" compile time polymorphism (see below), makes it hard/impossible to put different derived types in a collection. </p>\n\n<p>I found <a href=\"https://youtu.be/jBnIMEb2GhA?t=1098\" rel=\"nofollow noreferrer\">this video</a> helpful (link is to the CRTP code moment) to understand it, as it explores the various options, and, based on a practical example, shows their implementation and compares their performance. </p>\n\n<h2>Option2</h2>\n\n<p>Your option 2 comes closer, but overcomplicates things as far as I can see. You don't need the Derived to be templated, you just need it to be inheriting from the Base specialised with the Derived type: <code>Base&lt;Derived&gt;</code>. -- If you have an application specific need to make Derived templated, beyond CRTP, then that was not shown in your code, and yes, in that case, your Option 2 code is correct for \"proper\" CRTP. </p>\n\n<h2>Proposed solution</h2>\n\n<p>So by just cleaning up the above-mentioned over-complication, this works fine, doesn't it? (Note that I am showing a single Base with 2 Derived classes inheriting from it): </p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n\n// CRTP as explained in:\n// https://youtu.be/jBnIMEb2GhA?t=1098\ntemplate&lt;typename D&gt;\nclass Base {\npublic:\n void f2() { std::cout &lt;&lt; static_cast&lt;D*&gt;(this)-&gt;f1() &lt;&lt; \"\\n\"; }\n};\n\nclass Derived1 : public Base&lt;Derived1&gt; {\npublic:\n std::string f1() { return \"derived1\"; }\n};\n\n\nclass Derived2 : public Base&lt;Derived2&gt; {\npublic:\n std::string f1() { return \"derived2\"; }\n};\n\n\nint main() {\n Derived1 thing1;\n thing1.f2();\n Derived2 thing2;\n thing2.f2();\n return 0;\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>derived1\nderived2\n</code></pre>\n\n<h2>More inheritance options, or rather...</h2>\n\n<p>If you are looking at a re-design, you might also want to <a href=\"https://www.youtube.com/watch?v=QGcVXgEVMJg\" rel=\"nofollow noreferrer\">watch this from Sean Parent</a>, which is sort of \"the next level\", ie (almost) avoid inheritance altogether:</p>\n\n<p>Or, the same subject, explained in a clear and <a href=\"https://foonathan.net/2020/01/type-erasure/#content\" rel=\"nofollow noreferrer\">recent blogpost here</a>. </p>\n\n<p>These links are exploring their \"type erasure\" technique not for performance reasons, but to be able to remove tight inheritance coupling between different components. </p>\n\n<h2>Performance motivation...be careful</h2>\n\n<p>Note that if you are considering CRTP for performance reasons, because it can avoid the vtable, then <em>make sure you measure</em> before and after. The lady in the cppcon video does it nicely and the gains exist in her case, but they are not \"ground breaking\". Any gains are typically mostly due to the compiler's <em>inability to inline the calls</em> rather then the <em>indirection via the vtable</em>. So always measure, please. </p>\n\n<p>Hope that helps. If I have misunderstood what you're trying to do, please come back in the comments. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T03:32:10.273", "Id": "463407", "Score": "0", "body": "Heads up: the question contains hypothetical code, which is off-topic for the site, but unfortunately wasn't closed promptly to prevent otherwise legitimate answers like yours, so we may allow the OP to edit their question to fix the problem, possibly invalidating your answer. You may have to rework some parts of your answer. And that's part of the reason we discourage answers to off-topic questions. In the future, please try not to answer off-topic questions and wait for them to be fixed instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T04:27:28.420", "Id": "463412", "Score": "0", "body": "I see your point, but unfortunately this isn't the correct place to discuss site policies, so I can't discuss with you in depth here. Plus, you have to reach consensus with other members of the community. You can take a look at our [FAQ](https://codereview.meta.stackexchange.com/q/1709) on this, which states the reasons many users think that this rule is necessary, as well as other related questions on [meta]. If you think the rule is outdated or needs improvement, feel free to discuss on [meta], which is visited by many of the active members, with the arguments you just listed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T15:32:51.090", "Id": "463466", "Score": "1", "body": "very helpful! thanks very much Oliver" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T23:48:45.633", "Id": "236446", "ParentId": "236425", "Score": "3" } } ]
{ "AcceptedAnswerId": "236446", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T16:49:17.247", "Id": "236425", "Score": "-1", "Tags": [ "c++", "object-oriented", "comparative-review", "template", "inheritance" ], "Title": "abstract base classes versus the curiously recurring template pattern" }
236425
<p>This if for a school project that is all about getting the most performance possible out of a relatively weak computer.</p> <p>For this project we have received a weather station report generator that generates 8000 weather measurements per second. These measurements are split into groups of 10 stations resulting in 800 clusters sending these measurements.</p> <p>One such measurement:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;WEATHERDATA&gt; &lt;MEASUREMENT&gt; &lt;STN&gt;123456&lt;/STN&gt; &lt;DATE&gt;2009-09-13&lt;/DATE&gt; &lt;TIME&gt;15:59:46&lt;/TIME&gt; &lt;TEMP&gt;-60.1&lt;/TEMP&gt; &lt;DEWP&gt;-58.1&lt;/DEWP&gt; &lt;STP&gt;1034.5&lt;/STP&gt; &lt;SLP&gt;1007.6&lt;/SLP&gt; &lt;VISIB&gt;123.7&lt;/VISIB&gt; &lt;WDSP&gt;10.8&lt;/WDSP&gt; &lt;PRCP&gt;11.28&lt;/PRCP&gt; &lt;SNDP&gt;11.1&lt;/SNDP&gt; &lt;FRSHTT&gt;010101&lt;/FRSHTT&gt; &lt;CLDC&gt;87.4&lt;/CLDC&gt; &lt;WNDDIR&gt;342&lt;/WNDDIR&gt; &lt;/MEASUREMENT&gt; &lt;/WEATHERDATA&gt; </code></pre> <p>The goal of this project is to take this XML and parse it, that includes adding any missing data and correcting values that don't make sense. Then were supposed to take this data and save it on a server in as small a format as possible. We only have 20GB to work with. </p> <p>I ended up making a little java application that I think works pretty well but i'm new to java so I really want to know if there is anything I can improve especially regarding performance. </p> <p>This is the projects main file. Here I start the application and all of its thread pools. I also initialize a bunch of weather Station obj to use later.</p> <pre><code>import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; public class WeatherService { private static final int SERVER_PORT = 7789; private static final boolean DEBUG = true; private WeatherService(ServerSocket serverSocket) { BlockingQueue&lt;ArrayList&lt;String&gt;&gt; parseQueue = new ArrayBlockingQueue&lt;&gt;(100000, true); BlockingQueue&lt;Measurement&gt; storeQueue = new ArrayBlockingQueue&lt;&gt;(100000, true); AtomicInteger parseCounter = new AtomicInteger(0); AtomicInteger storeCounter = new AtomicInteger(0); //TODO: performance can be improved Station[] weatherStations = new Station[1000000]; initializeWeahterStations(weatherStations); // Create receiver thread pool ExecutorService receiverThreadPool = Executors.newCachedThreadPool(); //Create and start parser thread pool ExecutorService parserThreadPool = Executors.newFixedThreadPool(2); parserThreadPool.submit(new ParserThread(parseQueue, parseCounter, storeQueue, weatherStations)); //Create and start transmission thread pool ExecutorService transmissionThreadPool = Executors.newFixedThreadPool(2); transmissionThreadPool.submit(new TransmissionThread(storeQueue, storeCounter)); //Create and start a performance control thread pool if (DEBUG){ ScheduledExecutorService performanceControlPool = Executors.newScheduledThreadPool(1); performanceControlPool.scheduleAtFixedRate(new PerformanceControl(parseQueue, storeQueue, parseCounter, storeCounter), 0, 10, TimeUnit.SECONDS); } //Start receiver thread while (true) { try { Socket socket = serverSocket.accept(); receiverThreadPool.submit(new ReceiverThread(socket, parseQueue)); } catch (IOException e) { e.printStackTrace(); } } } private void initializeWeahterStations(Station[] weatherStations) { for (int i = 0; i &lt; 1000000; i++) { weatherStations[i] = new Station(); } } public static void main(String[] args) { try { new WeatherService(new ServerSocket(SERVER_PORT)); } catch (IOException e) { System.out.println("Error opening socket"); } } } </code></pre> <p>Station and measurement classes</p> <pre><code>import java.util.ArrayList; public class Station { private ArrayList&lt;Measurement&gt; measurements = new ArrayList&lt;&gt;(); Station() { } public void addNewMeasurement(Measurement measurement) { if (this.measurements.size() &gt;= 30) this.measurements.remove(0); this.measurements.add(measurement); } public String getLatestFrshtt() { if (measurements.size() &gt; 0) return measurements.get(0).frshtt; return "000000"; } public double getExtrapolatedValue(int pos) { double total = 0; for (Measurement measurement : measurements) { total += measurement.measurementValues[pos]; } return total / this.measurements.size(); } public double getExtrapolatedTemp(double temp) { double total = 0; for (Measurement measurement : measurements) { total += measurement.measurementValues[0]; } if (temp &gt;= total * 0.8 || temp &lt;= total * 1.2) return temp; else if (temp &lt;= total * 0.8) return temp + (total * 0.8); else if (temp &gt;= total * 1.2) return temp + (total * 1.2); return total / this.measurements.size(); } } public class Measurement { public int[] measurementValues = new int[10]; // [0] temp, temperatuur in graden Celsius, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal // [1] dewp, dauwpunt in graden Celsius, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal // [2] stp, luchtdruk op stationsniveau in millibar, geldige waardes van 0.0 t/m 9999.9 met 1 decimaal // [3] slp, luchtdruk op zeeniveau in millibar, geldige waardes van 0.0 t/m 9999.9 met 1 decimaal // [4] visib, zichtbaarheid in kilometers, geldige waardes van 0.0 t/m 999.9 met 1 decimaal // [5] wdsp, windsnelheid in kilometers per uur, geldige waardes van 0.0 t/m 999.9 met 1 decimaal // [6] prcp, neerslag in centimeters, geldige waardes van 0.00 t/m 99999. met 2 decimalen // [7] sndp, gevallen sneeuw in centimeters, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal // [8] cldc, bewolking in procenten, geldige waardes van 0.0 t/m 99.9 met 1 decimaal // [9] wnddir, windrichting in graden, geldige waardes van 0 t/m 359 alleen gehele getallen int stn; String frshtt; String date; // Datum van versturen van deze gegevens, formaat: yyyy-mm-dd String time; // Tijd van versturen van deze gegevens, formaat: hh:mm:ss public Measurement() { } } </code></pre> <p>Each receiver thread connects to one weather cluster and receives 10 measurements per second in a single XML file. It only grabs the relevant lines and adds these to an array. The arrays get added to the parserQueue for later processing.</p> <pre><code>import java.io.*; import java.net.Socket; import java.util.ArrayList; import java.util.concurrent.BlockingQueue; public class ReceiverThread implements Runnable { private final BlockingQueue&lt;ArrayList&lt;String&gt;&gt; outgoingQueue; private BufferedReader bufferedReader = null; private Socket socket; ReceiverThread(Socket socket, BlockingQueue&lt;ArrayList&lt;String&gt;&gt; outgoingQueue) { this.outgoingQueue = outgoingQueue; this.socket = socket; try { this.bufferedReader = new BufferedReader(new InputStreamReader(new BufferedInputStream(socket.getInputStream(), 256), "UTF-8"), 256); } catch (IOException e) { e.printStackTrace(); } } public void run() { try { this.receiverService(); } catch (IOException e) { e.printStackTrace(); } } private void receiverService() throws IOException { try { ArrayList&lt;String&gt; measurement = new ArrayList&lt;&gt;(); while (true) { String inputLine = bufferedReader.readLine(); if (inputLine == null) break; if (!inputLine.contains("?xml") &amp;&amp; !inputLine.contains("&lt;WEATHERDATA&gt;") &amp;&amp; !inputLine.contains("&lt;/WEATHERDATA&gt;") &amp;&amp; !inputLine.contains("&lt;MEASUREMENT&gt;") &amp;&amp; !inputLine.contains("&lt;/MEASUREMENT&gt;")) measurement.add(inputLine.trim()); if (inputLine.contains("&lt;/MEASUREMENT&gt;")) { outgoingQueue.add(measurement); measurement = new ArrayList&lt;&gt;(); } } } finally { bufferedReader.close(); socket.close(); } } } </code></pre> <p>The two parser threads grab the arrays from the queue and start stripping the unnecessary characters. The values taken from the arrays get turned into a measurement object and added to the transmission queue. </p> <p>In this thread the values also get checked if they are valid. Up to 30 measurements get added to each station to be used for extrapolation.</p> <pre><code>import java.util.ArrayList; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicInteger; public class ParserThread implements Runnable { private final BlockingQueue&lt;ArrayList&lt;String&gt;&gt; incomingQueue; private final BlockingQueue&lt;Measurement&gt; outgoingQueue; private final AtomicInteger counter; private final Station[] weatherStations; ParserThread(BlockingQueue&lt;ArrayList&lt;String&gt;&gt; incomingQueue, AtomicInteger counter, BlockingQueue&lt;Measurement&gt; outgoingQueue, Station[] weatherStations) { this.incomingQueue = incomingQueue; this.outgoingQueue = outgoingQueue; this.counter = counter; this.weatherStations = weatherStations; } public void run() { while (true) { this.parseData(); } } private void parseData() { try { if (incomingQueue.size() &gt; 100) { ArrayList&lt;ArrayList&lt;String&gt;&gt; parseList = new ArrayList&lt;&gt;(); this.incomingQueue.drainTo(parseList, 25000); for (ArrayList&lt;String&gt; items : parseList) { Measurement measurement = new Measurement(); ItemsToMeasurement(items, measurement); weatherStations[measurement.stn].addNewMeasurement(measurement); this.outgoingQueue.add(measurement); this.counter.getAndIncrement(); } } else { Thread.sleep(2000); } } catch (Exception | Error e) { e.printStackTrace(); } } //TODO: Make this shorter/ more efficient private void ItemsToMeasurement(ArrayList&lt;String&gt; items, Measurement measurement) { measurement.stn = Integer.parseInt(items.get(0).substring(5, items.get(0).length() - 6)); measurement.date = items.get(1).substring(6, items.get(1).length() - 7); measurement.time = items.get(2).substring(6, items.get(2).length() - 7); measurement.frshtt = validateFrshtt(items.get(11).substring(8, items.get(11).length() - 9), measurement); measurement.measurementValues[0] = validateLine(items.get(3).substring(6, items.get(3).length() - 7), measurement, 0); measurement.measurementValues[1] = validateLine(items.get(4).substring(6, items.get(4).length() - 7), measurement, 1); measurement.measurementValues[2] = validateLine(items.get(5).substring(5, items.get(5).length() - 6), measurement, 2); measurement.measurementValues[3] = validateLine(items.get(6).substring(5, items.get(6).length() - 6), measurement, 3); measurement.measurementValues[4] = validateLine(items.get(7).substring(7, items.get(7).length() - 8), measurement, 4); measurement.measurementValues[5] = validateLine(items.get(8).substring(6, items.get(8).length() - 7), measurement, 5); measurement.measurementValues[6] = validateLine(items.get(9).substring(6, items.get(9).length() - 7), measurement, 6); measurement.measurementValues[7] = validateLine(items.get(10).substring(6, items.get(10).length() - 7), measurement, 7); measurement.measurementValues[8] = validateLine(items.get(12).substring(6, items.get(12).length() - 7), measurement, 8); measurement.measurementValues[9] = validateLine(items.get(13).substring(8, items.get(13).length() - 9), measurement, 9); } private String validateFrshtt(String line, Measurement measurement) { if (line.isEmpty()) return weatherStations[measurement.stn].getLatestFrshtt(); return line; } private int validateLine(String line, Measurement measurement, int pos) { if (line.isEmpty()) return (int) (weatherStations[measurement.stn].getExtrapolatedValue(pos) * 100); if (pos == 0) return (int) (weatherStations[measurement.stn].getExtrapolatedTemp((Double.parseDouble(line)) * 100)); return (int) (Double.parseDouble(line) * 100); } } </code></pre> <p>Last but not least the measurements get written to a file. This part isn't quite done yet as I have yet to do anything to reduce the size of the data but ill get to that later. For now it writes integers to a file. It creates a folder for each day and in that folder a folder for each hour. In that folder a file gets created for each minute of measurements. </p> <pre><code>import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicInteger; public class TransmissionThread implements Runnable { private final BlockingQueue&lt;Measurement&gt; incomingQueue; private final AtomicInteger counter; TransmissionThread(BlockingQueue&lt;Measurement&gt; incomingQueue, AtomicInteger counter) { this.incomingQueue = incomingQueue; this.counter = counter; } public void run() { while (true) { this.transmitData(); } } private void transmitData() { try { if (incomingQueue.size() &gt; 100) { ArrayList&lt;Measurement&gt; transmitList = new ArrayList&lt;&gt;(); this.incomingQueue.drainTo(transmitList, 25000); File directory = new File("C:\\Users\\djurr\\Desktop\\New folder\\out\\" + transmitList.get(0).date + "\\H" + transmitList.get(0).time.substring(0, 2)); if (!directory.exists()) directory.mkdir(); BufferedWriter writer = new BufferedWriter( new FileWriter("C:\\Users\\djurr\\Desktop\\New folder\\out\\" + transmitList.get(0).date + "\\H" + transmitList.get(0).time.substring(0, 2) + "\\M"+ transmitList.get(0).time.substring(3, 5) +".txt", true) ); for (Measurement measurement : transmitList) { //TODO: bitify data dataToFile(measurement, writer); this.counter.getAndIncrement(); } writer.close(); } else { Thread.sleep(2000); } } catch (Exception | Error e) { e.printStackTrace(); } } private void dataToFile(Measurement measurement, BufferedWriter writer) { try { writer.newLine(); writer.write(measurement.stn + "," + measurement.time + "," + measurement.frshtt + "," + Arrays.toString(measurement.measurementValues)); } catch (IOException e) { e.printStackTrace(); } } } </code></pre> <p>So yea if you see anything that I can do to improve this code, especially performance wise, id love to hear it. And sorry for the long post :P</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T20:34:18.160", "Id": "463367", "Score": "0", "body": "Why do you want 8000 measurements per second?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T20:49:22.540", "Id": "463372", "Score": "1", "body": "Because that's the assignment @Mast. In this project we represent a company that sells this data to other people so we want to store all of it to sell later." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T21:19:59.663", "Id": "463380", "Score": "0", "body": "A proper company should realize to average (and otherwise filter) at least some of those 8k values to have around 500 (at most) useful values per second. We're talking about the weather here, after a while it simply doesn't make sense to increase measurement-frequency. I used to have a weather station that checked every 5 seconds and that was already accurate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T14:33:11.160", "Id": "463458", "Score": "0", "body": "@Mast the data is used for research so they want as much as possible" } ]
[ { "body": "<p>Some hints about Java standard coding practices:</p>\n\n<p><strong>Declaring from Interface type instead of Class</strong> </p>\n\n<p>In your code are present declarations like this below:</p>\n\n<blockquote>\n<pre><code> private ArrayList&lt;Measurement&gt; measurements = new ArrayList&lt;&gt;();\n</code></pre>\n</blockquote>\n\n<p>Better use instead:</p>\n\n<pre><code>private List&lt;Measurement&gt; measurements = new ArrayList&lt;&gt;();\n</code></pre>\n\n<p>It allows flexibility if you do not want to implement an ArrayList but maybe another type of list without correcting every declaration in your code.</p>\n\n<p>I have seen in your code you have the following if-else block:</p>\n\n<blockquote>\n<pre><code>if (temp &gt;= total * 0.8 || temp &lt;= total * 1.2)\n return temp;\nelse if (temp &lt;= total * 0.8)\n return temp + (total * 0.8);\n else if (temp &gt;= total * 1.2)\n return temp + (total * 1.2);\nreturn total / this.measurements.size();\n</code></pre>\n</blockquote>\n\n<p>If you have an if branch ending with a return , you have no need to use the else for the other branch; refactoring these lines and with the help of local variables you can obtain:</p>\n\n<pre><code>double a = total * 0.8;\ndouble b = total * 1.2;\nif (temp &gt;= a || temp &lt;= b) { return temp; }\nif (temp &lt;= a) { return temp + a; }\nif (temp &gt;= b) { return temp + b; }\nreturn total / this.measurements.size();\n</code></pre>\n\n<p>You have no need of use <code>this</code> in instance methods like your code below:</p>\n\n<blockquote>\n<pre><code>public class Station {\n private ArrayList&lt;Measurement&gt; measurements = new ArrayList&lt;&gt;();\n Station() {}\n public void addNewMeasurement(Measurement measurement) {\n if (this.measurements.size() &gt;= 30)\n this.measurements.remove(0);\n this.measurements.add(measurement);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>You can rewrite your code initializing measurements inside the constructor and eliminate the <code>this</code> keyword from your methods:</p>\n\n<pre><code>public class Station {\n private List&lt;Measurement&gt; measurements;\n\n public Station() {\n this.measurements = new ArrayList&lt;Measurement&gt;();\n }\n\n public void addNewMeasurement(Measurement measurement) {\n if (measurements.size() &gt;= 30) {\n measurements.remove(0);\n }\n measurements.add(measurement);\n }\n}\n</code></pre>\n\n<p>About the reading of xml files, you are not using one of the xml api Java offers, I'm including an example of how you can read the file you posted using the Java <a href=\"https://docs.oracle.com/javase/8/docs/api/org/w3c/dom/package-summary.html\" rel=\"nofollow noreferrer\">dom package</a> and extract for example the DATE and TIME tags:</p>\n\n<pre><code>File file = new File(\"measurement.xml\");\nDocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\nDocumentBuilder builder = factory.newDocumentBuilder();\nDocument doc = builder.parse(file);\nNode node = doc.getElementsByTagName(\"DATE\").item(0);\nString date = node.getTextContent();\nnode = doc.getElementsByTagName(\"TIME\").item(0);\nString time = node.getTextContent();\nLocalDateTime dateTime = LocalDateTime.of(LocalDate.parse(date), LocalTime.parse(time));\nSystem.out.println(dateTime.toLocalTime());\nSystem.out.println(dateTime.toLocalDate());\n</code></pre>\n\n<p>You can start from this example to extract other tags inside the xml file, instead of using two distinct fields for memorizing date and time in your class <code>Measurement</code> you have only to store the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html\" rel=\"nofollow noreferrer\">LocalDateTime</a> object.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T23:26:29.110", "Id": "463517", "Score": "0", "body": "Thank you very much for the response. I will defiantly be implementing some of your suggestions. The only thing I wonder about is doesn't using a dom package affect the performance negatively?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T10:27:01.437", "Id": "463534", "Score": "0", "body": "@Bobeliciousbob In your code you are using the `ItemsToMeasurement` method with several calls to substring and so you are creating several String objects inside ot it and more important it will break if you receive an xml with missing data or even light difference with the file you posted here ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T10:28:45.427", "Id": "463536", "Score": "0", "body": "@Bobeliciousbob Dom stores the xml in memory and this is expensive, but on the other side you can with few lines of code check if tags are present and extract values. If you want to obtain a better performance you can use the Sax java api that consumes much less memory compared to Dom but this implies you have to write more code and handle all situations automatically handled by Dom. For further information you can read [SAX vs DOM](https://stackoverflow.com/questions/6828703/what-is-the-difference-between-sax-and-dom)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T17:47:40.033", "Id": "236475", "ParentId": "236426", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T17:18:00.740", "Id": "236426", "Score": "5", "Tags": [ "java", "performance", "beginner", "homework" ], "Title": "Parsing weather station XML on raspberry pi" }
236426
<p>I have an XML Parser in Java using WoodStox that I wrote. This parser is going to be parsing through extremely large files, could be 5+GB. The goal of the parser is to convert a nest XML file into a CSV. The XML file is going to be formatted in such a way where there will be a '<code>rowTag</code>' that has the actual information that the parser is interested in. Take for example XML file:</p> <pre><code>&lt;persons&gt; &lt;person id="1"&gt; &lt;firstname&gt;James&lt;/firstname&gt; &lt;lastname&gt;Smith&lt;/lastname&gt; &lt;middlename&gt;&lt;/middlename&gt; &lt;dob_year&gt;1980&lt;/dob_year&gt; &lt;dob_month&gt;1&lt;/dob_month&gt; &lt;gender&gt;M&lt;/gender&gt; &lt;salary currency="Euro"&gt;10000&lt;/salary&gt; &lt;street&gt;456 apple street&lt;/street&gt; &lt;city&gt;newark&lt;/city&gt; &lt;state&gt;DE&lt;/state&gt; &lt;/person&gt; &lt;person id="2"&gt; &lt;firstname&gt;Michael&lt;/firstname&gt; &lt;lastname&gt;&lt;/lastname&gt; &lt;middlename&gt;Rose&lt;/middlename&gt; &lt;dob_year&gt;1990&lt;/dob_year&gt; &lt;dob_month&gt;6&lt;/dob_month&gt; &lt;gender&gt;M&lt;/gender&gt; &lt;salary currency="Dollor"&gt;10000&lt;/salary&gt; &lt;street&gt;4367 orange st&lt;/street&gt; &lt;city&gt;sandiago&lt;/city&gt; &lt;state&gt;CA&lt;/state&gt; &lt;/person&gt; &lt;/persons&gt; </code></pre> <p>The rowtag here would be "person", and the headers would be all the tags inside of <code>&lt;person&gt;</code>. </p> <p>Below is the class I wrote for this. Would love to hear feedback. You can use WoodStox with either this jar file <a href="http://www.java2s.com/Code/JarDownload/woodstox/woodstox-5.2.0-m1.jar.zip" rel="nofollow noreferrer">here</a>, or include it in gradle:</p> <p><code>implementation(["org.codehaus.woodstox:stax2-api:3.1.1"])</code></p> <pre><code>import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.apache.commons.lang3.StringUtils; import org.codehaus.stax2.XMLInputFactory2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class XmlConverter2 { private static final Logger logger = LoggerFactory.getLogger(XmlConverter.class); private static final String ROWTAG = "person"; public void readLargeXmlWithWoodStox(String file) throws FactoryConfigurationError, XMLStreamException, IOException { long startTime = System.nanoTime(); // set up a Woodstox reader XMLInputFactory xmlif = XMLInputFactory2.newInstance(); XMLStreamReader xmlStreamReader = xmlif.createXMLStreamReader(new FileReader(file)); boolean firstPass = true; boolean insideRowTag = false; Files.deleteIfExists(new File( file + ".csv").toPath()); BufferedWriter br = new BufferedWriter(new FileWriter(file + ".csv", true), 64*1024*1024); StringBuilder firstItems = new StringBuilder(); try { while (xmlStreamReader.hasNext()) { xmlStreamReader.next(); // If 4 event, meaning just some random '\n' or something, we skip. if (xmlStreamReader.isCharacters()) { continue; } // If we are at a start element, we want to check a couple of things if (xmlStreamReader.isStartElement()) { // If we are at our rowtag, we want to start looking at what is inside. // We are 'continuing' because a Rowtag will not have any "elementText" in it, so we want to continue to the next tag. if (xmlStreamReader.getLocalName().equalsIgnoreCase(ROWTAG)) { insideRowTag = true; continue; } // if we are at a tag inside a row tag, we want to extract that information (the text it contains) from it.... if (insideRowTag) { // ...but first, if we have not started to collect everything, we need to collect the headers! // This makes an assumption that all the "headers" are constant. If the first record has 6 tags in it, // but the next one has 7 tags in it, we are in trouble. We can add flexibility for that, I think. if (firstPass) { // We want to write the headers first br.write(xmlStreamReader.getLocalName() + ','); // And collect the items inside in a stringBuilder, which we'll dump later. firstItems.append(xmlStreamReader.getElementText()).append(','); } else { // If we're not in the first pass, just write the elements directly. br.write(xmlStreamReader.getElementText() + ','); } } } // If we are at an end element that is the rowTag, so at the end of the record, we want to do a couple of things if (xmlStreamReader.isEndElement() &amp;&amp; xmlStreamReader.getLocalName().equalsIgnoreCase(ROWTAG)) { // First, if we are at the first pass, we want to send out the elements inside the first record // that we were collecting to dump *after* we got all the headers if (firstPass) { firstPass = false; br.write('\n' + StringUtils.chop(firstItems.toString())); } // Then we set this off so that we no longer collect irrelevant data if it is present. insideRowTag = false; br.write('\n'); } } } catch (Exception e) { logger.error("Error! " + e.toString()); } finally { xmlStreamReader.close(); } br.close(); long endTime = System.nanoTime(); long totalTime = endTime - startTime; logger.info("Done! Time took: {}", totalTime / 1000000000); } } </code></pre> <p>My goal is to make this faster and/or consume less memory. Any other advice is appreciated, of course. I am executing it using <code>-Xms4g -Xmx4g</code> tags. Right now, it takes around 25 seconds to run on an xml file that is 1.5Gb approximately. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T19:05:28.977", "Id": "463360", "Score": "0", "body": "How much memory does it consume?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T19:55:44.680", "Id": "463364", "Score": "0", "body": "@D.Jurcau Not entirely sure, I haven't been able to find a great way to measure that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T20:33:53.210", "Id": "463366", "Score": "1", "body": "It's a bit odd to call your program a \"parser\". Woodstox is the parser." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T20:37:51.193", "Id": "463369", "Score": "0", "body": "@MichaelKay You're right I guess ¯\\_ (ツ)_/¯ what would you recommend I call it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T20:39:31.577", "Id": "463370", "Score": "3", "body": "I think 1.5Gb in 25s is a pretty good speed, and I wouldn't think it can be improved all that much. Try writing an application that does the absolute minimum to invoke Woodstox to parse the XML, and I suspect it won't be much faster than this. The critical component from a performance perspective is almost certainly the Woodstox parser, and not your calling application. There might be a few tiny savings you can make, for example detecting the ROW end tag by tracking nesting depth rather than with a string comparison; but they're going to be very minor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T20:44:35.477", "Id": "463371", "Score": "1", "body": "In fact since you aren't handling nested rowtags anyway, you could avoid the string comparison on start tag names when `inrowtag` is true." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T05:36:26.283", "Id": "463523", "Score": "0", "body": "Not regarding your actual solution, but as a general tip from experience: this is the use-case where a simple SAX parser really shines. Basically start a row context with startEntity whenever you enconter a person, record the contents between each start/endEnitity, and flush the row on endEntity for a person. I would be interested to see a comparison in runtimes with your current solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T10:36:34.397", "Id": "463537", "Score": "1", "body": "@mtj in my experience it matters a lot more if a parser allocates `String`s at any point or only juggles some internal buffers, giving you some sort of a view on it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T11:37:51.490", "Id": "463712", "Score": "1", "body": "FileReader and FileWriter use the default platform encoding; probably wrong. Nice would be UTF-8. For XML better use an InputStream. If so needed with a BOM as first char `\"\\uFEFF\"`. I also have some doubt on skipping `isCharacters` but I assume that is for the header line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-19T22:06:43.097", "Id": "512383", "Score": "0", "body": "Extending from the excellent point of never ever relying on platform-encoding (there's no upside) -- use `FileInputStream` instead of `FileReader` -- XML parsers are required to use proper content auto-detection (from xml declaration, if available), and Woodstox does that. It may be slightly faster as well (although unlikely humongous benefit) but more importantly uses correct encoding." } ]
[ { "body": "<ul>\n<li>I was in a similar position several years ago - needing to parse multi-gigabyte XML files. Tried all the standard solutions Woodstox, Xerces, Piccolo whatnot - can't remember all the names. Ended up using an XML parser from a library called <a href=\"http://javolution.org/\" rel=\"nofollow noreferrer\">Javolution</a>. It's development has stalled a while back, but the parser works well.</li>\n<li><p>Available from Maven Central: <a href=\"https://search.maven.org/artifact/org.javolution/javolution-core-java/6.0.0/bundle\" rel=\"nofollow noreferrer\">https://search.maven.org/artifact/org.javolution/javolution-core-java/6.0.0/bundle</a></p></li>\n<li><p>I got it to parse at about 1 GB/s with an SSD. </p>\n\n<ul>\n<li>A very old example of my usage (link to the line where the XML parser is instantiated): <a href=\"https://github.com/chhh/MSFTBX/blob/e53ae6be982e2de3123292be7d5297715bec70bb/MSFileToolbox/src/main/java/umich/ms/fileio/filetypes/mzml/MZMLMultiSpectraParser.java#L105\" rel=\"nofollow noreferrer\">https://github.com/chhh/MSFTBX/blob/e53ae6be982e2de3123292be7d5297715bec70bb/MSFileToolbox/src/main/java/umich/ms/fileio/filetypes/mzml/MZMLMultiSpectraParser.java#L105</a></li>\n<li>Description of their XML package: <a href=\"https://github.com/javolution/javolution/blob/master/src/main/java/org/javolution/xml/package-info.java\" rel=\"nofollow noreferrer\">https://github.com/javolution/javolution/blob/master/src/main/java/org/javolution/xml/package-info.java</a></li>\n</ul></li>\n<li><p>If you're using an HDD without RAID, then you're most likely limited to 100-200 MB/s just by IO, so likely you can't be faster than 1 GB in 5 seconds with that scenario.</p></li>\n<li><p>Core thing for XML parsing speed (apart from just good io code) is to not allocate unnecessary garbage, the parser should not be allocating Strings all the time to just do a comparison or give you an array of tag's attributes. Javolution does exactly that using an internal sliding buffer and refernecing it. Like a <code>java.lang.CharSequence</code>, called <code>CharArray</code> in javolution. It's important to use <code>CharArray#contentEquals()</code> when comparing to Strings to avoid extra String creation.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T09:50:02.710", "Id": "463435", "Score": "1", "body": "According to https://www.xml.com/pub/a/2007/05/09/xml-parser-benchmarks-part-1.html (which is quite old), Javolotion parsing performance is pretty much the same as Woodstox - fast, but not wildly faster than other parsers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T19:27:48.927", "Id": "463487", "Score": "0", "body": "@MichaelKay Just sharing my experience. I wasn't able to squeeze out comparable performance out of woodstox, but maybe I did domething wrong somewhere." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T23:43:46.020", "Id": "236445", "ParentId": "236428", "Score": "3" } }, { "body": "<p>I have some suggestion for the code, that will not make to code faster, but cleaner, in my opinion.</p>\n\n<ol>\n<li>You can use the <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\"><code>try-with-resources</code></a> to handle the closing of the stream automatically (java 8+)</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>try(BufferedWriter br = new BufferedWriter(new FileWriter(file + \".csv\", true), 64 * 1024 * 1024)) {\n //[...]\n}\n</code></pre>\n\n<ol start=\"2\">\n<li>I suggest that you separate the code in more methods, to separate the different sections; preferably the section that handles the reading / parsing of the XML.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>private void parseXml(XMLStreamReader xmlStreamReader, boolean firstPass, boolean insideRowTag, BufferedWriter br) throws XMLStreamException, IOException {\n StringBuilder firstItems = new StringBuilder();\n while (xmlStreamReader.hasNext()) {\n xmlStreamReader.next();\n\n // If 4 event, meaning just some random '\\n' or something, we skip.\n if (xmlStreamReader.isCharacters()) {\n continue;\n }\n\n // If we are at a start element, we want to check a couple of things\n if (xmlStreamReader.isStartElement()) {\n // If we are at our rowtag, we want to start looking at what is inside.\n // We are 'continuing' because a Rowtag will not have any \"elementText\" in it, so we want to continue to the next tag.\n if (xmlStreamReader.getLocalName().equalsIgnoreCase(ROWTAG)) {\n insideRowTag = true;\n continue;\n }\n\n // if we are at a tag inside a row tag, we want to extract that information (the text it contains) from it....\n if (insideRowTag) {\n // ...but first, if we have not started to collect everything, we need to collect the headers!\n // This makes an assumption that all the \"headers\" are constant. If the first record has 6 tags in it,\n // but the next one has 7 tags in it, we are in trouble. We can add flexibility for that, I think.\n if (firstPass) {\n // We want to write the headers first\n br.write(xmlStreamReader.getLocalName() + ',');\n\n // And collect the items inside in a stringBuilder, which we'll dump later.\n firstItems.append(xmlStreamReader.getElementText()).append(',');\n } else {\n // If we're not in the first pass, just write the elements directly.\n br.write(xmlStreamReader.getElementText() + ',');\n }\n }\n }\n\n // If we are at an end element that is the rowTag, so at the end of the record, we want to do a couple of things\n if (xmlStreamReader.isEndElement() &amp;&amp; xmlStreamReader.getLocalName().equalsIgnoreCase(ROWTAG)) {\n // First, if we are at the first pass, we want to send out the elements inside the first record\n // that we were collecting to dump *after* we got all the headers\n if (firstPass) {\n firstPass = false;\n br.write('\\n' + StringUtils.chop(firstItems.toString()));\n }\n\n // Then we set this off so that we no longer collect irrelevant data if it is present.\n insideRowTag = false;\n br.write('\\n');\n }\n }\n}\n</code></pre>\n\n<h3>Refactored code</h3>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class XmlConverter2 {\n private static final Logger logger = LoggerFactory.getLogger(XmlConverter2.class);\n private static final String ROWTAG = \"person\";\n\n public void readLargeXmlWithWoodStox(String file)\n throws FactoryConfigurationError, XMLStreamException, IOException {\n long startTime = System.nanoTime();\n // set up a Woodstox reader\n XMLInputFactory xmlif = XMLInputFactory2.newInstance();\n\n XMLStreamReader xmlStreamReader = xmlif.createXMLStreamReader(new FileReader(file));\n boolean firstPass = true;\n boolean insideRowTag = false;\n\n Files.deleteIfExists(new File(file + \".csv\").toPath());\n\n try (BufferedWriter br = new BufferedWriter(new FileWriter(file + \".csv\", true), 64 * 1024 * 1024)) {\n parseXml(xmlStreamReader, firstPass, insideRowTag, br);\n } catch (Exception e) {\n logger.error(\"Error! \" + e.toString());\n } finally {\n xmlStreamReader.close();\n }\n\n long endTime = System.nanoTime();\n long totalTime = endTime - startTime;\n logger.info(\"Done! Time took: {}\", totalTime / 1000000000);\n }\n\n private void parseXml(XMLStreamReader xmlStreamReader, boolean firstPass, boolean insideRowTag, BufferedWriter br) throws XMLStreamException, IOException {\n StringBuilder firstItems = new StringBuilder();\n while (xmlStreamReader.hasNext()) {\n xmlStreamReader.next();\n\n // If 4 event, meaning just some random '\\n' or something, we skip.\n if (xmlStreamReader.isCharacters()) {\n continue;\n }\n\n // If we are at a start element, we want to check a couple of things\n if (xmlStreamReader.isStartElement()) {\n // If we are at our rowtag, we want to start looking at what is inside.\n // We are 'continuing' because a Rowtag will not have any \"elementText\" in it, so we want to continue to the next tag.\n if (xmlStreamReader.getLocalName().equalsIgnoreCase(ROWTAG)) {\n insideRowTag = true;\n continue;\n }\n\n // if we are at a tag inside a row tag, we want to extract that information (the text it contains) from it....\n if (insideRowTag) {\n // ...but first, if we have not started to collect everything, we need to collect the headers!\n // This makes an assumption that all the \"headers\" are constant. If the first record has 6 tags in it,\n // but the next one has 7 tags in it, we are in trouble. We can add flexibility for that, I think.\n if (firstPass) {\n // We want to write the headers first\n br.write(xmlStreamReader.getLocalName() + ',');\n\n // And collect the items inside in a stringBuilder, which we'll dump later.\n firstItems.append(xmlStreamReader.getElementText()).append(',');\n } else {\n // If we're not in the first pass, just write the elements directly.\n br.write(xmlStreamReader.getElementText() + ',');\n }\n }\n }\n\n // If we are at an end element that is the rowTag, so at the end of the record, we want to do a couple of things\n if (xmlStreamReader.isEndElement() &amp;&amp; xmlStreamReader.getLocalName().equalsIgnoreCase(ROWTAG)) {\n // First, if we are at the first pass, we want to send out the elements inside the first record\n // that we were collecting to dump *after* we got all the headers\n if (firstPass) {\n firstPass = false;\n br.write('\\n' + StringUtils.chop(firstItems.toString()));\n }\n\n // Then we set this off so that we no longer collect irrelevant data if it is present.\n insideRowTag = false;\n br.write('\\n');\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T10:41:21.913", "Id": "463540", "Score": "0", "body": "This definitely looks a lot cleaner! Thank you for the suggestion!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T00:33:40.900", "Id": "236449", "ParentId": "236428", "Score": "4" } }, { "body": "<p>I was somewhat curious if Woodstox has improved, so I wrote a complete parser for your example data. It's in a different style than your code, complete repo: <a href=\"https://github.com/chhh/testing-woodstox-xml-parsing\" rel=\"nofollow noreferrer\">https://github.com/chhh/testing-woodstox-xml-parsing</a></p>\n\n<p><strong>My results with fake data records that I created:</strong><br>\nParsed 4,000,000 persons (1.36 GB) in 16.75 seconds (Ryzen5 3600), memory usage wasn't really significant.</p>\n\n<p>First of all there's a newer version of Woodstox on Maven Central.<br>\nGradle dependency: <code>implementation 'com.fasterxml.woodstox:woodstox-core:6.0.3'</code><br>\nThey now have XMLStreamReader2 with <code>.configureForSpeed()</code> option. I didn't really check what it does, but for my test it didn't do much.</p>\n\n<p>Had to create fake data. You can make files of any size with <a href=\"https://github.com/chhh/testing-woodstox-xml-parsing/blob/master/src/main/java/com/dmtavt/tests/FakeData.java\" rel=\"nofollow noreferrer\">FakeData.createHugeXml(Path path, int numEntries)</a>.</p>\n\n<p>Just in case, here's main parsing code, excluding the Person class (which is not very interesing and can be found <a href=\"https://github.com/chhh/testing-woodstox-xml-parsing/blob/db189b4e9b5efb87f3b5c4f7cf6905e075b8d3c9/src/main/java/com/dmtavt/tests/woodstox/WoodstoxParser.java#L121\" rel=\"nofollow noreferrer\">here</a>)</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class WoodstoxParser {\n @FunctionalInterface\n interface ConditionCallback {\n boolean processXml(XMLStreamReader2 sr) throws XMLStreamException;\n }\n\n interface TagPairCallback {\n void tagStart(String tagName, XMLStreamReader2 sr) throws XMLStreamException;\n\n void tagContents(String tagName, StringBuilder sb);\n }\n\n public static void processUntilTrue(XMLStreamReader2 sr, ConditionCallback callback) throws XMLStreamException {\n do {\n if (callback.processXml(sr))\n return;\n } while (sr.hasNext() &amp;&amp; sr.next() &gt;= 0);\n throw new IllegalStateException(\"xml document ended without callback returning true\");\n }\n\n /** Main parsing function. **/\n public static List&lt;Person&gt; parse(Path path) throws IOException, XMLStreamException {\n XMLInputFactory2 f = (XMLInputFactory2) XMLInputFactory2.newFactory();\n f.configureForSpeed();\n// f.configureForLowMemUsage();\n XMLStreamReader2 sr = null;\n try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {\n sr = (XMLStreamReader2) f.createXMLStreamReader(br);\n\n // fast forward to beginning 'persons' tag (will throw if we don't find the tag at all)\n processUntilTrue(sr, sr1 -&gt; isTagStart(sr1, \"persons\"));\n\n final List&lt;Person&gt; persons = new ArrayList&lt;&gt;(); // we've found the tag, so we can allocate storage for data\n final StringBuilder sb = new StringBuilder(); // reuse a single string builder for all character aggregation\n\n // now keep processing unless we reach closing 'persons' tag\n processUntilTrue(sr, sr1 -&gt; {\n if (isTagEnd(sr1, \"persons\"))\n return true;\n\n if (isTagStart(sr1, \"person\")) {\n // now we're finally reached a 'person', can start processing it\n int idIndex = sr1.getAttributeInfo().findAttributeIndex(\"\", \"id\");\n Person p = new Person(Integer.parseInt(sr1.getAttributeValue(idIndex)));\n\n sr1.next();\n processUntilTrue(sr1, sr2 -&gt; {\n // processing the meat of a 'person' tag\n // split it into a function of its own to not clutter the main loop\n //return processPerson(sr2, p, sb);\n if (isTagEnd(sr2, \"person\"))\n return true; // we're done processing a 'person' only when we reach the ending 'person' tag\n\n if (isTagStart(sr2))\n processTagPair(sr2, sb, p);\n\n return false;\n });\n // we've reached the end of a 'person'\n if (p.isComplete()) {\n persons.add(p);\n } else {\n throw new IllegalStateException(\"Whoa, a person had incomplete data\");\n }\n }\n\n return false;\n });\n return persons;\n\n } finally {\n if (sr != null)\n sr.close();\n }\n\n }\n\n public static void processTagPair(XMLStreamReader2 sr, StringBuilder sb, TagPairCallback callback) throws XMLStreamException {\n final String tagName = sr.getLocalName();\n callback.tagStart(tagName, sr); // let the caller do whatever they need with the tag name and attributes\n sb.setLength(0); // clear our buffer, preparing to read the characters inside\n processUntilTrue(sr, sr1 -&gt; {\n switch (sr1.getEventType()) {\n case XMLStreamReader2.END_ELEMENT: // ending condition\n callback.tagContents(tagName, sb); // let the caller do whatever they need with text contents of the tag\n return true;\n case XMLStreamReader2.CHARACTERS:\n sb.append(sr1.getText());\n break;\n }\n return false;\n });\n }\n\n public static boolean isTagStart(XMLStreamReader2 sr, String tagName) {\n return XMLStreamReader2.START_ELEMENT == sr.getEventType() &amp;&amp; tagName.equalsIgnoreCase(sr.getLocalName());\n }\n\n public static boolean isTagStart(XMLStreamReader2 sr) {\n return XMLStreamReader2.START_ELEMENT == sr.getEventType();\n }\n\n public static boolean isTagEnd(XMLStreamReader2 sr, String tagName) {\n return XMLStreamReader2.END_ELEMENT == sr.getEventType() &amp;&amp; tagName.equalsIgnoreCase(sr.getLocalName());\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T10:40:56.960", "Id": "463539", "Score": "0", "body": "Thank you so much for the answer. I’m currently on vacation and get back in two or so weeks. Will take a closer look then - unless I get curios, which I probably will, and look at it before :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T01:52:08.367", "Id": "236483", "ParentId": "236428", "Score": "4" } }, { "body": "<p>Aside from other suggestions which make sense, one simple thing to try is to use Aalto-xml parser from:</p>\n<p><a href=\"https://github.com/FasterXML/aalto-xml\" rel=\"nofollow noreferrer\">https://github.com/FasterXML/aalto-xml</a></p>\n<p>it implements Stax API (as well as Stax2 extension, SAX); and as long as you do not need full DTD handling (which I suspect you don't) has the feature set you need.\nFor common read use cases I think it can be 30-40% faster; but most importantly it should be very easy to just try out.</p>\n<p>Maven coordinates are:</p>\n<ul>\n<li>group id: <code>com.fasterxml</code></li>\n<li>artifact id: <code>aalto-xml</code></li>\n<li>version (latest): 1.2.2</li>\n</ul>\n<p>And <code>XMLInputFactory</code> implementation <code>com.fasterxml.aalto.stax.InputFactoryImpl</code>. I would recommend creating instance directly, instead of using <code>XMLInputFactory.newInstance()</code> so you can sure of the exact implementation you have (if you have multiple Stax implementations in classpath, choice is arbitrary).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-19T22:03:59.520", "Id": "259738", "ParentId": "236428", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T17:55:43.320", "Id": "236428", "Score": "6", "Tags": [ "java", "parsing", "xml", "stream" ], "Title": "Make my XML Parser in Java using WoodStox run faster and use less memory, or just generally better" }
236428
<p><a href="https://i.stack.imgur.com/Xxnia.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xxnia.png" alt="StigJan 1"></a></p> <p><a href="https://i.stack.imgur.com/iabJJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iabJJ.png" alt="Stigjan 2"></a></p> <p>What I have tried to accomplish with the code is to make some sort of partner budget where 2 people can have 2 separate budgets with separate expenses but which are still intertwined with eachother in some instances.</p> <p>The code refers to the range <code>A36:H160</code> and <code>K36:R76</code>. The first range being Fixed expenses and the 2. range being Other Expenses. Each range have 4 columns with the Amount Spend, date, category, if it is a Common expense (Fælles) or Paid By (Lagt Ud) and description.</p> <p>So if one person pays for something that is consumed by both(Food), Fælles will be chosen in the 3. column. And if one pays for the whole amount for the other person, Lagt Ud(Paid By) will be chosen.</p> <p>If Fælles, there will be a -SUMIFS/2 in the expense. And if Lagt Ud it will just minus it from the budget but add it to the other persons budget. The other half of the expense is then added to a box with a sum of all Fælles and Lagt Ud that month to conclude who owes who and what amount. This number is changing the whole time according to who pays most.</p> <p>The Fælles and STIGS code are just 2 sides of the same code and makes sure that when STIGS is added in the other persons budget it will subtract half of the amount of the expense.</p> <p>The bolding part of the code is made in order to not add the expenses more than once.</p> <p>The STIGS and STIG code also have the function to give a good overview through conditional formatting who has made the expenses. So STIGS would be green in my sheet but red in hers.</p> <p>This is outlines why the code should copy the data in the columns, make the 3. column bold, add STIG or STIGS to the description and remove the 3. column in the other sheet (so that it doesn't look like the other person did the expense)</p> <p>Hope all this makes sense.</p> <p>Also i used to have a interior color part in the code, but have since removed this, as this works better with conditional formatting.</p> <pre><code>Private Sub CommandButton1_Click() Dim wsSource, wsTarget As Worksheet Dim i, iLastSource, iRowTarget, count As Long Dim cell As Range Set wsSource = Worksheets("Stig Jan") iLastSource = wsSource.Cells(Rows.count, 1).End(xlUp).Row Set wsTarget = Worksheets("Laura Jan") count = 0 With wsSource iRowTarget = wsTarget.Cells(Rows.count, 1).End(xlUp).Row + 1 For i = 36 To iLastSource Set cell = .Cells(i, 4) If cell.Font.Bold = False Then If cell.Value = "Fælles" Then cell.Offset(, 1).Value = "STIGS " &amp; cell.Offset(, 1).Value wsTarget.Range("A" &amp; iRowTarget &amp; ":H" &amp; iRowTarget).Value = .Range("A" &amp; i &amp; ":H" &amp; i).Value wsTarget.Range("D" &amp; iRowTarget).ClearContents iRowTarget = iRowTarget + 1 count = count + 1 End If End If If cell.Font.Bold = False Then If cell.Value = "Lagt Ud" Then cell.Offset(, 1).Value = "STIG " &amp; cell.Offset(, 1).Value wsTarget.Range("A" &amp; iRowTarget &amp; ":H" &amp; iRowTarget).Value = .Range("A" &amp; i &amp; ":H" &amp; i).Value wsTarget.Range("D" &amp; iRowTarget).ClearContents iRowTarget = iRowTarget + 1 count = count + 1 End If End If If cell.Value = "Fælles" Or cell.Value = "Lagt Ud" Then wsSource.Rows(i).Columns("D").Font.Bold = True End If Next iRowTarget = wsTarget.Range("K76").End(xlUp).Row + 1 For i = 36 To iLastSource Set cell = .Cells(i, 14) If cell.Font.Bold = False Then If cell.Value = "Fælles" Then cell.Offset(, 1).Value = "STIGS " &amp; cell.Offset(, 1).Value wsTarget.Range("K" &amp; iRowTarget &amp; ":R" &amp; iRowTarget).Value = .Range("K" &amp; i &amp; ":R" &amp; i).Value wsTarget.Range("N" &amp; iRowTarget).ClearContents iRowTarget = iRowTarget + 1 count = count + 1 End If End If If cell.Font.Bold = False Then If cell.Value = "Lagt Ud" Then cell.Offset(, 1).Value = "STIG " &amp; cell.Offset(, 1).Value wsTarget.Range("K" &amp; iRowTarget &amp; ":R" &amp; iRowTarget).Value = .Range("K" &amp; i &amp; ":R" &amp; i).Value wsTarget.Range("N" &amp; iRowTarget).ClearContents iRowTarget = iRowTarget + 1 count = count + 1 End If End If If cell.Value = "Fælles" Or cell.Value = "Lagt Ud" Then wsSource.Rows(i).Columns("N").Font.Bold = True End If Next End With MsgBox "Done : " &amp; count &amp; " rows copied" End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T20:37:27.993", "Id": "463368", "Score": "1", "body": "Why do you want to shorten it? If I take a look at it, I'd cut it into multiple subs instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T20:59:00.467", "Id": "463374", "Score": "0", "body": "Hi Mast, thank you for taking time to review it. The code has been developed with lots of help from a couple of programmers. And then i have cut/copied/pasted it in to place using the trial and error method. :) And i dont think i think like a programmer yet, so was just thinking that maybe there are some unnecessary lines in there?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T21:00:20.953", "Id": "463375", "Score": "1", "body": "I actually just deleted the last part. With the interior color because i think it will be better with conditional formatting. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T21:55:58.803", "Id": "463384", "Score": "0", "body": "I have read abit about subs and cut it up with the best of my abilities. But most likely i am doing it wrong since the code stops at the beginning. i have addded a picture." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T19:49:49.700", "Id": "463491", "Score": "1", "body": "That looks like a breakpoint. Remove all breakpoints before execution. Does the code work or not?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T20:02:40.067", "Id": "463493", "Score": "0", "body": "The code works in the original form. I guess i just really lack fundamentals. So I am just abit unsure what you mean when you say i could cut it into subs. Breakpoints is that the lines?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T20:13:00.277", "Id": "463496", "Score": "0", "body": "I work in carpentry and just kinda stumbled into this arena out of curiosity. This is my first project. But it has definitly sparked my interest of getting better at it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T20:37:03.987", "Id": "463501", "Score": "0", "body": "Under the Debug menu, try to Clear All Breakpoints (Ctrl + Shift + F9). If you have breakpoints (indicated by a dot in front of the line while the code isn't running), that will remove them all. Breakpoints are for debugging, they're easy to place by mistake." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T21:06:38.060", "Id": "463503", "Score": "0", "body": "in this case i think it was not a breakpoint. I am having some trouble placing the subs. Will have to read some more about it!" } ]
[ { "body": "<p>Turn on <code>Option Explicit</code>. From the menu at the top Tools>Option>Editor tab>Code Settings group>Require Variable Declaration check box. Make sure that is checked. This mandates that you use <code>Dim foo as Bar</code> before you can use any variables and will save you needless headaches. Why? <code>myRange</code> is not declared anywhere and a simple typo can mean a half hour or more debugging to find that typo. This will add <code>Option Explicit</code> automatically to any <em>new</em> code modules. It's on you however to add it any existing code modules.</p>\n\n<hr>\n\n<p>Multiple variables declared on one line. <code>Dim i, iLastSource, iRowTarget, count As Long</code> only <code>count</code> is declared as a <code>Long</code> type. The rest are <code>Variant</code>. Likewise for <code>Dim wsSource, wsTarget As Worksheet</code> only wsTarget has the type of <code>Worksheet</code>, <code>wsSource</code> if of type <code>Variant</code>. Fix this by declaring each variable on its own line. Also declare them just before you use them. This makes refactoring easier and avoids unused variables.</p>\n\n<hr>\n\n<p>Your Stig Jan worksheet isn't created in the click event which means it's available at design time. Reference that worksheet by using the <a href=\"https://docs.microsoft.com/en-us/office/vba/api/excel.worksheet.codename\" rel=\"nofollow noreferrer\">Worksheet.CodeName property</a>. In the VBIDE under View>Properties Window (Hotkey: <code>F4</code>). Rename the CodeName, shown in properties window as (Name) property, to a descriptive name. I've rename it to StigJan.</p>\n\n<p><a href=\"https://i.stack.imgur.com/b3TmJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/b3TmJ.png\" alt=\"enter image description here\"></a></p>\n\n<p>Then you can reference that worksheet directly. This way if the name of the worksheet changes your code won't break.</p>\n\n<p><a href=\"https://i.stack.imgur.com/aH7qP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aH7qP.png\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<p>Hungarian notation isn't needed. Because you have your variables declared with a type <code>As Worksheet</code> you don't need the <code>ws</code> prefix. Place your cursor on a variable name and from the menu at the top Edit>Quick Info (Hotkey: <code>Ctrl+I</code>) you can display the variables type.</p>\n\n<p><a href=\"https://i.stack.imgur.com/FTTrq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FTTrq.png\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<p>Your <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/fornext-statement\" rel=\"nofollow noreferrer\">For ... Next statement</a> logic can be simplified. You're looping with the counter <code>i</code> but within that loop setting a <code>cell</code> variable. This is a candidate for a <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/for-eachnext-statement\" rel=\"nofollow noreferrer\">For Each ... Next statement</a>.</p>\n\n<pre><code>For i = 36 To iLastSource\n Dim cell As Worksheet\n Set cell = .Cells(i, 4)\n</code></pre>\n\n<p>Becomes the code below. This clarifies the intent that you're looping through each cell in the area.</p>\n\n<pre><code>Dim checkArea As Range\nSet checkArea = source.Range(source.Cells(36, 4), source.Cells(iLastSource, 4))\nDim checkCell As Range\nFor Each checkCell In checkArea\n</code></pre>\n\n<p>Once you've done that the next step is to consolidate the if checks. <code>cell.Font.Bold = False</code> can be rewritten as <code>Not cell.Font.Bold</code>. Combine that into a single check with the value check of the cell below it.</p>\n\n<pre><code>If cell.Font.Bold = False Then\n If cell.Value = \"Fælles\" Then\n</code></pre>\n\n<p>Becomes</p>\n\n<pre><code>If Not checkCell.Font.Bold And checkCell.Value = \"Fælles\" Then\n</code></pre>\n\n<p>The body within the If statement can then be reviewed. The parts that change are <code>\"STIGS \"</code>, <code>\"A\"</code>, <code>\"H\"</code>, <code>\"D\"</code>. </p>\n\n<pre><code>cell.Offset(, 1).Value = \"STIGS \" &amp; cell.Offset(, 1).Value\nwsTarget.Range(\"A\" &amp; iRowTarget &amp; \":H\" &amp; iRowTarget).Value = .Range(\"A\" &amp; i &amp; \":H\" &amp; i).Value\nwsTarget.Range(\"D\" &amp; iRowTarget).ClearContents\niRowTarget = iRowTarget + 1\ncount = count + 1\n</code></pre>\n\n<p>We extract that into its own dedicated Sub and supply the arguments that let it requires. The parameters <code>targetRow</code>, and <code>copiedRowCount</code> have the <code>ByRef</code> modifier because we want any changes to be reflected in the calling member after this Sub finishes.</p>\n\n<pre><code>Private Sub UpdateOffsetCellAndClearContents(ByVal checkCell As Range, _\n ByVal sourceWorksheet As Worksheet, _\n ByVal targetWorksheet As Worksheet, _\n ByRef targetRow As Long, _\n ByVal leftTargetColumn As Variant, _\n ByVal rightTargetColumn As Variant, _\n ByVal columnOfCellToClear As Variant, _\n ByVal offsetPrefixValue As String, _\n ByRef copiedRowCount As Long)\n checkCell.Offset(ColumnOffset:=1).Value = offsetPrefixValue &amp; \" \" &amp; checkCell.Offset(ColumnOffset:=1).Value\n\n Dim destinationArea As Range\n Set destinationArea = targetWorksheet.Range(targetWorksheet.Cells(targetRow, leftTargetColumn), targetWorksheet.Cells(targetRow, rightTargetColumn))\n Dim sourceArea As Range\n Set sourceArea = sourceWorksheet.Range(sourceWorksheet.Cells(checkCell.Row, leftTargetColumn), sourceWorksheet.Cells(checkCell.Row, rightTargetColumn))\n destinationArea.Value2 = sourceArea.Value2\n\n targetWorksheet.Cells(targetRow, columnOfCellToClear).ClearContents\n\n targetRow = targetRow + 1\n copiedRowCount = copiedRowCount + 1\nEnd Sub\n</code></pre>\n\n<p>The call sites where this is used.</p>\n\n<pre><code>UpdateOffsetCellAndClearContents checkCell, source, target, targetRow, \"A\", \"H\", \"D\", \"STIGS \", count\n... \nUpdateOffsetCellAndClearContents checkCell, source, target, targetRow, \"A\", \"H\", \"D\", \"STIG \", count\n...\nUpdateOffsetCellAndClearContents checkCell, source, target, targetRow, \"K\", \"R\", \"N\", \"STIGS \", count\n...\nUpdateOffsetCellAndClearContents checkCell, source, target, targetRow, \"K\", \"R\", \"N\", \"STIG \", count\n</code></pre>\n\n<p>Now if/when you need to make an update to the logic you change it within the Sub and all sites where it's called are now updated.</p>\n\n<hr>\n\n<p>Instead of <code>If cell.Value = \"Fælles\" Or cell.Value = \"Lagt Ud\" Then</code> to bold the font or <code>If myCell Like \"*STIG*\" Then</code> to color a cells interior use conditional formatting. That way you set it for the entire range and it will automatically be applied whenever the cell changes. For their respective parts I came up with the below for bolding and </p>\n\n<pre><code>Private Sub AddBoldConditionalFormattingTo(ByVal formatArea As Range, ParamArray values())\n If formatArea.FormatConditions.count &gt; 0 Then\n formatArea.FormatConditions.Delete\n End If\n\n Dim topLeftAddress As String\n topLeftAddress = formatArea.Cells(1, 1).Address(False, False)\n Dim orArguments As String\n orArguments = topLeftAddress &amp; \"=\"\"\" &amp; Join(values, \"\"\",\" &amp; topLeftAddress &amp; \"=\"\"\") &amp; \"\"\"\"\n Dim formulaForTopLeftCell As String\n formulaForTopLeftCell = \"=OR(\" &amp; orArguments &amp; \")\"\n\n Dim addedCondition As FormatCondition\n Set addedCondition = formatArea.FormatConditions.Add(XlFormatConditionType.xlExpression, Formula1:=formulaForTopLeftCell)\n addedCondition.Font.Bold = True\nEnd Sub\n\nPrivate Sub AddInteriorColorConditionalFormattingTo(ByVal formatArea As Range, ByVal interiorColor As Long, ByVal valueToSearchFor As String)\n If formatArea.FormatConditions.count &gt; 0 Then\n formatArea.FormatConditions.Delete\n End If\n\n Dim formulaForTopLeftCell As String\n formulaForTopLeftCell = \"=NOT(ISERROR(SEARCH(\"\"\" &amp; \"STIG\" &amp; \"\"\",\" &amp; formatArea.Cells(1, 1).Address(False, False) &amp; \")))\"\n\n Dim addedCondition As FormatCondition\n Set addedCondition = formatArea.FormatConditions.Add(XlFormatConditionType.xlExpression, Formula1:=formulaForTopLeftCell, TextOperator:=XlContainsOperator.xlContains)\n addedCondition.Interior.Color = interiorColor\nEnd Sub\n</code></pre>\n\n<p>Their respective call sites as below</p>\n\n<pre><code>AddBoldConditionalFormattingTo checkArea, \"Fælles\", \"Lagt Ud\"\n</code></pre>\n\n<p>and </p>\n\n<pre><code>AddInteriorColorConditionalFormattingTo target.Range(\"A36:S1000\"), \"STIG\", RGB(255, 220, 220)\n</code></pre>\n\n<hr>\n\n<p>Static cell ranges. <code>Range(\"K76\")</code> will break whenever a row above or column to the left is inserted/deleted, as will <code>Range(\"A36:S1000\")</code>. Make these named ranges and reference them through the named ranges because named ranges don't break with insertions/deletions. I have no clue what these cells represent and can't begin to offer a suggestion.</p>\n\n<hr>\n\n<p>Magic numbers. <code>36</code> has what significance? It's in the code for some reason. Why is it there? Use a name to describe why its there and/or its siginificance. If this number will never ever change convert it to a <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/const-statement\" rel=\"nofollow noreferrer\">Const statement</a> with a descriptive name like <code>Const StartRow As Long = 36</code>. If it may vary at run-time determine its value and assign it </p>\n\n<pre><code>dim startRow As Long\nstartRow = source.Cells(1,4).End(xlDown).Row + 1\n</code></pre>\n\n<hr>\n\n<p>The refactored code below reflect these changes</p>\n\n<pre><code>Option Explicit\n\nPrivate Sub CommandButton1_Click()\n Dim source As Worksheet\n Set source = StigJan\n Dim lastSourceRow As Long\n lastSourceRow = source.Cells(Rows.count, 1).End(xlUp).Row\n\n Dim target As Worksheet\n Set target = LauraJan\n\n Dim targetRow As Long\n targetRow = target.Cells(Rows.count, 1).End(xlUp).Row + 1\n\n Const StartRow As Long = 36\n\n Dim count As Long\n Dim checkArea As Range\n Set checkArea = source.Range(source.Cells(StartRow, 4), source.Cells(lastSourceRow, 4))\n Dim checkCell As Range\n For Each checkCell In checkArea\n If Not checkCell.Font.Bold And checkCell.Value = \"Fælles\" Then\n UpdateOffsetCellAndClearContents checkCell, source, target, targetRow, \"A\", \"H\", \"D\", \"STIGS \", count\n End If\n\n If Not checkCell.Font.Bold And checkCell.Value = \"Lagt Ud\" Then\n UpdateOffsetCellAndClearContents checkCell, source, target, targetRow, \"A\", \"H\", \"D\", \"STIG \", count\n End If\n Next\n AddBoldConditionalFormattingTo checkArea, \"Fælles\", \"Lagt Ud\"\n\n targetRow = target.Range(\"K76\").End(xlUp).Row + 1\n Set checkArea = source.Range(source.Cells(StartRow, 14), source.Cells(lastSourceRow, 14))\n For Each checkCell In checkArea\n If Not checkCell.Font.Bold And checkCell.Value = \"Fælles\" Then\n UpdateOffsetCellAndClearContents checkCell, source, target, targetRow, \"K\", \"R\", \"N\", \"STIGS \", count\n End If\n\n If Not checkCell.Font.Bold And checkCell.Value = \"Lagt Ud\" Then\n UpdateOffsetCellAndClearContents checkCell, source, target, targetRow, \"K\", \"R\", \"N\", \"STIG \", count\n End If\n Next\n AddBoldConditionalFormattingTo checkArea, \"Fælles\", \"Lagt Ud\"\n\n AddInteriorColorConditionalFormattingTo target.Range(\"AdequatelyNamedArea\"), \"STIG\", RGB(255, 220, 220)\n\n MsgBox \"Done : \" &amp; count &amp; \" rows copied\"\nEnd Sub\n\nPrivate Sub UpdateOffsetCellAndClearContents(ByVal checkCell As Range, _\n ByVal sourceWorksheet As Worksheet, _\n ByVal targetWorksheet As Worksheet, _\n ByRef targetRow As Long, _\n ByVal leftTargetColumn As Variant, _\n ByVal rightTargetColumn As Variant, _\n ByVal columnOfCellToClear As Variant, _\n ByVal offsetPrefixValue As String, _\n ByRef copiedRowCount As Long)\n checkCell.Offset(ColumnOffset:=1).Value = offsetPrefixValue &amp; \" \" &amp; checkCell.Offset(ColumnOffset:=1).Value\n\n Dim destinationArea As Range\n Set destinationArea = targetWorksheet.Range(targetWorksheet.Cells(targetRow, leftTargetColumn), targetWorksheet.Cells(targetRow, rightTargetColumn))\n Dim sourceArea As Range\n Set sourceArea = sourceWorksheet.Range(sourceWorksheet.Cells(checkCell.Row, leftTargetColumn), sourceWorksheet.Cells(checkCell.Row, rightTargetColumn))\n destinationArea.Value2 = sourceArea.Value2\n\n targetWorksheet.Cells(targetRow, columnOfCellToClear).ClearContents\n\n targetRow = targetRow + 1\n copiedRowCount = copiedRowCount + 1\nEnd Sub\n\nPrivate Sub AddBoldConditionalFormattingTo(ByVal formatArea As Range, ParamArray values())\n If formatArea.FormatConditions.count &gt; 0 Then\n formatArea.FormatConditions.Delete\n End If\n\n Dim topLeftAddress As String\n topLeftAddress = formatArea.Cells(1, 1).Address(False, False)\n Dim orArguments As String\n orArguments = topLeftAddress &amp; \"=\"\"\" &amp; Join(values, \"\"\",\" &amp; topLeftAddress &amp; \"=\"\"\") &amp; \"\"\"\"\n Dim formulaForTopLeftCell As String\n formulaForTopLeftCell = \"=OR(\" &amp; orArguments &amp; \")\"\n\n Dim addedCondition As FormatCondition\n Set addedCondition = formatArea.FormatConditions.Add(XlFormatConditionType.xlExpression, Formula1:=formulaForTopLeftCell)\n addedCondition.Font.Bold = True\nEnd Sub\n\nPrivate Sub AddInteriorColorConditionalFormattingTo(ByVal formatArea As Range, ByVal interiorColor As Long, ByVal valueToSearchFor As String)\n If formatArea.FormatConditions.count &gt; 0 Then\n formatArea.FormatConditions.Delete\n End If\n\n Dim formulaForTopLeftCell As String\n formulaForTopLeftCell = \"=NOT(ISERROR(SEARCH(\"\"\" &amp; valueToSearchFor &amp; \"\"\",\" &amp; formatArea.Cells(1, 1).Address(False, False) &amp; \")))\"\n\n Dim addedCondition As FormatCondition\n Set addedCondition = formatArea.FormatConditions.Add(XlFormatConditionType.xlExpression, Formula1:=formulaForTopLeftCell, TextOperator:=XlContainsOperator.xlContains)\n addedCondition.Interior.Color = interiorColor\nEnd Sub\n</code></pre>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-04T13:02:35.457", "Id": "463849", "Score": "0", "body": "I am just completely blown away and overwhelmed by the amount of help I have received in this community. This must have taken ages to come up with! I am also very surprised how you are able interpret what i want to do with the information i have put out. I got the impression that you have to be very concise and precise about the the questions on Stack Overflow, so this is why I haven't written too much info about what I wanna do. I can't wait to check this out and I will try to write what i am trying to do and why when i get back home! Thank you from the bottom of my heart!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-04T17:32:29.843", "Id": "463904", "Score": "0", "body": "Hi Ivenbach, I have read your answer a couple of times now and to be honest it is not everything i understand yet. Will definitely have to revisit it a few times more. I have tried to do the instructions now and the code seems to be running fine except for this part:`Set addedCondition = formatArea.FormatConditions.Add(XlFormatConditionType.xlExpression, Formula1:=formulaForTopLeftCell)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-04T17:36:28.557", "Id": "463905", "Score": "0", "body": "Also I have rewritten the whole question in order for it to make more sense of what i have tried to do to you and others that might see it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-05T09:22:58.930", "Id": "463988", "Score": "0", "body": "Just wanna say that i am very grateful for your elaborate answer. This is very advanced for me at this point. But i will revisit it many times and try to grasp every step of it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-26T22:03:02.290", "Id": "466765", "Score": "0", "body": "The `Set addedCondition = ...` is adding a format condition. Have a look at the documentation for [FormatConditions.Add](https://docs.microsoft.com/en-us/office/vba/api/excel.formatconditions.add). It uses `xlExpression` which is a member of [XlFormatConditionType enumeration](https://docs.microsoft.com/en-us/office/vba/api/excel.xlformatconditiontype) as the first argument. The argument for `Formula1` is built up and saved to a variable. Work on a simplified format that you want to add first then add complexity until it matches your original. That should get you to resolving that issue." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-04T00:50:52.700", "Id": "236614", "ParentId": "236429", "Score": "3" } } ]
{ "AcceptedAnswerId": "236614", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T18:46:03.383", "Id": "236429", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "Adds text to specific cells then bolds one column and copies it to target sheet removing bolded column. Makes last column red" }
236429
<p>Recently I was receiving Error 2015 when trying to use <code>Application.Evaluate</code>, then I realized it was because my formula was greater than 255 characters. As a workaround, I came up with this UDF:</p> <pre><code>Function AdvancedEvaluate(eformula As String) ThisWorkbook.Worksheets("Scripting Worksheet").Range("A1").Formula = eformula AdvancedEvaluate = ThisWorkbook.Worksheets("Scripting Worksheet").Range("A1").Value ThisWorkbook.Worksheets("Scripting Worksheet").Range("A1").ClearContents End Function </code></pre> <p>Which I use in place of all of my <code>Application.Evaluate</code>. However, I'm not satisfied with this solution... is my solution sufficient, or is there a better way to evaluate a formula of greater than 255 characters?</p>
[]
[ { "body": "<p>The function is implicitly public, takes an implicitly <code>ByRef</code> parameter that has no reason to not be passed <code>ByVal</code>, and returns an implicit <code>Variant</code> that should be explicit.</p>\n\n<p>It's also side-effecting, which makes it unusable as an actual UDF.</p>\n\n<p><code>ThisWorkbook.Worksheets(\"Scripting Worksheet\")</code> suggests the procedure is using a purposely-made bogus (hidden?) sheet just for that. So why does that sheet need to be dereferenced 3 times in the same scope? Give it a meaningful code name, and use it!</p>\n\n<pre><code>Public Function AdvancedEvaluate(ByVal expression As String) As Variant\n With ScriptingSheet.Range(\"A1\")\n .Formula = expression\n AdvancedEvaluate = .Value\n .ClearContents\n End With\nEnd Function\n</code></pre>\n\n<p>Now, that's the exact same logic, just more explicit and unnoticeably more efficient in the handling of object references.</p>\n\n<p>To the extent that the idea is to somehow get Excel's calc engine to do the work, other than getting the Excel devs to lift the 255-char limitation in the object model, I think that's as good as it's going to get. It's not a UDF though: in Excel a <em>User-Defined Function</em> refers to a function that can be invoked from a cell - but this function will only ever return an error value to Excel; VBA code can merrily consume it though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T19:22:43.143", "Id": "463486", "Score": "0", "body": "Thanks Mat, this is great! And you're right, I totally butchered the verbiage using UDF here. I was knocking my head for hours trying to figure out why my `Application.Evaluate` was failing!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T08:29:50.903", "Id": "518297", "Score": "0", "body": "Do you think this would be a valid use of a Sub taking outArguments ByRef, but not a tryEvaluate Function since we would rather Excel errors were propogated rather than booleanified." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T13:05:35.470", "Id": "518315", "Score": "0", "body": "@Greedo given it's side-effecting, that's a yes =)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T22:42:45.033", "Id": "236439", "ParentId": "236433", "Score": "10" } } ]
{ "AcceptedAnswerId": "236439", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T21:09:57.540", "Id": "236433", "Score": "6", "Tags": [ "vba", "excel" ], "Title": "Evaluating formulas greater than 255 characters" }
236433
<p>Please could we examine the below code for anyway to put all console output in one statements?</p> <pre><code> #include &lt;iostream&gt; using namespace std; int main( ) { //print("") in Python cout&lt;&lt;"Hello " "everybody!"&lt;&lt;endl; cout&lt;&lt;"My name is AK."&lt;&lt;endl; cout&lt;&lt;"Goodbye."&lt;&lt;endl; cout&lt;&lt;""&lt;&lt;endl; //Poem cout&lt;&lt;"Twinkle, twinkle, little bat!"&lt;&lt;endl; cout&lt;&lt;"How I wonder what you're at?"&lt;&lt;endl; cout&lt;&lt;"Up above the world you fly,"&lt;&lt;endl; cout&lt;&lt;"Like a tea-tray in the sky."&lt;&lt;endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T21:19:05.870", "Id": "463379", "Score": "0", "body": "You can just use `'\\n'` literals inside the text you want to output, or even better [raw string literals](https://en.cppreference.com/w/cpp/language/string_literal)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T21:45:08.283", "Id": "463383", "Score": "0", "body": "i did this #include <iostream>\nusing namespace std;\n\nint main( )\n{ //print(\"Hello World\")\n //Displays Hello World on the screen\n // Short form with string literals\n\n string Intro = \"Hello everybody!\"<<endl\n \"My name is AK\".\\n\n \"Goodbye.\"\\n\n \\n\n \"Twinkle, twinkle, little bat!\"\\n\n \"How I wonder what you're at\"?\\n\n \"Up above the world you fly,\"\\n\n \"Like a tea-tray in the sky.\";\n\n cout<< Intro<<end1;\n return 0;\n}" } ]
[ { "body": "<h2>Scope</h2>\n\n<p>This is really just limited to style and code formatting. </p>\n\n<h2>Two (almost) substantive points</h2>\n\n<ul>\n<li>You should get in the habbit of <strong>not</strong>:</li>\n</ul>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>It can get you into name-clash issues later, as you progress. </p>\n\n<ul>\n<li>You should be aware that <code>std::endl</code> flushes the stream buffer. This is often unnecessary, unwanted and can be slow if used in a tight loop. You should use <code>'\\n'</code> for most situations. If you are worried about\nplatform specific line-ending, don't be. <code>'\\n'</code> adapts, just like\n<code>std::endl</code>.</li>\n</ul>\n\n<h2>Code formatting</h2>\n\n<ul>\n<li>Install <a href=\"https://clang.llvm.org/docs/ClangFormat.html\" rel=\"noreferrer\">clang-format</a> or similar to help you with formatting. </li>\n</ul>\n\n<p>All I did was to integrate your <code>endl</code> into the strings and hit \"auto-clang-format\" and I got this:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nint main() {\n std::cout &lt;&lt; \"Hello everybody!\\n\"\n &lt;&lt; \"My name is AK.\\n\"\n &lt;&lt; \"Goodbye.\\n\"\n &lt;&lt; \"\\n\"\n\n // Poem\n &lt;&lt; \"Twinkle, twinkle, little bat!\\n\"\n &lt;&lt; \"How I wonder what you're at?\\n\"\n &lt;&lt; \"Up above the world you fly,\\n\"\n &lt;&lt; \"Like a tea-tray in the sky.\\n\";\n return 0;\n}\n\n</code></pre>\n\n<p>Which is \"good enough for me\". Clang format is very tunable, and I have it configured to something which works for me, and my team, in 99% of cases. So we don't spend time fighting the formatting of the code. </p>\n\n<p>The above style with \"one streaming operator\" <code>&lt;&lt;</code> at the beginning of each line is what we use most of the time. It makes sense when you have literals interspersed with variables and/or function calls. </p>\n\n<p>For this very specific (and rather atypical?) case, you could, as someone else pointed out, also just stream it all as one continuous literal. C++ allows you stop/start string literals like this:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nint main() {\n std::cout &lt;&lt; \"Hello everybody!\\n\"\n \"My name is AK.\\n\"\n \"Goodbye.\\n\"\n \"\\n\"\n\n // Poem\n \"Twinkle, twinkle, little bat!\\n\"\n \"How I wonder what you're at?\\n\"\n \"Up above the world you fly,\\n\"\n \"Like a tea-tray in the sky.\\n\";\n return 0;\n}\n\n</code></pre>\n\n<p>Hope that helps. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T22:19:41.297", "Id": "463387", "Score": "1", "body": "Why not using raw string literals for the whole text? Just to preserve the comments?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T22:29:33.783", "Id": "463388", "Score": "1", "body": "@πάνταῥεῖ Yes, as it is all one string, you could in this case. Have added that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T22:31:14.267", "Id": "463389", "Score": "0", "body": "Are you sure what _raw string literal_ means?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T22:34:10.223", "Id": "463391", "Score": "0", "body": "@πάνταῥεῖ\nIt's not something I get exited about, but yes I do. And I don't see the point here. It's just messy. but that's entirely subjective." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T05:06:32.617", "Id": "463416", "Score": "0", "body": "I am sorry for the messy cod. I hope i can soon learn how to write cleaner code. Thank you for the string literals direction. I found out why you used R\"x as it outputs raw data. You guys are the best." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T13:56:45.830", "Id": "463457", "Score": "0", "body": "@IEatBagels To be fair to him, he did below." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T16:17:38.387", "Id": "463472", "Score": "0", "body": "@OliverSchönrock Well, my bad ahah" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T22:11:12.897", "Id": "236437", "ParentId": "236434", "Score": "7" } }, { "body": "<p>You can do that in single statements using raw string literals:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\n int main( )\n { //print(\"\") in Python\n std::cout &lt;&lt; \nR\"x(Hello everybody! \nMy name is AK.\nGoodbye.\n)x\";\n\n //Poem\n std::cout&lt;&lt;\nR\"x(Twinkle, twinkle, little bat!\nHow I wonder what you're at?\nUp above the world you fly,\nLike a tea-tray in the sky.\n)x\";\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T22:35:02.653", "Id": "463392", "Score": "2", "body": "counter nitpick: don't use `namespace std`. That's 2 statements, not one. And it looks messy. IMHO. ;-) Indentation is totally broken if you used that in a class or nested block." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T04:46:06.830", "Id": "463415", "Score": "0", "body": "Thank you very much good people. I have just started learning so my apologies that it looks like a dog's breakfast." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T05:10:10.270", "Id": "463417", "Score": "0", "body": "Hi, i am trying to mark/upvote both answers as very useful but it won't let me. What have i done wrong because both answers are correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T05:16:23.420", "Id": "463418", "Score": "0", "body": "@Megadon.cyber You can upvote both, but not accept both I think. Don't sweat it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T09:17:19.250", "Id": "463434", "Score": "3", "body": "I generally advise against multi-lines raw string literals because they mess up with indentation. The parser doesn't care, but the human reader does." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T22:27:41.157", "Id": "236438", "ParentId": "236434", "Score": "2" } } ]
{ "AcceptedAnswerId": "236437", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T21:14:29.147", "Id": "236434", "Score": "4", "Tags": [ "c++" ], "Title": "Exercise 1_2 multiple console outputs. I would like to reduce the number of console output statements" }
236434
<p>I'd like feedback on my solution to the outlined programming challenge (medium level). I've tried it fast in any way I know how to, but, what might be a more efficient and/or pythonic solution?</p> <blockquote> <p>[Letter Count II] Have the function LetterCount(str) take the str parameter being passed and return the first word with the greatest number of repeated letters. For example: "Today, is the greatest day ever!" should return greatest because it has 2 e's (and 2 t's) and it comes before ever which also has 2 e's. If there are no words with repeating letters return -1. Words will be separated by spaces.</p> </blockquote> <pre><code>import doctest import logging import timeit from collections import Counter from string import ascii_letters def letter_count(s: str): """Return the word in s with the largest number of repeating letters &gt;&gt;&gt; letter_count(s="Today, is the greatest day ever!") 'greatest' &gt;&gt;&gt; letter_count(s="!!!Today, is the &gt;&gt;&gt;&gt;greatest day ever!") 'greatest' &gt;&gt;&gt; letter_count(s="!!!Today, is the greatest &gt;&gt;&gt;&gt; day ever!") 'greatest' &gt;&gt;&gt; letter_count(s="!!!Today, is the greatest &gt;&gt;&gt;&gt; day ever xx!") 'greatest' &gt;&gt;&gt; letter_count(s="") -1 &gt;&gt;&gt; letter_count(s="abcd efg hijk") -1 """ if s == "": return -1 word_counters = dict((word, Counter(word)) for word in s.split(" ")) # tuple of (word(str), most common letter frequency(int)) most_repeating_word = ("", 0) for word, counter in word_counters.items(): # most_common format = (letter(str), freq(int)) for most_common in counter.most_common(): if most_common[0] not in ascii_letters: continue if most_common[1] &gt; most_repeating_word[1]: most_repeating_word = (word, most_common[1]) break if most_repeating_word[1] &lt;= 1: return -1 return "".join(l for l in most_repeating_word[0] if l in ascii_letters) if __name__ == "__main__": doctest.testmod() print(timeit.timeit("letter_count(s='!!!Today, is the greatest &gt;&gt;&gt;&gt; day ever!')", setup=("from __main__ import letter_count; from collections " "import Counter; from string import ascii_letters"), number=10000)) </code></pre>
[]
[ { "body": "<p>The core problem can be solved a lot quicker using the built-in <code>max</code> and making a generator that produces the maximum count of repeated letters. Note that <code>max</code> already takes the first occurrence of the maximum, as required by the challenge, but we need to take care to not compare the words lexicographically, as I did in a previous version, by using a <code>key</code> function. You should probably add testcases for this, such as <code>\"free greatest\" -&gt; \"free\"</code> and <code>\"greatest free\" -&gt; \"greatest\"</code>.</p>\n\n<pre><code>from collections import Counter\nfrom operator import itemgetter\n\ndef letter_count(s):\n words = s.split(\" \")\n most_common_letters = (Counter(word).most_common(1)[0][1] for word in words)\n return max(zip(most_common_letters, words), key=itemgetter(0))[1]\n</code></pre>\n\n<p>This does not handle any of the edge cases, though. It fails if the most common letter is not an ASCII character, but we can easily get around this by removing all of those right at the start. I also added your check against the empty string, but improving it to exit early if there is nothing left after filtering for ASCII characters, including the case that only spaces are left. I also split on all whitespace, not just single spaces, because this way multiple spaces are joined and all other whitespace characters have already been removed. I also use <code>if not s</code> instead of <code>if s == \"\"</code>, because empty sequences are falsey and it sounds more like English this way.</p>\n\n<pre><code>from collections import Counter\nfrom string import ascii_letters\nfrom operator import itemgetter\n\nASCII_LETTERS = set(ascii_letters) | {\" \"}\n\ndef letter_count(s: str):\n \"\"\"Return the word in s with the largest number of repeating letters\n\n\n &gt;&gt;&gt; letter_count(s=\"Today, is the greatest day ever!\")\n 'greatest'\n &gt;&gt;&gt; letter_count(s=\"!!!Today, is the &gt;&gt;&gt;&gt;greatest day ever!\")\n 'greatest'\n &gt;&gt;&gt; letter_count(s=\"!!!Today, is the greatest &gt;&gt;&gt;&gt; day ever!\")\n 'greatest'\n &gt;&gt;&gt; letter_count(s=\"!!!Today, is the greatest &gt;&gt;&gt;&gt; day ever xx!\")\n 'greatest'\n &gt;&gt;&gt; letter_count(s=\"Today, is thee greatest day ever!\")\n 'thee'\n &gt;&gt;&gt; letter_count(s=\"!!! &gt;&gt;&gt;&gt;\")\n -1\n &gt;&gt;&gt; letter_count(s=\"\")\n -1\n &gt;&gt;&gt; letter_count(s=\"abcd efg hijk\")\n -1\n \"\"\"\n s = \"\".join(c for c in s if c in ASCII_LETTERS)\n if not s.replace(\" \", \"\"):\n return -1\n words = s.split()\n most_common_letters = (Counter(word).most_common(1)[0][1] for word in words)\n best_word = max(zip(most_common_letters, words), key=itemgetter(0))\n return best_word[1] if best_word[0] &gt; 1 else -1\n</code></pre>\n\n<p>Note that the challenge design is not the best. Normally I would recommend against returning differing types from a function unless absolutely necessary. Having it return a string in most cases and sometimes an int can be dangerous. Better to at least return <code>None</code>, if you absolutely need a special value, or even better, just let the caller deal with an exception.</p>\n\n<p>Otherwise your code looks quite alright. You have a docstring, tests and a main guard. I must say that your comments don't help me a lot, I personally prefer plain English or, even better, self-explanatory variable names. But naming things is hard, and you have already done a good enough job at that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T10:57:01.593", "Id": "236463", "ParentId": "236435", "Score": "5" } } ]
{ "AcceptedAnswerId": "236463", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T21:54:13.660", "Id": "236435", "Score": "3", "Tags": [ "python", "python-3.x", "programming-challenge", "strings" ], "Title": "Find and return the earliest occurring word from a string which contains the most repeating letters" }
236435
<p><a href="https://jsfiddle.net/0a7tcv2g/" rel="nofollow noreferrer">https://jsfiddle.net/0a7tcv2g/</a></p> <p>I know I could locally store the data, write in es6, and all that, but I wanted to learn to work with APIs, and really understand JS through ES5, before brushing up my ES6+ skills. I haven't finished adding all the small details yet, but thats trivial at this point. Just looking for feedback on my JS, and responsiveness of my site. (I know I used some es6, and could use const in some places instead of let).</p> <p>HTML:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Pokedex&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="styles.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;h1 id="main-header"&gt;Pokedex&lt;/h1&gt; &lt;div id="main-container"&gt; &lt;/div&gt; &lt;script src="index.js" type="text/javascript"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>CSS:</p> <pre><code>*{ font-family: Arial, Helvetica, San-serrif; margin:0; padding: 0; } h1 { background: red; color: white; font-size: 3em; text-align: center; } #main-container { position: absolute; display: flex; flex-wrap: wrap; perspective: 625em; } .card-container { position: relative; display: flex; transform-style: preserve-3d; flex-wrap: wrap; justify-content: center; align-content: center; flex-basis: 31%; height: 25em; width:18.75em; box-shadow: 0.07em 0.07em 0.4em 0.13em rgb(40, 40, 40, 0.6); margin: 0.4em; transition: 1000ms; background: #0000ff; border: 0.63em solid gold; } .frontFace, .backFace { display: flex; flex-wrap: wrap; flex-basis: 31%; position: absolute; height: 100%; width: 100%; backface-visibility: hidden; color: white; /*Temporary*/ text-shadow: -0.13em 0 red, 0 0.13em red, 0.13em 0 red, 0 -0.13em red; } .backFace { transform: rotateY(180deg); height: 100% width: 100%; } .frontFace img, .backFace img { position: absolute; margin-top: 18%; margin-left: 20%; background: white; border: gold 0.19em solid; width: 60%; height: auto; } .name{ width: 100%; text-align: center; font-size: 1.5em; overflow:auto; } .frontName { font-size: 1.5em; text-align: center; margin-top: 2%; width: 100%; max-width: 100%; } .type { margin-top: 70%; margin-left: 66%; } .id { position: absolute; margin-left: 4%; margin-top: 4%; height: auto; } </code></pre> <p>JS:</p> <pre><code>const container = document.getElementById('main-container'); function getPokemon(callback) { const xhr = new XMLHttpRequest(); const url = 'https://pokeapi.co/api/v2/pokemon/'; xhr.onload = function() { if(xhr.status === 200) { const pokemon = JSON.parse(xhr.responseText); pokemon.results.forEach((poke, index)=&gt;{ let cardContainer = document.createElement('div'); cardContainer.className = 'card-container'; container.appendChild(cardContainer); let frontFace = document.createElement('div'); frontFace.className = 'frontFace'; cardContainer.appendChild(frontFace); let sprite = document.createElement('img') sprite.src = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${(index + 1).toString()}.png` frontFace.appendChild(sprite); let backName = document.createElement('h4'); backName.className = 'name'; function capitalName(string) { backName.innerText = string.charAt(0).toUpperCase() + string.slice(1); } capitalName(poke.name) frontFace.appendChild(backName); }) callback(); } } xhr.open('GET', url, true); xhr.send(); } function cardBack() { const endPoint = this.innerText.charAt(0).toLowerCase() + this.innerText.slice(1); const card = this.parentElement; const xhr = new XMLHttpRequest(); xhr.onload = function() { if(xhr.status === 200) { if(card.childNodes.length === 2) { card.style.transform = 'rotateY(180deg)'; } else { const details = JSON.parse(xhr.responseText); let backFace = document.createElement('div'); backFace.className = 'backFace'; backFace.addEventListener('click', ()=&gt;{ card.style.transform = '' }) card.appendChild(backFace); let sprite = document.createElement('img') sprite.src = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${(details.id).toString()}.png` backFace.appendChild(sprite); let name = document.createElement('h4'); name.className = 'frontName'; name.innerHTML = details.name; let type = document.createElement('h4'); type.className = 'type'; type.innerHTML = details.types[0].type.name; backFace.appendChild(name); backFace.appendChild(type); let ids = document.createElement('h4'); ids.className = 'id'; ids.innerHTML = `#${details.id}`; backFace.appendChild(ids); card.style.transform = 'rotateY(180deg)'; } } } xhr.open('GET', 'https://pokeapi.co/api/v2/pokemon/' + endPoint, true); xhr.send(); } getPokemon(()=&gt;{ const cardFront = document.querySelectorAll('.frontFace'); cardFront.forEach((card)=&gt; { card.addEventListener('click', cardBack); }) }); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T22:00:45.900", "Id": "236436", "Score": "2", "Tags": [ "javascript", "css", "api" ], "Title": "Pokedex that displays flip cards" }
236436
<p>This is my first go at Django, so I'm looking first to learn how to make this more idiomatic. Also, is there a better way to set up my tests? To my HTTP status codes make sense?</p> <p><strong>chores/tests.py</strong></p> <pre class="lang-py prettyprint-override"><code>import datetime import json from django.test import TestCase, Client from django.urls import reverse from rest_framework import status from .models import Chore class ChoreTest(TestCase): def test_update(self): chore = Chore(name='sweep', period=7, due=datetime.date.today()) chore.update() self.assertEqual(chore.due, datetime.date.today() + datetime.timedelta(days=7)) def test_update_overdue_chore(self): chore = Chore(name='sweep', period=7, due=datetime.date.today() - datetime.timedelta(days=1)) chore.update() self.assertEqual(chore.due, datetime.date.today() + datetime.timedelta(days=7)) class TestChoresView(TestCase): def setUp(self) -&gt; None: Chore.objects.create(name='sweep', period=7, due=datetime.date.today()) Chore.objects.create(name='wipe', period=3, due=datetime.date.today() + datetime.timedelta(days=1)) self.client = Client() def test_get_all_chores(self): response = self.client.get(reverse('all')) response_content = json.loads(response.content) self.assertEqual(2, len(response_content)) all_names = [chore['name'] for chore in response_content] self.assertIn('sweep', all_names) self.assertIn('wipe', all_names) def test_chores_correctly_serialized(self): response = self.client.get(reverse('all')) response_content = json.loads(response.content) expected_keys = ('name', 'period', 'due', 'id') for key in expected_keys: self.assertIn(key, response_content[0].keys()) self.assertIn(key, response_content[1].keys()) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_update_chore(self): chore = Chore.objects.get(name='sweep') response = self.client.generic('POST', reverse('update'), json.dumps({'id': chore.pk})) chore = Chore.objects.get(name='sweep') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(chore.due, datetime.date.today() + datetime.timedelta(days=chore.period)) def test_update_invalid_chore(self): response = self.client.generic('POST', reverse('update'), json.dumps({'id': 1337})) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_get_due_chores(self): response = self.client.get(reverse('due')) response_content = json.loads(response.content) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(1, len(response_content)) self.assertEqual(response_content[0]['name'], 'sweep') def test_get_no_chores_due(self): # Start by updating all chores, so none will be due chores = Chore.objects.all() for chore in chores: chore.update() response = self.client.get(reverse('due')) response_content = json.loads(response.content) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(1, len(response_content)) </code></pre> <p><strong>chores/views.py</strong></p> <pre class="lang-py prettyprint-override"><code>import datetime import json from django.shortcuts import render from django.views.decorators.csrf import ensure_csrf_cookie from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Chore from .serializers import ChoreSerializer @ensure_csrf_cookie def index(request): return render(request, 'chores/index.html') @ensure_csrf_cookie @api_view(['GET']) def chores(request): all_chores = Chore.objects.all() serializer = ChoreSerializer(all_chores, many=True) return Response(serializer.data) @ensure_csrf_cookie @api_view(['POST']) def update_chore(request): content = json.loads(request.body) chore_id = content['id'] try: chore = Chore.objects.get(pk=chore_id) except Chore.DoesNotExist: return Response(status=status.HTTP_400_BAD_REQUEST) chore.update() chore.save() return Response(status=status.HTTP_200_OK) @api_view(['GET']) def due_chores(request): today = datetime.date.today() all_chores = Chore.objects.filter(due__lte=today) serializer = ChoreSerializer(all_chores, many=True) return Response(serializer.data) </code></pre> <p><strong>chores/models.py</strong></p> <pre class="lang-py prettyprint-override"><code>import datetime from django.db import models class Chore(models.Model): name = models.CharField(max_length=100) # Number of days in between instances of scheduled chore period = models.IntegerField() # Due date of chore due = models.DateField() def __str__(self): return self.name def update(self) -&gt; None: """ Mark a chore as complete by updating the due date. :return: None """ self.due = datetime.date.today() + datetime.timedelta(days=self.period) </code></pre>
[]
[ { "body": "<p>Some suggestions:</p>\n\n<ol>\n<li><code>Chore</code>'s <code>period</code> field should probably be <code>period_days</code> to avoid the comment.</li>\n<li>The comment on <code>update</code> makes it look like it should be called <code>mark_complete</code> or something, so that you can remove the comment. In any case I would expect the <em>view</em> rather than the model to do that update.</li>\n<li>It is customary to use a <code>ModelViewSet</code> to encapsulate the sort of functions you have in views.py.</li>\n<li><code>Chore.DoesNotExist</code> should result in a HTTP 404 response code, which is the default. No need for custom code. In general, letting DRF decide the response code is much easier.</li>\n<li>The test classes have inconsistent naming.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T23:08:55.350", "Id": "236441", "ParentId": "236440", "Score": "2" } } ]
{ "AcceptedAnswerId": "236441", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T22:48:23.310", "Id": "236440", "Score": "2", "Tags": [ "python", "django", "rest" ], "Title": "Backend for chore management app" }
236440
<p><strong>Background</strong><br> I was looking for a simple <code>Event Broker</code> or <code>EventBus</code> (whatever else keyword you can come up with) to use in a small(-ish) WinForms application. In Java I was using <code>org.greenrobot.EventBus</code> for a long time, but couldn't find a comparably established and <em>simple</em> solution in C# - everything looks to be enterprise grade. <code>Rebus</code> with in-memory transport seemed very promising, but it lacked unsubscription capabilities (I asked the author in <a href="https://stackoverflow.com/questions/59964763/rebus-how-to-register-an-instance-of-a-handler">this question's followup comments</a>). </p> <p>So here's my first attempt to roll my own.</p> <p><em>If you know of a good solution that worked for you - please post it!</em></p> <p><strong>Question</strong>: Does this implementation have some critical flaws?</p> <p><strong>Some facts that I think are true about it:</strong></p> <ol> <li>All listeners are notified on the same thread that published the event, so it's up to listeners to run tasks on correct threads.</li> <li>You subscribe <code>Delegates</code>, so you can sub a static method, if need be.</li> <li>Fast sub/unsub (should be O(1)), so it's ok to have tens of thousands of listeners for UI purposes.</li> <li>As all sub/unsub/maintenance operations are synchronized (on the same object) it probably can't be too fast overall.</li> </ol> <p>Point [1] is likely a problem. Not sure how to do it best.</p> <p><strong>Code</strong></p> <pre><code>using System; using System.Collections.Generic; using System.Reflection; namespace DmtAvt.Bus { public class MiniBus : IDisposable { readonly object _lock = new object(); readonly Dictionary&lt;Type, LinkedList&lt;MiniSub&gt;&gt; _subscriptions = new Dictionary&lt;Type, LinkedList&lt;MiniSub&gt;&gt;(); readonly List&lt;MiniSub&gt; _recycling = new List&lt;MiniSub&gt;(); public static readonly MiniBus Default = new MiniBus(); public delegate void On&lt;in T&gt;(T asd); public MiniSub Sub&lt;T&gt;(On&lt;T&gt; d) { if (d.Method.IsAbstract || d.Method.IsGenericMethod) throw new ArgumentException("No generics or abstract methods"); if (typeof(void) != d.Method.ReturnType) throw new ArgumentException("Registered delegates must have return type 'void'"); ParameterInfo[] pis = d.Method.GetParameters(); if (pis.Length != 1) throw new ArgumentException("Registered delegates must have exactly 1 parameter"); Type messageType = pis[0].ParameterType; lock (_lock) { if (!_subscriptions.TryGetValue(messageType, out var forType)) { forType = new LinkedList&lt;MiniSub&gt;(); _subscriptions.Add(messageType, forType); } var sub = new MiniSub(this, messageType, d); var node = new LinkedListNode&lt;MiniSub&gt;(sub); sub._listNode.SetTarget(node); forType.AddLast(node); return sub; } } public void UnSub(MiniSub sub) { lock (_lock) { if (_subscriptions.TryGetValue(sub._type, out var list)) { if (sub._listNode.TryGetTarget(out var node)) { try { list.Remove(node); } catch (Exception) { // It's ok if the node is already gone or some other unexpected // circumstances happened, like the list itself is already gone, etc. } } } } } public void Pub(object message) { var type = message.GetType(); _subscriptions.TryGetValue(type, out var subs); if (subs == null) return; // no one is subscribed to this topic foreach (var sub in subs) { if (!sub.TryHandleMessage(message)) { _recycling.Add(sub); } } if (_recycling.Count &gt; 0) { Maintenance(); } } protected void Maintenance() { lock (_lock) { foreach (var l in _recycling) { UnSub(l); } _recycling.Clear(); } } public void Dispose() { lock (_lock) { foreach (var kv in _subscriptions) { foreach (var sub in kv.Value) { sub._bus.SetTarget(null); sub._listNode.SetTarget(null); } } _subscriptions.Clear(); _recycling.Clear(); } } } public class MiniSub : IDisposable { internal readonly WeakReference&lt;MiniBus&gt; _bus; internal readonly Type _type; internal readonly WeakReference&lt;LinkedListNode&lt;MiniSub&gt;&gt; _listNode; public readonly WeakReference&lt;Delegate&gt; _delegate; internal MiniSub(MiniBus bus, Type type, Delegate del) { _bus = new WeakReference&lt;MiniBus&gt;(bus); _type = type; _listNode = new WeakReference&lt;LinkedListNode&lt;MiniSub&gt;&gt;(null); _delegate = new WeakReference&lt;Delegate&gt;(del); } internal bool TryHandleMessage(object o) { if (_delegate.TryGetTarget(out var d)) { d.DynamicInvoke(o); return true; } return false; } public void UnSub() { Dispose(); } public void Dispose() { if (_bus.TryGetTarget(out var b)) { b.UnSub(this); } } } } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T23:10:36.417", "Id": "236442", "Score": "3", "Tags": [ "c#", "event-handling" ], "Title": "Simple event broker / eventbus in C# (~100 lines of code)" }
236442
<p>Inspired by <a href="https://codereview.stackexchange.com/questions/155834/wrapping-indexdb-with-rxjs">Wrapping IndexDB with RxJs</a>.</p> <p>(Edit - Added a <a href="https://stackblitz.com/edit/angular-caupm5" rel="nofollow noreferrer">Stackblitz</a> example).</p> <p>My use case is a simple, on-disk temporary cache. No errors are propagated, <code>null</code> values are returned instead. All errors are logged. </p> <pre><code>import { Injectable } from '@angular/core'; import { Observable, Observer, ReplaySubject, Subject } from 'rxjs'; import { take, filter } from 'rxjs/operators'; const VERSION = 1; interface Record { key: string; value: any; ttl: number; timestamp: number; } type RecordInput = Omit&lt;Record, 'timestamp'&gt;; @Injectable({ providedIn: 'root', }) export class IndexedDbService { db = new ReplaySubject&lt;IDBDatabase | null&gt;(1); $db = this.db.pipe(take(1), filter(db =&gt; !!db)); constructor() { const onError = error =&gt; { console.log(error); this.db.complete(); }; if (!window.indexedDB) { onError('IndexedDB not available'); } else { const openRequest = indexedDB.open('myapp', VERSION); openRequest.onerror = () =&gt; onError(openRequest.error); openRequest.onsuccess = () =&gt; this.db.next(openRequest.result); openRequest.onupgradeneeded = () =&gt; { try { const db: IDBDatabase = openRequest.result; const cacheStore = db.createObjectStore('store', { keyPath: 'key' }); cacheStore.createIndex('value', 'value'); cacheStore.createIndex('timestamp', 'timestamp'); cacheStore.createIndex('ttl', 'ttl'); } catch (error) { onError(error); } }; } } get(storeName: string, key: string): Observable&lt;Record | null&gt; { return Observable.create((observer: Observer&lt;Record&gt;) =&gt; { const onError = error =&gt; { console.log(error); observer.complete(); }; this.$db.subscribe(db =&gt; { try { const txn = db.transaction([storeName], 'readonly'); const store = txn.objectStore(storeName); const getRequest: IDBRequest&lt;Record&gt; = store.get(key); getRequest.onerror = () =&gt; onError(getRequest.error); getRequest.onsuccess = () =&gt; { const record = getRequest.result; if (!record || new Date(Date.now() - record.timestamp).getSeconds() &gt; record.ttl ) { observer.next(null); } else { observer.next(getRequest.result); } observer.complete(); }; } catch (err) { onError(err); } }); }); } put(storeName: string, value: RecordInput): Observable&lt;IDBValidKey | null&gt; { return Observable.create((observer: Observer&lt;IDBValidKey&gt;) =&gt; { const onError = error =&gt; { console.log(error); observer.complete(); }; this.$db.subscribe(db =&gt; { try { const txn = db.transaction([storeName], 'readwrite'); const store = txn.objectStore(storeName); const record: Record = {...value, timestamp: Date.now()}; const putRequest = store.put(record); putRequest.onerror = () =&gt; onError(putRequest.error); putRequest.onsuccess = () =&gt; { observer.next(putRequest.result); observer.complete(); }; } catch (err) { onError(err); } }); }); } clear(storeName: string) { return Observable.create((observer: Observer&lt;void&gt;) =&gt; { this.$db.subscribe(db =&gt; { try { db.transaction([storeName], 'readwrite').objectStore(storeName).clear(); } catch (error) { console.log(error); } observer.complete(); }); }); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T23:28:22.193", "Id": "236444", "Score": "5", "Tags": [ "angular-2+", "rxjs", "indexeddb" ], "Title": "IndexDB (RxJs) - Angular Service" }
236444
<p>I'm creating a simple registration form for a Linux installation party I'm organizing.</p> <p>Although I'm a decent programmer, I rarely create HTML files. I want to know if this form is safe for my users and if it will work on most devices. Am I following all the good web development practices? Is my code pure HTML5?</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="description" content="Installation fest inscription form"&gt; &lt;meta name="author" content="name - email@example.com"&gt; &lt;title&gt;Installfest Inscription&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Installfest Inscription&lt;/h1&gt; &lt;form action="/action_page" method="post"&gt; First name:&lt;br&gt; &lt;input type="text" name="firstname"&gt;&lt;br&gt; Last name:&lt;br&gt; &lt;input type="text" name="lastname"&gt; Laptop model:&lt;br&gt; &lt;input type="text" name="model"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Thanks!</p>
[]
[ { "body": "<blockquote>\n <p>I wanted to know if this form is safe for my users and if it will work on most devices.</p>\n</blockquote>\n\n<p>Your HTML form will definitely work on all devices. But as for being 'safe for users', that would probably depend on your backend code you are using to submit your form eg PHP. You would use PHP (or some other backend language eg Python) to handle the submitted data. The browser would decide if the form is safe enough based on how safely and securely you encrypt and submit the data.</p>\n\n<blockquote>\n <p>Am I following all the good web development practices?</p>\n</blockquote>\n\n<p>You have followed most of the good programming practices for web development. Though there aren't many things I can improve on for such a simple webpage, there are some minor problems:</p>\n\n<ul>\n<li>It is more conventional to use <code>&lt;br /&gt;</code> not <code>&lt;br&gt;</code> because it is a self-closing tag. Adding the <code>/</code> in the tag tells the browser not to waste time looking for the (non-existent) closing <code>&lt;/br&gt;</code> tag.</li>\n<li>And it is not a good idea to place your input labels as 'naked' untagged text. Instead, use <code>label</code> tags:</li>\n</ul>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;label for=\"firstname\"&gt;Firstname:&lt;/label&gt;\n&lt;input type=\"text\" name=\"firstname\" /&gt;\n</code></pre>\n\n<ul>\n<li>Web developers usually write the <code>doctype</code> in lowercase, like this:</li>\n</ul>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;!doctype html&gt;\n</code></pre>\n\n<p>not this:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;!DOCTYPE HTML&gt;\n</code></pre>\n\n<p>But there is no major difference.</p>\n\n<blockquote>\n <p>Is my code pure HTML5?</p>\n</blockquote>\n\n<p>This is all pure HTML5, I see no other programming language (eg JS) or markup language (eg CSS) in your sample code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T14:34:43.230", "Id": "463553", "Score": "1", "body": "W3C recommends `<!DOCTYPE html>`. [HTML doctype declaration](https://www.w3schools.com/tags/tag_doctype.asp)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-05T11:09:11.733", "Id": "464002", "Score": "0", "body": "In HTML 5 it's completely irrelevant if you use `<br>` or `<br />`. The browser doesn't go looking for a closing `</br>`, because It knows which elements are supposed to be empty." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T11:39:07.803", "Id": "236495", "ParentId": "236447", "Score": "4" } }, { "body": "<p>It would help Google and other crawlers if the <code>&lt;head&gt;</code> also included:</p>\n\n<pre><code>&lt;link rel=\"canonical\" href=\"https://appropriate/url\" /&gt;\n&lt;meta name=\"description\"\n content=\"Brief description that will appear in Google search results.\" /&gt;\n</code></pre>\n\n<hr>\n\n<p>In terms of coding style, using <code>&lt;br&gt;</code> (which should be <code>&lt;br /&gt;</code>), isn't pretty.\nIt also indicates that you are thinking of display format while writing HTML.\nHTML code is for saying what things <em>are</em>, not how they should be displayed.</p>\n\n<hr>\n\n<p>For labelled input, one should use the <code>&lt;label&gt;</code> tag to definitively associate the label with the input area.\nThis will help software that reads your page, whether for SEO, or for accessibility For someone that can't see well, voice software can know for sure what the input field's label is, whereas with your original code it would have to guess.</p>\n\n<p>There are two common ways of doing this.</p>\n\n<p>By putting the input tag inside the label:</p>\n\n<pre><code>&lt;label&gt;\n Firstname: &lt;input type=\"text\" name=\"firstname\" /&gt;\n&lt;/label&gt;\n...\n</code></pre>\n\n<p>or by listing the labels and inputs separately:</p>\n\n<pre><code>&lt;label for=\"firstname\"&gt;Firstname:&lt;/label&gt;\n...\n\n&lt;input type=\"text\" name=\"firstname\" /&gt;\n...\n</code></pre>\n\n<p>The results are the same, so use whichever feels most appropriate for your code.\nEither way though, do not include anything other than the label text (e.g. don't add an <code>&lt;a&gt;</code> link inside the <code>&lt;label&gt;</code>).</p>\n\n<p>Finally, if you don't like the default formatting that this produces, use CSS in the <code>&lt;head&gt;&lt;style&gt;</code> section to improve the appearance.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T15:00:18.983", "Id": "236498", "ParentId": "236447", "Score": "4" } } ]
{ "AcceptedAnswerId": "236495", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-30T23:54:34.837", "Id": "236447", "Score": "5", "Tags": [ "html", "html5" ], "Title": "Simple HTML5 registration form" }
236447
<p>I have a common style (<code>common.scss</code>) and a text direction (RTL, LTR) option file (<code>option-document-direction-rtl.scss</code>, <code>option-document-direction-ltr.scss</code>). And by switching the reading of these files, the css file with RTL / LTR changed is output by method like gulp.js.</p> <p><strong>_common.scss</strong></p> <pre><code>body { max-width: 1120px; background-color: black; color: white; text-align: $direction; } </code></pre> <p><strong>_option-document-direction-rtl.scss</strong></p> <pre><code>$direction: right; </code></pre> <p><strong>_option-document-direction-ltr.scss</strong></p> <pre><code>$direction: left; </code></pre> <p><strong>style.scss</strong></p> <pre><code>@import "option-document-direction-rtl"; // switch to @import "option-document-direction-rtl"; @import "common.scss" </code></pre> <p>And I can get below <em>two css files same time</em> by some method (actually these scss files style be more complex):</p> <p><strong>rtl-style.css</strong></p> <pre><code>body { max-width: 1120px; background-color: black; color: white; text-align: right; } </code></pre> <p><strong>ltr-style.css</strong></p> <pre><code>body { max-width: 1120px; background-color: black; color: white; text-align: left; } </code></pre> <hr> <h3>Main subject</h3> <p>So, I have to switched these style condition different from text direction. For example, screen size without media queries. In this case, I think need a new options SCSS file, such as <code>_computer.scss</code> and <code>_smartphone.scss</code>. Here, I had a question.</p> <p>The number of configuration files with new conditions may increase in the future. In the current method, in short, the css file to be output is changed depending on which of the "configuration files that describe the settings used in each condition" is read.</p> <p>I'm afraid that my configuration files will grow and become more difficult to manage. What tools and mechanisms on SCSS can be used to increase the scalability of many configuration files?</p> <p>I considered a method of dynamically changing the output file according to the argument at the time of build, but I have not been able to determine whether this is a way to improve scalability.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T01:29:28.987", "Id": "236450", "Score": "2", "Tags": [ "javascript", "css", "sass", "gulp.js" ], "Title": "How to increase scalability the method that output each file while switching multiple many conditions?" }
236450
<p>I was tasked to write process that initially seemed like a straight forward thing. "Fetch data from database, create a cache object, and assign this data to it. Use existing class to model this after." That's it in a nutshell. The 'existing' class did not do any caching, just an async call across layers to the database. The purpose the async method is prevent the app from waiting for this data to load. I should mention this is custom app that run as a plug-in to the MS Excel (Don't ask!), and so it's a WPF app. As such, caching of larger data is done with a use of Dictionaries rather than using System.Runtime.Caching library. Originally I used a dictionary like this: <code>public async Task&lt;Dictionary&lt;projectId, ProjectFeatureIndicatorMetadata&gt;&gt; GetProjectFeatureIndicatorsStatusAsync(Guid projectId)</code> but the tech lead decided not to use a Dictionary due unnecessary memory usage.</p> <p>So what I'm looking to gain from this post is constructive comments to see if this is overkill, can it be simplified, or improved, etc. Bottom line is, code works I just want to see if it can be improved. If you decide to down vote it, I would ask to leave comment as to why.</p> <p>Doing to start with the data layer. So here the <code>ReaderAsync</code> reads the data set and assigns it to the ProjectFeatureIndicatorMetadata class:</p> <pre><code>public async Task&lt;ProjectFeatureIndicatorMetadata&gt; GetProjectFeatureIndicatorsStatusAsync(Guid projectId) { ProjectFeatureIndicatorMetadata result = null; await GetSpHelper().ExecuteReaderAsync( cancellationToken: CancellationToken.None, spName: "ITV.usp_ProjectFeatureIndicators_GetByProjectId", parmsDg: parms =&gt; { parms.AddWithValue("@ProjectId:", projectId); }, methodDg: async (reader, ct) =&gt; { while (await reader.ReadAsync(ct)) { result = new ProjectFeatureIndicatorMetadata( Convert.ToBoolean(reader["SprcIncludesInd"]), Convert.ToBoolean(reader["SprcVariablesInd"]), Convert.ToBoolean(reader["SprcFlowInd"]), Convert.ToBoolean(reader["SprcGenerationInd"])); } return true; }); return result; } </code></pre> <p>Then I have the this code in one of the business layers. I only included pertinent code:</p> <pre><code>public class ItvCacheFeatureFlagManager : IitvCacheFeatureFlagManager { public static ProjectFeatureIndicatorMetadata _featureIndicatorFlagCache = new ProjectFeatureIndicatorMetadata(true,true,true,true); public virtual async Task&lt;ProjectFeatureIndicatorMetadata&gt; GetProjectFeatureIndicatorMetadata(Guid projectId) { using (new WriteLock(_lock)) { if (_featureIndicatorFlagCache != null) { return _featureIndicatorFlagCache; } else { var dbresult = await GetProjectFeatureIndicatorsStatusAsync(projectId); return dbresult; } } } } </code></pre> <p>The type <code>ProjectFeatureIndicatorMetadata</code> is like model class and this is where I was not certain if I even need this:</p> <pre><code>public class ProjectFeatureIndicatorMetadata { public ProjectFeatureIndicatorMetadata( bool SprcIncludesInd, bool sprcVariablesInd, bool sprcFlowInd, bool sprcGenerationInd) { SprcIncludesInd = sprcIncludesInd; SprcVariablesInd = sprcVariablesInd; SprcFlowInd = sprcFlowInd; SprcGenerationInd = sprcGenerationInd; } public bool SprcIncludesInd { get; set; } public bool SprcVariablesInd { get; set; } public bool SprcFlowInd { get; set; } public bool SprcGenerationInd { get; set; } } </code></pre> <p>Update: I refactored some of the code and included some of the startup code as it was suggested below.</p> <pre><code> //Staring class: public class ClientUserInterface : IClientUserInterface { [NotNull] private ProjectData Data { [Pure, DebuggerStepThrough] get { return ProjectDataProvider.ProjectData; } } private void OpenPublisher(ProjectIdentifier project) { Task.Run(async () =&gt; await Data.GetProjectFeatureIndicatorMetadata(project)); } } public class ProjectData : DependencyObject, INotifyPropertyChanged, IDisposable { // the green squidgy under _featureManger says "Field 'ProjectData._featureManger' // is never assigned to, and will have its default value null private readonly IitvCacheFeatureFlagManager _featureManger; public async Task&lt;ProjectFeatureIndicatorMetadata&gt; GetProjectFeatureIndicatorMetadata(ProjectIdentifier projectId) { return await _featureManger.GetProjectFeatureIndicatorMetadata(projectId); } } public interface IitvCacheFeatureFlagManager { Task&lt;ProjectFeatureIndicatorMetadata&gt; GetProjectFeatureIndicatorMetadata(Guid projectId); } public class ItvCacheFeatureFlagManager : IitvCacheFeatureFlagManager { private readonly ItvCacheFeatureFlagProvider _provider; private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); public static ProjectFeatureIndicatorMetadata _featureIndicatorFlagCache = new ProjectFeatureIndicatorMetadata(); public ItvCacheFeatureFlagManager( SqlConnectionFactory connectionFactory ) { _provider = new ItvCacheFeatureFlagProvider(connectionFactory); } public virtual async Task&lt;ProjectFeatureIndicatorMetadata&gt; GetProjectFeatureIndicatorMetadata(Guid projectId) { using (new WriteLock(_lock)) { if (_featureIndicatorFlagCache != null) { return _featureIndicatorFlagCache; } else { var dbresult = await GetProjectFeatureIndicatorsStatusAsync(projectId); return dbresult; } } } public virtual async Task&lt;ProjectFeatureIndicatorMetadata&gt; GetProjectFeatureIndicatorsStatusAsync(Guid projectId) { var dbresult = await _provider.GetProjectFeatureIndicatorsStatusAsync(projectId); return dbresult; } } public class ItvCacheFeatureFlagProvider : IitvCacheFeatureFlagProvider { private SqlConnectionFactory ConnectionFactory { get; } private SqlSpHelper GetSpHelper() =&gt; new SqlSpHelper(ConnectionFactory); public ItvCacheFeatureFlagProvider(SqlConnectionFactory connectionFactory) { ConnectionFactory = connectionFactory; } public async Task&lt;ProjectFeatureIndicatorMetadata&gt; GetProjectFeatureIndicatorsStatusAsync(Guid projectId) { ProjectFeatureIndicatorMetadata result = null; await GetSpHelper().ExecuteReaderAsync( cancellationToken: CancellationToken.None, spName: "ITV.usp_ProjectFeatureIndicators_GetByProjectId", parmsDg: parms =&gt; { parms.AddWithValue("@ProjectId:", projectId); }, methodDg: async (reader, ct) =&gt; { while (await reader.ReadAsync(ct)) { result.SprcIncludesInd = Convert.ToBoolean(reader["SprcIncludesInd"]); result.SprcVariablesInd = Convert.ToBoolean(reader["SprcVariablesInd"]); result.SprcGenerationInd = Convert.ToBoolean(reader["SprcGenerationInd"]); result.SprcFlowInd = Convert.ToBoolean(reader["SprcFlowInd"]); } return true; }); return result; } } public class ProjectFeatureIndicatorMetadata { public ProjectFeatureIndicatorMetadata() { } public bool? SprcIncludesInd { get; set; } public bool? SprcVariablesInd { get; set; } public bool? SprcFlowInd { get; set; } public bool? SprcGenerationInd { get; set; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T03:49:26.570", "Id": "463578", "Score": "0", "body": "I still have doubts this code works as expected. ClientUserInterface.OpenPublisher calls ProjectData.GetProjectFeatureIndicatorMetadata, this is just a chain command and doesn't do any process, that gets chained to ItvCacheFeatureFlagManager.GetProjectFeatureIndicatorMetadata which checks if _featureIndicatorFlagCache is not null, which it never is null as it set with a default value. So it will *always* return _featureIndicatorFlagCache and never call into GetProjectFeatureIndicatorsStatusAsync" } ]
[ { "body": "<p>Does this code work? The _featureIndicatorFlagCache is set right away and is never cleared out. So the check if it's null will always be false and send back just he default and never execute GetProjectFeatureIndicatorsStatusAsync. </p>\n\n<p>I assume you want to cache the call to GetProjectFeatureIndicatorsStatusAsync but you won't be able to store that in one property unless it's a dictionary as I assume the data it returns is based on projectId. </p>\n\n<p>If you want an example of a simple caching you can use the <code>Lazy&lt;Task&lt;&gt;&gt;</code> in the dictionary. The Lazy will only execute once and return the same task back to all the callers. I would just use the ConcurrentDictionary as not have to deal with the locking myself. </p>\n\n<pre><code>public static ConcurrentDictionary&lt;Guid, Lazy&lt;Task&lt;ProjectFeatureIndicatorMetadata&gt;&gt;&gt; _cache =\n new ConcurrentDictionary&lt;Guid, Lazy&lt;Task&lt;ProjectFeatureIndicatorMetadata&gt;&gt;&gt;();\n</code></pre>\n\n<p>The the cache method would look something like this</p>\n\n<pre><code>public virtual Task&lt;ProjectFeatureIndicatorMetadata&gt; GetProjectFeatureIndicatorMetadata(\n Guid projectId)\n{\n // This is optional just removes any tasks that have been faulted to re-execute \n if (_cache.TryGetValue(projectId, out var result))\n {\n // IsFaulted will be false while task is in flight - this is what we want and don't want to block on it\n if (result.Value.IsFaulted)\n {\n // cast as dictionary to get remove that also checks the value along with the key\n var cacheDictionary = (IDictionary&lt;Guid, Lazy&lt;Task&lt;ProjectFeatureIndicatorMetadata&gt;&gt;&gt;) _cache;\n cacheDictionary.Remove(\n new KeyValuePair&lt;Guid, Lazy&lt;Task&lt;ProjectFeatureIndicatorMetadata&gt;&gt;&gt;(projectId, result));\n result = null;\n }\n }\n\n if (result == null)\n {\n result = _cache.GetOrAdd(projectId, id =&gt; new Lazy&lt;Task&lt;ProjectFeatureIndicatorMetadata&gt;&gt;(GetProjectFeatureIndicatorsStatusAsync(id)));\n }\n\n return result.Value;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T19:06:46.180", "Id": "463485", "Score": "0", "body": "Thanks for your reply! In the start up method I call this method like this: `Task.Run(async () => await FeatureFlagManager.GetProjectFeatureIndicatorMetadata(project));` and checking the cache object like this: `var cacheData = ItvCacheFeatureFlagManager._featureIndicatorFlagCache;` before the call is made, cacheData is null and after it shows my four variable as 'true'.\n\nGetProjectFeatureIndicatorsStatusAsync is important as this where these values come from." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T19:45:20.880", "Id": "463490", "Score": "0", "body": "Again how can you cache to a single property if the data is required by projectId? Is there only ever one project id?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T20:16:05.277", "Id": "463497", "Score": "0", "body": "I timed out as wrote my previous comment. The projectId is not relevant after results are fetched. It just occurred to that I'm over writing the data from the database call when I instantiated the metadata class. That's fixed now. As to your latest comment, the projectId is just a key that gets one specific row from the database. After that it's not used. So this case there only one projectId per application session." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T21:28:44.553", "Id": "463506", "Score": "0", "body": "Please add your startup code to your question as it seems important to reviewing this code. As in your code the GetProjectFeatureIndicatorMetadata method isn't static" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T00:49:43.927", "Id": "463520", "Score": "0", "body": "I've added an update above. I've refactored some of the code and included some of the interfaces and classes in various layers. I appreciate you sticking with this!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T17:21:04.700", "Id": "236473", "ParentId": "236451", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T02:04:09.957", "Id": "236451", "Score": "2", "Tags": [ "c#", ".net", "asynchronous" ], "Title": "Can this async method be improved or simplified" }
236451
<p>I am brand new to writing hooks and I am having a little trouble getting my head wrapped around it. Initially, I wanted to write this with one event listener that passed the event and a separate param to distinguish itself from the other incoming arguments.</p> <p>With hooks, I was confused as to how I should pass a separate param and even more confused on how I would go about putting the logic into deciphering what each argument was.</p> <p>So... Basically, I am calling two arrow functions in render and using separate arguments to dictate what <code>iconType</code> the <code>onMouseOver</code> is effecting.</p> <p>I guess my question is, is this an acceptable way to write react hooks? This is my first component with any kind of state in my project (a simple navbar). I wan to make sure I am on the right path.</p> <pre><code>import React, { useState, useEffect } from 'react'; import '../styles/HomeNavBar.css'; import logo from '../styles/images/pulse_logo.png' // relative path to image export default function HomeNavBar() { const [isTrue, handleMouseOver] = useState(false) const [iconType, setArg] = useState('') return ( &lt;div id="navbar-container"&gt; &lt;div className="image-holder"&gt; &lt;img id="pulse-logo-nav" src={logo} alt={"pulse"}/&gt; &lt;/div&gt; &lt;nav id="navbar"&gt; &lt;div onMouseEnter={() =&gt; handleMouseOver(true), () =&gt; setArg('services')} onMouseLeave = {() =&gt; handleMouseOver(false), () =&gt; setArg('')} className="link-holder"&gt; {isTrue === false &amp;&amp; iconType !== 'services' ? &lt;p&gt;Services&lt;i className="fas fa-arrow-circle-right"&gt;&lt;/i&gt;&lt;/p&gt; : &lt;p&gt;Services&lt;i className="fas fa-arrow-circle-down"&gt;&lt;/i&gt;&lt;/p&gt;} &lt;/div&gt; &lt;div onMouseEnter={() =&gt; handleMouseOver(true), () =&gt; setArg('careers')} onMouseLeave = {() =&gt; handleMouseOver(false), () =&gt; setArg('')} className="link-holder"&gt; {isTrue === false &amp;&amp; iconType !== 'careers' ? &lt;p&gt;Careers&lt;i className="fas fa-arrow-circle-right"&gt;&lt;/i&gt;&lt;/p&gt; : &lt;p&gt;Careers&lt;i className="fas fa-arrow-circle-down"&gt;&lt;/i&gt;&lt;/p&gt;} &lt;/div&gt; &lt;div onMouseEnter={() =&gt; handleMouseOver(true), () =&gt; setArg('blog')} onMouseLeave = {() =&gt; handleMouseOver(false), () =&gt; setArg('')} className="link-holder"&gt; {isTrue === false &amp;&amp; iconType !== 'blog' ? &lt;p&gt;Blog&lt;i className="fas fa-arrow-circle-right"&gt;&lt;/i&gt;&lt;/p&gt; : &lt;p&gt;Blog&lt;i className="fas fa-arrow-circle-down"&gt;&lt;/i&gt;&lt;/p&gt;} &lt;/div&gt; &lt;div className="link-holder"&gt; &lt;p&gt;About&lt;/p&gt; &lt;/div&gt; &lt;div className="social-media-div"&gt; &lt;i className="fab fa-linkedin"&gt;&lt;/i&gt; &lt;i className="fab fa-facebook"&gt;&lt;/i&gt; &lt;/div&gt; &lt;/nav&gt; &lt;/div&gt; ); } <span class="math-container">````</span> </code></pre>
[]
[ { "body": "<p>Probably the biggest issue I see here is naming. In particular, <code>isTrue</code> is very vague - perhaps is <code>isHovered</code> would be better? And conventionally you use <code>set...</code> rather than <code>handle...</code> with <code>useState</code> so this should be <code>setIsHovered</code>. Similarly, I think you should rename <code>setArg</code> to <code>setIconType</code>.</p>\n\n<p>Also, I don't think you can pass 2 seperate functions as a prop. You maybe want to instead do this:</p>\n\n<pre><code>&lt;div \n onMouseEnter={() =&gt; {\n setIsHovered(true)\n setIconType('careers')\n }}\n&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Other than that, it looks fine to me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T08:49:02.210", "Id": "236462", "ParentId": "236454", "Score": "2" } } ]
{ "AcceptedAnswerId": "236462", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T02:46:48.383", "Id": "236454", "Score": "1", "Tags": [ "react.js" ], "Title": "React Hooks - Did I write this correctly?" }
236454
<p>I'm implementing the following function for signed integer numbers: given endpoints of a closed interval <code>lo</code> and <code>hi</code>, and inputs <code>x</code> (in <code>[lo..hi]</code>) and <code>dx</code>, I'd like to compute the "reflected sum": if <code>x + dx</code> is still in <code>[lo..hi]</code> then that's it; otherwise the underhanging or overhanging portion is "folded back" onto the result (shown as <code>y</code> below). Basically, <code>x</code> is "bouncing around" in the interval.</p> <pre><code> overhang /--\ dx --------------&gt; --------[-------|-------|---]---|------ lo x y hi x + dx &lt;--- </code></pre> <p>Because this is for a hardware circuit, I am doing this using Clash's <a href="http://hackage.haskell.org/package/clash-prelude-1.0.1/docs/Clash-Sized-Signed.html" rel="nofollow noreferrer">sized <code>Signed</code> integer type</a> and <a href="http://hackage.haskell.org/package/clash-prelude-1.0.1/docs/Clash-Class-Num.html#v:add" rel="nofollow noreferrer">width-extending addition</a>, otherwise it is normal Haskell code.</p> <p>My current implementation is the following:</p> <pre><code>bounce :: (KnownNat n, KnownNat k, (k + 1) &lt;= n) =&gt; (Signed n, Signed n) -&gt; Signed n -&gt; Signed k -&gt; (Signed n, Bool) bounce (lo, hi) x dx | under &gt; 0 = (lo + under, True) | over &gt; 0 = (hi - over, True) | otherwise = (resize new, False) where new = add x dx under = resize $ resize lo - new over = resize $ new - resize hi </code></pre> <p>Things I don't like about this implementation:</p> <ul> <li>There is a lot of noise about bit widths (all the <code>resize</code> calls)</li> <li>Overall, it is not immediately obvious by just looking at the code what it does. It feels like it's doing a lot of seemingly ad-hoc arithmetic operations that "just happen" to work. </li> </ul> <p>I am looking for improvements that come from the structure of the problem, not "oh you should rename <code>x</code> to <code>theNumberThatIsBouncingAround</code> because one-letter variable names bad".</p>
[]
[ { "body": "<p>I don't think your code agrees with your spec: Your code looks like it can only implement a function built from three line segments.</p>\n\n<p>You shouldn't need explicit resize.</p>\n\n<pre><code>bounce (lo, hi) x dx = let\n (bounces, remainder) = divMod (add dx $ x-lo) $ hi-lo\n in (if even bounces then lo + remainder else hi - remainder\n ,bounces /= 0)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T00:45:24.287", "Id": "463518", "Score": "0", "body": "Unfortunately, `divMod` by a non-power-of-two is not really implementable as a combinational circuit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T00:46:10.673", "Id": "463519", "Score": "0", "body": "I'm happy with not supporting multiple bounces in one timestep." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T00:53:21.317", "Id": "463521", "Score": "0", "body": "You are already implementing `divMod` by means of a lookup table for div in {-1,0,1}. That's why your code looks improvable to you. You do in fact need to implement `divMod` in some way, for that is your problem statement." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T00:41:45.537", "Id": "236481", "ParentId": "236459", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T06:09:36.903", "Id": "236459", "Score": "2", "Tags": [ "haskell", "integer" ], "Title": "\"Reflecting\" addition" }
236459
<p>I have a dictionary where for each key, a single value is stored. Say</p> <pre><code>import pandas as pd dd = {'Alice': 40, 'Bob': 50, 'Charlie': 35} </code></pre> <p>Now, I want to cast this dictionary to a pd.Dataframe with <em>two</em> columns. The first column contains the keys of the dictionary, the second column the values and give the columns a name (Say "Name" and "Age"). I expect to have a function call like:</p> <pre><code> pd.DataFrame(dd, columns=['Name', 'Age']) </code></pre> <p>which gives not desired output, since it only has 0 rows.</p> <p>Currently I have two "solutions":</p> <pre><code># Rename the index and reset it: pd.DataFrame.from_dict(dd, orient='index', columns=['Age']).rename_axis('Name').reset_index() pd.DataFrame(list(dd.items()), columns=['Name', 'Age']) # Both result in the desired output: Name Age 0 Alice 40 1 Bob 50 2 Charlie 35 </code></pre> <p>However, both appear a bit hacky and thus inefficient and error-prone to me. Is there a more pythonic way to achieve this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T15:13:25.257", "Id": "463462", "Score": "3", "body": "There's nothing wrong/hacky in using `pd.DataFrame(dd.items(), columns=['Name', 'Age'])` to get the needed result in your case" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T15:31:08.247", "Id": "463464", "Score": "0", "body": "@RomanPerekhrest, Didn't realize that ```list()´´´´ can be removed. Without this, it seems to be ok for me. Do you want to post it as an answer, so I can accept it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T15:32:43.510", "Id": "463465", "Score": "2", "body": "Honestly, it's too simple to be a significant answer." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T14:38:27.453", "Id": "236469", "Score": "2", "Tags": [ "python", "python-3.x", "pandas", "hash-map" ], "Title": "Pythonic way to cast a dictionary into a pd.DataFrame with two columns?" }
236469
<p>My program looks for the area of ​​the figures, depending on the value of the variable <code>а</code>.</p> <ol> <li><p>area -&gt; triangle</p> </li> <li><p>area -&gt; triangle2</p> </li> <li><p>area -&gt; square</p> </li> <li><p>area -&gt; rhombus</p> <p>I want to get constructive criticism about the structure of the code and what can be redone. The program is written in the Python programming language.</p> </li> </ol> <pre class="lang-py prettyprint-override"><code>while True: class S(): print(&quot;Для выхода нажмите Enter&quot;) a = int(input(&quot;1. Площадь прямоугольного тр. \n2. Площадь равнобедренного тр. \n3. Площадь квадрата \n4. Площадь ромба &quot;)) if a == 1: print(&quot;Это нахождение площади прямоугольного треугольника&quot;) a1 = float(input(&quot;Введите первый катет &quot;)) b1 = float(input(&quot;Введите второй катет &quot;)) class Triangle1(): def __init__(self, a1, b1): self.a = a1 self.b = b1 def area(self): return (self.a * self.b) / 2 Striangle1 = Triangle1(a1,b1) print(&quot;Площадь равна = &quot;,Striangle1.area()) elif a == 2: print(&quot;Это нахождение площади равнобедренного треугольника&quot;) a2 = float(input(&quot;Введите основание &quot;)) b2 = float(input(&quot;Введите высоту &quot;)) class Triangle2(): def __init__(self, a2, b2): self.a2 = a2 self.b2 = b2 def area(self): return (self.a2/2)*self.b2 Striangle2 = Triangle2(a2,b2) print(&quot;Площадь равна = &quot;,Striangle2.area()) if a == 3: print(&quot;Это нахождение площади квадрата &quot;) a3 = float(input(&quot;Введите сторону &quot;)) class Hexagon(): def __init__(self, a3): self.a3 = a3 def area(self): return self.a3**2 Shexagon = Hexagon(a3) print(&quot;Площадь равна = &quot;,Shexagon.area()) elif a == 4: print(&quot;Это нахождение площади ромба&quot;) a4 = float(input(&quot;Введите 1 диагональ &quot;)) b4 = float(input(&quot;Введите 2 диагональ &quot;)) class Romb(): def __init__(self, a4, b4): self.a4 = a4 self.b4 = b4 def area(self): return (self.a4*self.b4)/2 Sromb = Romb(a4,b4) print(&quot;Площадь равна = &quot;,Sromb.area()) </code></pre> <p><a href="https://drive.google.com/open?id=1962HO7OyPxOy2C5vsqJoBwF5NcpONuOX" rel="nofollow noreferrer">Drive link to the code</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T18:41:28.097", "Id": "463564", "Score": "2", "body": "Hi @feraun! Could you please convert those input prompts to English? Thanks!" } ]
[ { "body": "<p>There are several ways to improve this code:</p>\n\n<ol>\n<li>Commenting. Please add some comments to your code so other people can understand it easily. It might not be a \"coding\" suggestion but it is as important as writing a good code.</li>\n<li>Classes declaration location. It is not usual to declare the classes inside the main loop area. You can declare them outside, maybe even in another file.</li>\n<li>Use meaningful variables names. </li>\n<li>Use type annotations. To make the code faster and more readable.</li>\n<li>Remove redundant class. Class <code>S</code> is redundant and should probably be removed since it has no real functionality.</li>\n<li>Create a general class. All of your classes can inherit from a general <code>shape</code> class and override the <code>area</code> method.</li>\n<li>Remove redundant parentheses. Remove redundant parentheses in the classes declarations.</li>\n<li>Use <code>fstring</code> while printing.</li>\n<li>Do not write code in <code>main</code>. Create a function that <code>__main__</code> will call so none of your variables will be global.</li>\n</ol>\n\n<p>As said there are several ways to improve this code. All of them are suggestion and you do not have to implement any of them. This is a functioning and understandable code as is.</p>\n\n<p>I know you asked us to rate your code, but I will not :)<br>\nKeep programing!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T18:21:37.597", "Id": "236502", "ParentId": "236474", "Score": "2" } }, { "body": "<p>First, note that finding the area of an isosceles triangle is the same formula as finding the area of right triangle. Both are 1/2 * base * height. </p>\n\n<p>You are mixing object oriented classes and imperative programming. This usually happens as you are first learning about classes. Here is are two alternate structures to your code:</p>\n\n<p>First option, you can ignore classes. The only commonality between a triangle and an octagon is that both have an <code>area()</code> method. There is no common data: a triangle has no radius and an octagon has nothing but a radius. You can make functions like <code>triangle_area(base, height)</code>, <code>octagon_radius(radius)</code>. Both return areas. Just doing this would simplify your code.</p>\n\n<p>Second option, you use classes anyway. You might do this if you expect more commonality in the near future. For example, if this is becoming a drawing program then a Figure might be a class that \"has a x,y center, current color, a move command, a draw command and an area function.\" This code would have code common to all figures in class Figure and would have empty (or virtual) routines that are 'parts any subclass needs to implement to considered a Figure'. </p>\n\n<p>Here is some a code outline to ponder:</p>\n\n<pre><code> class Figure:\n def area(self): # return the area of this figure\n raise NotImplementedExeception('subclass must have an area() function')\n\n class Triangle(Figure): # inheritence is the promise to follow the superclass API\n def __init__(self, base, height):\n super().__init__() # this is boilerplate\n self.base, self.height = base, height\n\n def area(self):\n return self.base * self.height / 2\n\n @classmethod # used for custom constructors\n def ask_right(cls):\n print(\"Это нахождение площади прямоугольного треугольника\")\n a1 = float(input(\"Введите первый катет \"))\n b1 = float(input(\"Введите второй катет \"))\n return cls(a1, a2) # return a new triangle\n\n @classmethod\n def ask_isosceles():\n ...\n\ndef main():\n print(\"Для выхода нажмите Enter\")\n a = int(input(\"1. Площадь прямоугольного тр. \\n2. Площадь равнобедренного тр. \\n3. Площадь квадрата \\n4. Площадь ромба \"))\n if a == 1:\n fig = Triangle.ask_right()\n elif a == 2:\n fig = Triangle.ask_isosceles()\n elif a == 3:\n fig = Octagon.ask()\n\n print f\"Area is {fig.area()}\")\n</code></pre>\n\n<p>In summary, using classes to organize your code makes more sense if you are doing more than just one item. The real power comes from being able to write functions like:</p>\n\n<pre><code>def redraw(list_of_figures):\n clear_screen()\n for fig in list_of_figures:\n fig.draw() # which might be Circle.draw(), Triangle.draw() or another subclass\n</code></pre>\n\n<p>and adding a new subclass, say Pentagon(Figure), without having to change the redraw() function.</p>\n\n<p>Classes can be hard to get your head around; that is normal.</p>\n\n<p>Keep hacking! Keep notes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T02:22:09.040", "Id": "236507", "ParentId": "236474", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T17:46:57.233", "Id": "236474", "Score": "1", "Tags": [ "python", "object-oriented" ], "Title": "Calculating area of different figures on a case by case basis" }
236474
<p>The following code refreshes an observable array of Run objects by calling an api method every 5 seconds. This code is working, but it seems like there's probably a utility method I'm missing that would handle merging the array from the ajax response with the existing observable array. Any suggestions are appreciated.</p> <pre><code>... var that = this that.Active = ko.observableArray() that.refreshActive = function() { $.get('/DataCon/GetActiveRuns') .done(function(data) { var deleted = [] ko.utils.arrayForEach(that.Active(), function(item) { if (!data.find(x =&gt; x.Id === item.Id())) deleted.push(item) }) that.Active.removeAll(deleted) data.forEach(run =&gt; { var match = ko.utils.arrayFirst(that.Active(), function(item) { return item.Id() === run.Id }) if (match) { ko.mapping.fromJS(run, match) } else { that.Active.push(ko.mapping.fromJS(run)) } }) }) .fail(function() { toastr.error('failed to refresh active runs') }) } ... vm.refreshActive() setInterval(vm.refreshActive, 5000) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T22:15:43.430", "Id": "463512", "Score": "0", "body": "Would you mind explaining the downvote? I'm genuinely curious." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T21:46:50.673", "Id": "236479", "Score": "1", "Tags": [ "javascript", "knockout.js" ], "Title": "knockout js refresh observable array from ajax" }
236479
<p>I have time-series data (<code>t</code>) that I want to loop through each <code>t</code> and take the difference of the previous five lags <code>t-1 ... t-5</code>. </p> <p>This code works, but is inefficient. I'm not sure how to increase the performance and efficiency of the code. </p> <p><strong>Sample data</strong></p> <pre><code>import pandas as pd import numpy.random as nr dat = pd.DataFrame({'t': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'rnum': nr.rand(10)}) </code></pre> <p><strong>Function</strong></p> <pre><code>def diff_n(idat): # Get t from group i = idat['t'].iat[0] # If one, nothing to difference if i == 1: return None # Get value to loop through and diff h1 = idat.groupby('t')['rnum'].mean().values # Subset dat (outside fn) h2 = dat[(dat.t &lt; i ) &amp; (dat.t &gt;= i - 5)] # Combine data for return retdat = pd.DataFrame() # Loop through t-1 to last obs for j in range(max(h2.t), min(h2.t), -1): # Get value to difference from h1 h3 = h2[h2.t == j].groupby('t')['rnum'].mean().values # Difference ndiff = (h3 - h1) # Build df and concat indat = pd.DataFrame({'t': [i], 'lag': i - j, 'diff': ndiff}) retdat = pd.concat([retdat, indat]) return retdat </code></pre> <p><strong>Groupby and apply the function to each t</strong></p> <pre><code>dat.groupby('t').apply(lambda x: diff_n(x)) </code></pre> <p><strong>Output</strong></p> <pre><code>&gt;&gt;&gt; dat.groupby('t').apply(lambda x: diff_n(x)) t lag diff t 2 0 2 1 0.440644 3 0 3 1 -0.284075 0 3 2 0.156569 4 0 4 1 0.439154 0 4 2 0.155079 0 4 3 0.595723 5 0 5 1 -0.095552 0 5 2 0.343602 0 5 3 0.059527 0 5 4 0.500171 6 0 6 1 0.296337 0 6 2 0.200784 0 6 3 0.639939 0 6 4 0.355864 0 6 5 0.796507 7 0 7 1 -0.749913 0 7 2 -0.453576 0 7 3 -0.549128 0 7 4 -0.109974 0 7 5 -0.394049 8 0 8 1 0.506379 0 8 2 -0.243534 0 8 3 0.052803 0 8 4 -0.042749 0 8 5 0.396405 9 0 9 1 -0.021761 0 9 2 0.484618 0 9 3 -0.265295 0 9 4 0.031042 0 9 5 -0.064510 10 0 10 1 0.409118 0 10 2 0.387357 0 10 3 0.893736 0 10 4 0.143823 0 10 5 0.440160 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T13:07:48.213", "Id": "463551", "Score": "0", "body": "Does your `t` column always contain numbers in consecutive increasing order? Could you have this sequence `'t': [1, 2, 3, 4, 5, 6, 3, 7, 8, 9, 2, 10, 5]` (repetitive numbers) ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T15:32:24.450", "Id": "463555", "Score": "0", "body": "@RomanPerekhrest I'm not sure what you mean. But yes, the nature of the problem means `t` is in consecutive increasing order." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T18:38:57.187", "Id": "463563", "Score": "0", "body": "Grouping by `t` values with `dat.groupby('t')` implicitly indicates that there could repetitive values, but in that case - the above code will fail (`ValueError: arrays must all be same length` .+. `KeyError: 't'`). Sample input `'t': [1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9, 10]`. But if your `t` column is not supposed to contain duplicate values - then why grouping on `t` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T21:04:15.037", "Id": "463568", "Score": "0", "body": "@RomanPerekhrest Yes, `t` will contain duplicate values because the `lag` variable is different across `t`. I use `groupby()` to get each `t`, then apply the function on `n` lags." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T09:33:22.383", "Id": "463589", "Score": "0", "body": "As I mentioned, your code will **not** work on this sample input `pd.DataFrame({'t': [1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9, 10], 'rnum': nr.rand(12)})`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T16:30:11.257", "Id": "463634", "Score": "0", "body": "@RomanPerekhrest Sorry, I fixed the code so your sample input will work now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T17:05:49.997", "Id": "463638", "Score": "0", "body": "It does not work with your fix, same errors" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T17:23:39.070", "Id": "463640", "Score": "0", "body": "@RomanPerekhrest Sorry I didn't change the for loop groupby. Works now." } ]
[ { "body": "<p>First of all, nice code, very readable and good comments.</p>\n\n<p>There are several improvements you can do:</p>\n\n<ol>\n<li>Reindex your dataframe with <code>t</code>. You are writing a lot of times <code>.t</code>, if you will use <code>index</code> some of <code>pandas</code> index optimization will kick in and your code will be faster.</li>\n<li>Do not do <code>concat</code> on only 2 items. Concatenate function will work much faster if you will just do all of the concatenation of all 5 elements at once.</li>\n<li>Why do you need <code>h2</code>? Try to avoid unnecessary coping of the data frame. You can work on the original <code>h1</code> or even <code>idat</code> since your function does not change anything implicitly.</li>\n<li>Use type annotations. Using type annotations can make the code run faster since the interpreter does not need to figure out what is the variable type. Also, probably even more important, it helps readability.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T18:04:25.537", "Id": "236501", "ParentId": "236480", "Score": "2" } }, { "body": "<h3>Toward better performance and functionality (reducing code run time twice)</h3>\n\n<p>Always give your identifier/variable/function a meaningful name.<br>Most of your identifiers/variables should be renamed to reflect the actual intention and purpose.<br> A short sample of better naming: </p>\n\n<ul>\n<li><code>dat</code> --> <strong><code>df</code></strong></li>\n<li><code>idat</code> --> <strong><code>group</code></strong></li>\n<li><code>i</code> variable, which is actually <code>t</code> value --> <strong><code>t</code></strong></li>\n<li><code>h1</code> variable, which is actually <code>rnum</code> mean value --> <strong><code>rnum_mean</code></strong> </li>\n</ul>\n\n<p>and so on ... (see the final implementation below)</p>\n\n<hr>\n\n<p><strong><code>diff_n</code></strong> function <br></p>\n\n<p>The number <code>5</code> serves as \"subtraction factor\" thus instead of hard-coding it it's better to make that factor adjustable and define it as default argument:</p>\n\n<pre><code>def diff_n(group, n=5):\n</code></pre>\n\n<p>Calling <code>.groupby('t')</code> in <code>idat.groupby('t')</code> and <code>h2[h2.t == j].groupby('t')</code> is redundant as the input/initial dataframe is already grouped by same <code>t</code> values (<code>dat.groupby('t').apply(lambda x: diff_n(x)</code>) and <code>diff_n</code> function will accept sub-dataframe having the <strong>same</strong> <code>t</code> column values but various <code>rnum</code> column values. </p>\n\n<p>No need to <code>mean().values</code> as <code>mean()</code> is a reducing function and returns a single value.</p>\n\n<p>Instead of generating a new dataframe and accumulate data with <code>pd.concat()</code> on each loop iteration - a single dataframe can be generated at once accepting a list of composed dictionaries.</p>\n\n<hr>\n\n<p>The final optimized approach:</p>\n\n<pre><code>import pandas as pd\nimport numpy.random as nr\n\ndf = pd.DataFrame({'t': [1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9, 10], 'rnum': nr.rand(12)})\n\ndef diff_n(group, n=5):\n t, rnum_mean = group.t.iloc[0], group.rnum.mean()\n if t == 1:\n return None\n\n # Subset df (outside fn)\n diff_rows = df[(df.t &lt; t) &amp; (df.t &gt;= t - n)]\n return pd.DataFrame([{'t': t,\n 'lag': t - i,\n 'diff': diff_rows[diff_rows.t == i].rnum.mean() - rnum_mean}\n for i in range(max(diff_rows.t), min(diff_rows.t), -1)])\n\n\nres = df.groupby('t').apply(lambda x: diff_n(x))\n</code></pre>\n\n<hr>\n\n<p><strong>Time performance comparison</strong> (tested on randomly generated sequence of numbers for <code>rnum</code> column):</p>\n\n<pre><code>rnum_data = [0.32371336559866004, 0.10698919887971459, 0.7953413399540619,\n 0.9868916409057458, 0.9441608945915095, 0.47072752314030053,\n 0.4508488822488548, 0.028372702128714233, 0.87623218782289,\n 0.16471466305535765, 0.1, 0.2]\ndf = pd.DataFrame({'t': [1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9, 10], 'rnum': rnum_data})\n...\n</code></pre>\n\n<p>The old (initial) approach:</p>\n\n<pre><code>import timeit\nprint(timeit.timeit(\"dat.groupby('t').apply(lambda x: diff_n(x))\", globals=globals(), number=100))\n\n5.156789435990504\n</code></pre>\n\n<p>The new approach:</p>\n\n<pre><code>import timeit\nprint(timeit.timeit(\"df.groupby('t').apply(lambda x: diff_n(x))\", globals=globals(), number=100))\n\n2.5971586129890056\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T18:30:24.267", "Id": "463751", "Score": "1", "body": "Great! Thank you for your effort. Much better performance." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T18:44:05.150", "Id": "236547", "ParentId": "236480", "Score": "2" } } ]
{ "AcceptedAnswerId": "236547", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T00:20:26.457", "Id": "236480", "Score": "5", "Tags": [ "python", "performance", "python-3.x", "numpy", "pandas" ], "Title": "Loop through group and difference lags" }
236480
<p>Wrote some code to install bootstrap (latest) in a newly created rails application.</p> <p>update: fixed a typo</p> <pre><code>yarn add bootstrap jquery popper.js expose-loader yarn install --check-files perl -pi.bak -e "s/extract_css: false/extract_css: true/" config/webpacker.yml s1=$'\n\nimport "bootstrap/dist/js/bootstrap";' echo "$s1" &gt;&gt; app/javascript/packs/application.js echo '@import "~bootstrap/scss/bootstrap";' &gt; app/javascript/packs/styles.scss (gsed $'/module.exports = environment/{e cat expose-loader.txt\n}' config/webpack/environment.js) &gt; config/webpack/environment.js.new mv config/webpack/environment.js.new config/webpack/environment.js (gsed $'/javascript_pack_tag .application/{e cat stylesheet_pack_tag.txt\n}' app/views/layouts/application.html.erb) &gt; app/views/layouts/application.html.erb.new mv app/views/layouts/application.html.erb.new app/views/layouts/application.html.erb </code></pre>
[]
[ { "body": "<p>In the two uses of <code>( )</code>, you have single commands:</p>\n\n<blockquote>\n<pre><code>(gsed $'/module.exports = environment/{e cat expose-loader.txt\\n}' config/webpack/environment.js) &gt; config/webpack/environment.js.new\n ...\n(gsed $'/javascript_pack_tag .application/{e cat stylesheet_pack_tag.txt\\n}' app/views/layouts/application.html.erb) &gt; app/views/layouts/application.html.erb.new\n</code></pre>\n</blockquote>\n\n<p>These could be written as:</p>\n\n<pre><code>gsed $'/module.exports = environment/{e cat expose-loader.txt\\n}' config/webpack/environment.js &gt; config/webpack/environment.js.new\n...\ngsed $'/javascript_pack_tag .application/{e cat stylesheet_pack_tag.txt\\n}' app/views/layouts/application.html.erb &gt; app/views/layouts/application.html.erb.new\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-10T10:35:01.143", "Id": "236983", "ParentId": "236482", "Score": "0" } }, { "body": "<p>It's worth starting with a shebang; I'd also advise setting shell flags <code>-e</code> (exit on error) and <code>-u</code> (error when using unset variables):</p>\n<pre><code>#!/bin/bash\n\nset -eu\n</code></pre>\n<p>Please use more whitespace and comments to make it easier to follow.</p>\n<p>Perl is overkill for the simple substitution here - if we stick to sed, then that's one fewer dependency:</p>\n<pre><code>sed -e '/^extract_css:/:.*/ true/' \\\n -i config/webpacker.yml\n</code></pre>\n<p>I omitted creating the backup because I don't think there's any value in keeping the original. If your later processes depend on having it around, then use <code>-i.bak</code> instead of <code>-i</code>, as in Perl (in fact, that's where Perl got that option).</p>\n<p>The two transform-and-move pairs can also use <code>sed -i</code>, making the script more consistent, and thus easier to follow. We can use the (standard sed) <code>r</code> command to read a file, instead of the non-standard <code>e</code> command:</p>\n<pre><code>sed -e '/module.exports = environment/rexpose-loader.txt' \\\n -i config/webpack/environment.js\nsed -e '/javascript_pack_tag .application/rstylesheet_pack_tag.txt' \\\n -i app/views/layouts/application.html.erb\n</code></pre>\n<p><code>$s1</code> is only used once, and doesn't add any value (such as a meaningful name), so just inline it.</p>\n<p>If we can eliminate the one use of C-escape quoting, then we can use plain POSIX shell instead of Bash.</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#!/bin/sh\n\nset -eu\n\nyarn add bootstrap jquery popper.js expose-loader\nyarn install --check-files\n\nsed -e '/^extract_css:/:.*/ true/' \\\n -i config/webpacker.yml\n\nprintf '\\n\\n%s' 'import &quot;bootstrap/dist/js/bootstrap&quot;;' \\\n &gt;&gt; app/javascript/packs/application.js\necho '@import &quot;~bootstrap/scss/bootstrap&quot;;' \\\n &gt; app/javascript/packs/styles.scss\n\nsed -e '/module.exports = environment/rexpose-loader.txt' \\\n -i config/webpack/environment.js\nsed -e '/javascript_pack_tag .application/rstylesheet_pack_tag.txt' \\\n -i app/views/layouts/application.html.erb\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-10T11:31:46.760", "Id": "236985", "ParentId": "236482", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T01:43:51.430", "Id": "236482", "Score": "4", "Tags": [ "bash", "unix", "sed" ], "Title": "Bash code to install bootstrap in a Ruby on Rails repository" }
236482
<p>Let's take the famous fibonacci problem as an example but this is a generic problem. Also, taking scala as the language as it's rather feature-rich. I want to know which solution you'd prefer.</p> <p>we all know that the following implementation is evil as it's not stack-safe: </p> <pre><code>//bad! def naiveFib(n: Int): BigInt = { if (n &lt;= 1) 1 else naiveFib(n - 1) + naiveFib(n - 2) } </code></pre> <p>we can improve it and make it tail-recursive and stack-safe:</p> <pre><code>def fibStackSafe(n: Int): BigInt = { @tailrec def internally(cycles: Int, last: BigInt, next: BigInt): BigInt = if (cycles &gt; 0) internally(cycles-1, next, last+next) else next internally(n - 2 , last = 1, next = 1) } </code></pre> <p>acceptable solution. Equally acceptable, is a solution like:</p> <pre><code>def fibByEval(n: Int): BigInt = { def internally(cycles: Int, last: BigInt, next: BigInt): Eval[BigInt] = Eval.always(cycles &gt; 0).flatMap { case true =&gt; internally(cycles-1, next, last+next) case false =&gt; Eval.now(next) } internally(n - 2 , last = 1, next = 1).value } </code></pre> <p>which uses <a href="https://typelevel.org/cats/datatypes/eval.html" rel="nofollow noreferrer">cats's Eval</a>/<a href="https://monix.io/docs/3x/eval/coeval.html" rel="nofollow noreferrer">Monix's Coeval</a> (slight difference between the two, feel free to comment on your preference) which guarantees stack-safety by definition. Although an Eval-powered function can still lack heap-safety and give you memory error. It does win you a few other things too.</p> <p>Here is a Stream/LazyList attempt which uses the concepts of lazy-evaluation: </p> <pre><code>def fibByZip(n: Int): BigInt = { def inner:Stream[Pure, BigInt] = Stream(BigInt(1)) ++ Stream(BigInt(1)) ++ (inner zip inner.tail).map{ t =&gt; t._1 + t._2 } inner.drop(n-1).take(1).compile.toVector.head } </code></pre> <p>this one comes with the feature/overhead of internally "caching" the intermediate results. </p> <p>Here is a more/less (depending on your point of view) readable version of the above: </p> <pre><code>def fibByScan(n: Int): BigInt = { def inner: Stream[Pure, BigInt] = Stream(BigInt(1)) ++ inner.scan(BigInt(1))(_ + _) inner.drop(n-1).take(1).compile.toVector.head } </code></pre> <p>and finally, here is an effect-full approach which uses <a href="https://fs2.io/guide.html" rel="nofollow noreferrer">fs2 streams</a> and <a href="https://typelevel.org/cats-effect/concurrency/ref.html" rel="nofollow noreferrer">cats's Ref</a>:</p> <pre><code>def fibStream(n: Int): IO[Int] = { val internal = { def getNextAndUpdateRefs(twoBefore: Ref[IO, Int], oneBefore: Ref[IO, Int]): IO[Int] = for { last &lt;- oneBefore.get lastLast &lt;- twoBefore.get _ &lt;- twoBefore.set(last) result = last + lastLast _ &lt;- oneBefore.set(result) } yield result for { twoBefore &lt;- Stream.eval(Ref.of[IO, Int](1)) oneBefore &lt;- Stream.eval(Ref.of[IO, Int](1)) _ &lt;- Stream.emits(Range(0, n-2)) res &lt;- Stream.eval(getNextAndUpdateRefs(twoBefore, oneBefore)) } yield res } internal.take(n).compile.lastOrError } </code></pre> <p>it's not pure but it's thread-safe and pretty readable.</p> <p>The code starts simple but will change in the future and needs to be maintained. </p> <ul> <li><p>model changing whereas instead of using the last two entries, you might need the last three elements. </p></li> <li><p>you want to easily debug it and/or reason about it.</p></li> <li><p>you want to easily and efficiently test it</p></li> <li><p>the model might become numerical and non-exact so you might want to test it for more than just correctness.</p></li> <li><p>model will become async to calculate.</p></li> <li><p>might need to introduce parallelism. </p></li> </ul> <p>I appreciate we should be agile and not future proof things too much, but I am interested to know which option people would go for, considering the following criteria:</p> <ul> <li>readability</li> <li>conciseness</li> <li>flexibility to maintain</li> <li>performance</li> </ul> <p>feel free to mention other criteria I might be ignoring here. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T06:23:52.060", "Id": "463524", "Score": "0", "body": "Any fibonacci number can be computed in constant time O(1) using the nonrecursive formula. That would be the most efficient, most readable, most concise And most flexible implementation. Unless you need to generate entire series up to nth element." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T09:12:32.823", "Id": "463532", "Score": "2", "body": "Please see the top of the post: \"Let's take the famous fibonacci problem as an example but this is a generic problem\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T09:16:34.310", "Id": "463533", "Score": "1", "body": "And the generic answer Is look for non-recursive ways. They Are Always better. Sometimes by miniscule amount but often much more than that. Anyway generic questions Are off topic on this site." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T03:17:00.067", "Id": "236484", "Score": "2", "Tags": [ "recursion", "functional-programming", "comparative-review", "scala" ], "Title": "generic implementation approaches for a recursive function" }
236484
<p>I wanted to get feedback on the correctness and efficiency of this post order traversal routine that my wife and I find really easy to grasp.</p> <pre class="lang-py prettyprint-override"><code>def postOrderTraversal(root: TreeNode): curr = root stack = [] while stack or curr: if curr is None: if stack[-1].right is None or popped == stack[-1].right: popped = stack.pop() print(popped.val) else: curr = stack[-1].right else: stack.append(curr) curr = curr.left </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T07:13:58.647", "Id": "463527", "Score": "4", "body": "Is this Python? Please add the appropriate tag of the language used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T08:41:05.317", "Id": "463530", "Score": "0", "body": "There is not much to go on regarding what this code is to accomplish. There is `stack`, indexable by integers, holding things with attributes `right` and `val`, the latter getting printed conditionally. Now, what is that `postOrder` as in `postOrderTraversal`? (Can't be Python, where identifiers should be `snake_case`.)" } ]
[ { "body": "<p>Congratulations on finding code you enjoy!</p>\n\n<p>This appears to be walking through a binary tree you have defined (or possibly from <a href=\"https://toytree.readthedocs.io/en/latest/6-treenodes.html\" rel=\"nofollow noreferrer\">toytree</a>?). Walking through this with an explicit stack is one way of thinking of the problem, and the code can be a good learning experience.</p>\n\n<p>An alternate method would be to use the Python's recursion system, where you make code vaguely like:</p>\n\n<pre><code> def walk(tree):\n if tree is not None: # ignore walking into an empty node\n walk(tree.left)\n walk(tree.right)\n print(tree.val)\n</code></pre>\n\n<p>It takes a a little brain stretching to see these as equivalent. As an exercise you should explore making the function a generator. That is, would call it as:</p>\n\n<pre><code> for value in tree.walk():\n print(value)\n</code></pre>\n\n<p>To do this, you need to replace a <code>print</code> with a <code>yield</code>, and a recursive call with a <code>yield from</code>. Try it: it does a different stretch on the brain.</p>\n\n<p>As far as efficiency, you need to use the the <a href=\"https://docs.python.org/3.8/library/timeit.html\" rel=\"nofollow noreferrer\">timeit</a> module to see what does run fast. In general, tree structures with a single value do poorly for really large numbers because memory access is a bit slow. However, profiling is necessary for optimizing by less than factors of n (the size of the tree). Orders of magnitude can be judged by eye and logic while unexpected internals might double the speed of some code. </p>\n\n<p>You might notice that your code will currently fail on being passed an empty tree (root=None), as <code>popped</code> will be checked before it is assigned. I am not sure why you are checking if popped equals the right node.</p>\n\n<p>Keep hacking! Keep notes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T04:19:51.237", "Id": "463580", "Score": "0", "body": "I disagree; the OP’s code will not fail when passed an empty tree. With `root == None`, both `curr` and `stack` will be falsy, so `stack or curr` will be `False`, and the `while` loop will execute zero times, and `popped` will never be referenced." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T04:25:52.010", "Id": "463581", "Score": "0", "body": "Regarding “_I am not sure why you are checking if popped equals the right node_”: that is rather critical to the correct functioning of their implementation. I suggest you study what their code is doing; walk through some examples by hand. Remove that check, and see how the wrong results are produced. Avoid answering questions you are not qualified to answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T01:16:34.137", "Id": "236505", "ParentId": "236486", "Score": "1" } }, { "body": "<h1>PEP-8</h1>\n\n<p>As commented by greybeard, the PEP-8 guidelines for Python suggest using <code>CapWords</code> for class names, and <code>snake_case</code> for variables and method names. So <code>postOrderTraversal</code> should be <code>post_order_traversal</code></p>\n\n<h1>Type Hints</h1>\n\n<p>Your code is incomplete, which makes it more difficult to review. Clearly, you have defined the <code>TreeNode</code> elsewhere, or your code would not run. You should include that code in your question post. (But don’t change it now that there have been answers posted to your question; your change would just be rolled back. In future questions, include all referenced code, including import statements and type definitions.)</p>\n\n<p>You are only half using type hints. You indicate that <code>postOrderTraversal</code> takes a <code>TreeNode</code> as an input parameter, but not specified what it returns. It doesn’t return anything, which should be indicated with <code>-&gt; None</code>. Eg)</p>\n\n<pre><code>def postOrderTraversal(root: TreeNode) -&gt; None:\n # remainder of function\n</code></pre>\n\n<h1>Documentation</h1>\n\n<p>You should help future users of your function understand what your function does and how to use it properly, without needing to read the code, by providing a <code>\"\"\"docstring\"\"\"</code> at the start of the function. A user may then type <code>help(postOrderTraversal)</code>, which would print out that information. </p>\n\n<p>You should help future maintainers of the code (including yourself) understand how the code works by including comments in the code, to describe the overall algorithm, and any non-obvious aspects. It is clear Charles Merriam did not understand the point of checking if <code>popped == stack[-1].right</code>, so that could definitely stand a comment or two.</p>\n\n<p>Please note the distinction between “users of” and “maintainers of”. A user needs a docstring describing what the function does, what it needs and what it returns. A maintainer needs comments in the code describing how the code functions.</p>\n\n<h1>Iterative Algorithm</h1>\n\n<p>When you first visit a node, you push it on the stack, so you can return to it a second time, and then proceed to walk down the left branch.</p>\n\n<p>When you return to the node, you leave it on the stack, so you can return to it a third time, and then you proceed to walk down the right branch.</p>\n\n<p>When you again return to the node the third time, you finally “process” the node ... by popping it off the stack and printing its value.</p>\n\n<p>You maintain a state machine using <code>curr</code>, <code>popped</code> and <code>stack[-1].right</code> to determine whether this is the first, second, or third visit to the node, which is somewhat complicated, despite you and your wife finding it “<em>easy to grasp</em>.”</p>\n\n<p>Instead, consider pushing both the node and the state information onto the stack.</p>\n\n<pre><code> stack.append((curr, False))\n curr = curr.left\n</code></pre>\n\n<p>And pop both pieces off the stack:</p>\n\n<pre><code> curr, visited_right = stack.pop()\n if visited_right:\n print(curr.val)\n curr = None\n else:\n stack.append((curr, True))\n curr = curr.right\n</code></pre>\n\n<p>With this change, you no longer need to maintain and check <code>popped</code> against <code>stack[-1].right</code>. The state is stored along with the node on the stack.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T05:23:41.887", "Id": "236513", "ParentId": "236486", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T07:00:09.843", "Id": "236486", "Score": "2", "Tags": [ "python", "algorithm", "python-3.x", "tree" ], "Title": "Iterative “post order” tree traversal" }
236486
<p>I made a preg_match to get my results and it works fine but I think it can be done with simple lines instead of repeating the code</p> <pre><code>$input = array('http://example.com/blue-bloods-s10e13-more-text/','http://example.com/charmed-2018-s02e11-more-text/','http://example.com/dynasty-2017-s03e11-more-text/','http://example.com/magnum-p-i-2018-s02e14-more-text/','http://example.com/fresh-off-the-boat-s06e13-more-text/','http://example.com/hawaii-five-0-2010-s10e14-more-text/','http://example.com/american-housewife-s04e13-more-text/','http://example.com/love-us-s01e13-more-text/'); foreach ($input as $value ){ preg_match('/http:\/\/example.com\/([^`]*?)-s([0-9]{2})e([0-9]{2})/', $value, $matches); $name = $matches[1]; $cname = preg_replace('/-us/', '', $name); $cname1 = preg_replace('/-/', ' ', $cname); $cname2 = preg_replace('/([0-9]{4})$/', '', $cname1); $cname3 = preg_replace('/\s$/', '', $cname2); echo $cname3."&lt;br&gt;"; } </code></pre> <p>The output is exactly like what I want</p> <pre><code>blue bloods charmed dynasty magnum p i fresh off the boat Hawaii five 0 american housewife love </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T12:45:19.357", "Id": "463549", "Score": "2", "body": "Welcome to Code Review. Can you add more information about what the input data looks like and what part of that you're interested in?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T16:07:06.473", "Id": "463556", "Score": "0", "body": "@Mask the input data already at the top of my code, the output that I wrote above is what I need, Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T22:20:35.287", "Id": "463775", "Score": "0", "body": "@Mast this looks good enough to reopen." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T22:20:51.910", "Id": "463776", "Score": "0", "body": "@Roman this looks good enough to reopen." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-04T07:26:18.970", "Id": "463794", "Score": "0", "body": "@mickmackusa My original comment has not be addressed, at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-04T07:51:32.243", "Id": "463798", "Score": "1", "body": "@Sammax I see that you have provided a battery of input strings and your exact desired output, but Mast wants _more_. Please edit your question to include a plain English description of what your pattern needs to do and how your strings may vary. For instance, is it possible to have a string with `-us` followed by `-2020`? How about in the opposite order? I would like to post an answer, but cannot while this page is closed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-04T08:00:58.583", "Id": "463801", "Score": "0", "body": "@Sammax how might this show look as one of your strings? https://m.imdb.com/title/tt0389564/?ref_=m_ttls_tt_3" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-05T01:00:17.123", "Id": "463951", "Score": "0", "body": "@ mickmackusa Good point, in this case I must improve the pattern." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-08T13:14:30.237", "Id": "464334", "Score": "0", "body": "Is this really gonna just hang at 4 out of 5 reopen votes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T23:01:35.737", "Id": "464985", "Score": "0", "body": "Well, I cannot post an answer because all 4 Reopen votes have timed out. Please edit your question then perhaps another wave of support can be offered." } ]
[ { "body": "<h3>Toward optimization and better functionality</h3>\n\n<ul>\n<li><p>consider using short array syntax <code>[]</code> instead of old-fashioned <code>array()</code> </p></li>\n<li><p>do not designate redundant captured groups such as <code>([0-9]{2})...([0-9]{2})</code> if you only need the 1st captured group <code>([^`]*?)</code></p></li>\n<li><p>regex <code>[0-9]</code> has a concise equivalent for designating digits - <strong><code>\\d</code></strong></p></li>\n</ul>\n\n<p>All those <code>preg_replace</code> calls in the initial approach can be combined into a single call using regex alternation group <code>/-us|(\\d{4}|\\s)$/</code> for combining the needed patterns. <br>The <code>\\s$</code> patten could also be excluded from combined pattern in favor of <code>rtrim</code> function call.<br>As <code>/-/</code> is the only pattern that is too simple and requires different replacement string <code>' '</code> (space) - it deserves to be a simple string replacement with <a href=\"https://www.php.net/manual/en/function.str-replace.php\" rel=\"nofollow noreferrer\"><code>str_replace</code></a> function.</p>\n\n<hr>\n\n<p>The final optimized approach:</p>\n\n<pre><code>$input = ['http://example.com/blue-bloods-s10e13-more-text/','http://example.com/charmed-2018-s02e11-more-text/',\n 'http://example.com/dynasty-2017-s03e11-more-text/','http://example.com/magnum-p-i-2018-s02e14-more-text/', \n 'http://example.com/fresh-off-the-boat-s06e13-more-text/','http://example.com/hawaii-five-0-2010-s10e14-more-text/',\n 'http://example.com/american-housewife-s04e13-more-text/','http://example.com/love-us-s01e13-more-text/'];\n\nforeach ($input as $value){\n preg_match('/http:\\/\\/example.com\\/([^`]*?)-s\\d{2}e\\d{2}/', $value, $matches);\n $name = str_replace('-', ' ', preg_replace('/-us|(\\d{4}|\\s)$/', '', $matches[1]));\n echo $name . \"&lt;br&gt;\";\n}\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>blue bloods\ncharmed\ndynasty\nmagnum p i\nfresh off the boat\nhawaii five 0\namerican housewife\nlove\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T10:21:35.153", "Id": "236526", "ParentId": "236489", "Score": "2" } } ]
{ "AcceptedAnswerId": "236526", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T10:46:23.360", "Id": "236489", "Score": "2", "Tags": [ "php" ], "Title": "Enhance and Shrink Preg_match lines" }
236489
<p>here is my first project : I have made a double pendulum animation with tkinter on Python. Can you give me some feedback on what can be improved ? Thanks !</p> <p>Code :</p> <pre class="lang-py prettyprint-override"><code># General imports import tkinter as tk import random import math as m # Parameters G = 9.81 class Pendulum(): def __init__(self, theta: float, theta_dot: float, mass: float, length: float, width: int = 3): """Creates a Pendulum with a given position, velocity, length and mass. width represent the width of the rope of the pendulum. The size of the pendulum is proportional to its mass.""" self.theta = theta self.theta_dot = theta_dot self.mass = mass self.length = length self.width = width class App(tk.Tk): def __init__(self, pendulum_1: Pendulum, pendulum_2: Pendulum, width: int = 600, height: int = 600, offset_width: int = 300, offset_height: int = 120, dt: float = 0.05): """Initialize the widget for the double pendulum animation. offset_width and offset_height represent the x and y offsets from the top left corner of the canvas to place the first pendulum.""" # Setting attributes self.width = width self.height = height self.offset_width = offset_width self.offset_height = offset_height self.dt = dt self.pendulum_1 = pendulum_1 self.pendulum_2 = pendulum_2 self.trace_coords = [] # Setting canvas widget tk.Tk.__init__(self) self.title("Double Pendulum") self.canvas = tk.Canvas(self, width=self.width, height=self.height) self.canvas.pack(side="top") # Action self.after(1, self.draw_frame) def update_pendulums_positions(self): """Update the angle positions and velocities of the two pendulums""" # Dealing with the first pendulum equation of motion num_1 = -G * (2 * self.pendulum_1.mass + self.pendulum_2.mass) num_1 *= m.sin(self.pendulum_1.theta) num_2 = -self.pendulum_2.mass * G num_2 *= m.sin( self.pendulum_1.theta - 2 * self.pendulum_2.theta ) num_3 = -2 * m.sin(self.pendulum_1.theta-self.pendulum_2.theta) num_3 *= self.pendulum_2.mass num_3 *= ( self.pendulum_2.theta_dot**2 * self.pendulum_2.length + self.pendulum_1.theta_dot**2 * self.pendulum_1.length * m.cos( self.pendulum_1.theta - self.pendulum_2.theta ) ) denom_1 = self.pendulum_1.length * ( 2 * self.pendulum_1.mass + self.pendulum_2.mass - self.pendulum_2.mass * m.cos( 2 * self.pendulum_1.theta - 2 * self.pendulum_2.theta ) ) # Dealing with the second pendulum equation of motion num_4 = 2 * m.sin(self.pendulum_1.theta - self.pendulum_2.theta) num_5 = ( self.pendulum_1.theta_dot**2 * self.pendulum_1.length * (self.pendulum_1.mass + self.pendulum_2.mass) ) num_6 = G * (self.pendulum_1.mass + self.pendulum_2.mass) num_6 *= m.cos(self.pendulum_1.theta) num_7 = self.pendulum_2.theta_dot**2 * self.pendulum_2.length num_7 *= self.pendulum_2.mass * m.cos( self.pendulum_1.theta - self.pendulum_2.theta ) denom_2 = self.pendulum_2.length * ( 2 * self.pendulum_1.mass + self.pendulum_2.mass - self.pendulum_2.mass * m.cos( 2 * self.pendulum_1.theta - 2 * self.pendulum_2.theta ) ) # Compute the accelerations theta1_dotdot = (num_1 + num_2 + num_3) / denom_1 theta2_dotdot = (num_4*(num_5+num_6+num_7)) / denom_2 # Update the velocities and positions self.pendulum_1.theta_dot += theta1_dotdot * self.dt self.pendulum_1.theta += self.pendulum_1.theta_dot * self.dt self.pendulum_2.theta_dot += theta2_dotdot * self.dt self.pendulum_2.theta += self.pendulum_2.theta_dot * self.dt def draw_pendulums(self): """Draw the two pendulums and the trace""" # Cartesian coordinates x1 = self.pendulum_1.length * m.sin(self.pendulum_1.theta) y1 = self.pendulum_1.length * m.cos(self.pendulum_1.theta) x2 = x1 + self.pendulum_2.length * m.sin(self.pendulum_2.theta) y2 = y1 + self.pendulum_2.length * m.cos(self.pendulum_2.theta) # Update the trace of the second pendulum self.trace_coords.append( ( self.offset_width + x2, self.offset_height + y2, self.offset_width + x2, self.offset_height + y2 ) ) # Draw the trace self.canvas.create_line(self.trace_coords, fill='black', tag='trace') # Draw the first pendulum self.canvas.create_line( self.offset_width, self.offset_height, self.offset_width + x1, self.offset_height + y1, width=self.pendulum_1.width, fill='pink', tags='pendulum' ) self.canvas.create_oval( self.offset_width - self.pendulum_1.mass + x1, self.offset_height - self.pendulum_1.mass + y1, self.offset_width + self.pendulum_1.mass + x1, self.offset_height + self.pendulum_1.mass + y1, fill='pink', outline='pink', tags='pendulum' ) # Draw the second pendulum self.canvas.create_line( self.offset_width + x1, self.offset_height + y1, self.offset_width + x2, self.offset_height + y2, width=self.pendulum_2.width, fill='pink', tags='pendulum' ) self.canvas.create_oval( self.offset_width - self.pendulum_2.mass + x2, self.offset_height - self.pendulum_2.mass + y2, self.offset_width + self.pendulum_2.mass + x2, self.offset_height + self.pendulum_2.mass + y2, fill='pink', outline='pink', tags='pendulum' ) def draw_frame(self): """Draw the current frame""" # Delete objects on the canvas to redraw self.canvas.delete('trace') self.canvas.delete('pendulum') # Update the positions and draw the frame self.update_pendulums_positions() self.draw_pendulums() # Repeat self.after(1, self.draw_frame) if __name__ == '__main__': # Initialization of the two pendulums theta1 = random.random() * 2 * m.pi theta2 = random.random() * 2 * m.pi pendulum_1_parameters = { "theta": theta1, "theta_dot": 0, "mass": 10, "length": 100, "width": 3 } pendulum_2_parameters = { "theta": theta2, "theta_dot": 0, "mass": 10, "length": 100, "width": 3 } pendulum_1 = Pendulum(**pendulum_1_parameters) pendulum_2 = Pendulum(**pendulum_2_parameters) # Run the animation animation_parameters = { "pendulum_1": pendulum_1, "pendulum_2": pendulum_2, "width": 600, "height": 600, "offset_width": 300, "offset_height": 150, "dt": 0.05 } app = App(**animation_parameters) app.mainloop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-07T04:40:16.317", "Id": "464211", "Score": "1", "body": "Looks great doesn't it! If you interested and for inspiration here is my double-pendulum project combining tkinter and matplotlib: https://codereview.stackexchange.com/questions/224472/double-pendulum-real-time-plot" } ]
[ { "body": "<p>It's hypnotic to watch them balacing!</p>\n\n<p>You assume the delta time is always 0,05sec. For a better simulation you should retrive real delta time.\nIn terms of code quality, in method update_pendulums_positions, your code will be heavily more readable if you use explicit variable names instead of \"num_\" something. Yeah, it's physics computation, but still, all computation has a meaning. Your code won't run slower if variable names are longer! (yes, already heard a coworker saying that for C++)</p>\n\n<p>You should also refactor some pieces, like:</p>\n\n<ul>\n<li><p>draw_pendulums: the create_line and create_oval are the same, just take pendulum as a parameter of a function</p></li>\n<li><p>computation of \"denom\" (denominator?): only the length change between the two of them</p></li>\n<li><p>updating velocities and positions: the two lines for each pendulum are the same</p></li>\n<li><p>cardinal coordinates, just add an (x,y) offset as a parameter to handle computation of the second pendulum depending on the coordinates of the first one</p></li>\n<li><p>num_3 and num_7: if I'm right, those two can be written as</p></li>\n</ul>\n\n<pre><code>num_3 = -2 * m.sin(self.pendulum_1.theta - self.pendulum_2.theta)\nnum_3 *= self.pendulum_2.mass * self.pendulum_2.theta_dot**2 * self.pendulum_2.length\nnum_3 *= 1 + m.cos(self.pendulum_1.theta - self.pendulum_2.theta)\n\nnum_7 = self.pendulum_2.mass * self.pendulum_2.theta_dot**2 * self.pendulum_2.length\nnum_7 *= m.cos(self.pendulum_1.theta - self.pendulum_2.theta)\n</code></pre>\n\n<p>You can see that some computations are done twice. Use intermediate variable to do those once. Your app is not heavy, but that would help to make something more scalable by optimizing your code.</p>\n\n<p>TL,DR: <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> and <a href=\"https://stackoverflow.com/questions/209015/what-is-self-documenting-code-and-can-it-replace-well-documented-code\">Self-documented code</a> (even though writing comments is a rule, it can't hurt to have a 'human-readable' code)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T02:26:12.337", "Id": "463577", "Score": "1", "body": "Instead of full answer, let me expand on the last line of @VincentRG. Looking at your comments, `draw_frame()` has the comment `Draw the current frame`. You could rename it to `draw_current_frame()` and throw away the comment. Comments cause future maintenance costs, like any other code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T16:27:46.020", "Id": "236500", "ParentId": "236491", "Score": "2" } } ]
{ "AcceptedAnswerId": "236500", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T11:11:16.930", "Id": "236491", "Score": "8", "Tags": [ "python", "object-oriented", "animation", "tkinter" ], "Title": "Double pendulum animation with tkinter" }
236491
<p>I have the following piece of code:</p> <pre><code>$Page = str_replace('-&amp;amp;-', '-[+]-', $Page); $Page = str_replace('&amp;amp;', '-[+]-', $Page); $Page = str_replace('-and-', '-[+]-', $Page); $Page = str_replace('-et-', '-[+]-', $Page); $Page = str_replace('-und-', '-[+]-', $Page); $Page = str_replace('-y-', '-[+]-', $Page); $Page = str_replace('-&amp;-', '-[+]-', $Page); </code></pre> <p>which I then run <strong>many times</strong> per page load (perhaps 10 to 40 times).</p> <blockquote> <p>N.B. <code>$Page</code> represents a URL fragment - rarely more than 20 characters long.</p> </blockquote> <p>Am I better off leaving it as it is, or may I, for the purposes of code maintenance, rewrite this code as:</p> <pre><code>$Page = preg_replace('/(-&amp;-|-&amp;amp;-|&amp;amp;|-and-|-et-|-und-|-y-)/', '-[+]-', $Page); </code></pre> <p>without suffering a slowdown of one or several hundredths of a second?</p> <p>(If the slowdown is a matter of milliseconds, I am less bothered).</p> <hr> <p><strong>Background:</strong></p> <p>I am less familiar with the evolution of PHP than with that of javascript, css etc. so when I see recommendations (long-stated, albeit from the late 2000s and early 2010s) like:</p> <blockquote> <p>Avoid <code>preg_replace</code> unless you need to use it and always use <code>str_replace</code> instead, which is an order of magnitude faster.</p> </blockquote> <p>I don't know if that recommendation still has any relevancy for <strong>PHP 7.3</strong> in 2020, or whether that recommendation was important to follow in the days of <strong>PHP 5</strong>, but is less of a concern now (given that <strong>PHP 7</strong> is so much faster and more optimised than its predecessor).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T11:24:12.693", "Id": "463542", "Score": "1", "body": "Oh dear. My first question on Code Review and downvoted already. Have I done something wrong? Is this the wrong sort of question for Code Review? Ta. I thought this sort of question was better to be asked here rather than over on Stack Overflow (?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T11:47:12.877", "Id": "463543", "Score": "0", "body": "I wish the could exaplain the vote" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T11:58:19.387", "Id": "463545", "Score": "3", "body": "The downvote my be because it reads as though you are asking about usage of a method, as opposed to an actual piece of code. If you are specifically concerned with the example you have given, then consider making that the focus of the question (since any feedback related to the code should be on-topic), or requesting a comparative review between the (concrete) examples. Stuff like \"should I use X instead of Y\" is simply not on-topic at Code Review: everything needs concrete context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T12:02:56.160", "Id": "463546", "Score": "0", "body": "Thanks. I have edited the question to make it clear that I am indeed asking about that specific piece of code (as well as questioning whether a piece of \"common knowledge\" relating to PHP performance is still accurate or now constitutes an old wive's tale)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T01:58:44.677", "Id": "463575", "Score": "1", "body": "Is this question off-topic because: **generic best practices are outside the scope of this site.**?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T11:51:34.240", "Id": "463600", "Score": "0", "body": "Hmm. The _SE Code Review Tour_ states I should ask questions about _\"The quality of your working code with regards to: **Best practices** and design pattern usage [... and...] Performance\"_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T08:34:18.523", "Id": "463684", "Score": "0", "body": "@Rou no, I wasn't being tongue in cheek. I'll also admit that I am still familiarizing myself with what should be closed here -- this is why I don't engage with the Review Queue. You state that this call will be run 30-40 times at a clip, but we don't know if `$Page` has 100 characters or 300,000 characters. This feels like an important factor in making an informed decision." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T09:35:13.567", "Id": "463695", "Score": "0", "body": "Ah, true. In this case `$Page` is a URL fragment - rarely more than 20 characters long - I'll add this relevant information to the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T10:46:19.767", "Id": "463705", "Score": "0", "body": "May we see 5 different realistic sample strings? Can we better understand why this replacement is necessary? Are you receiving this query string data and having to re-replace? Seems tedious. How about implementing `http_build_query()`? Is it 100% safe to consider `preg_replace('~-[^-]+-~', '&amp;', $Page)` before calling `http_build_query()`? Or is it crucial to target all of the \"and\" substrings? @Rou" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T11:33:12.860", "Id": "463711", "Score": "0", "body": "No, this is not related to query strings. The objective here is to maintain different (but mutually translatable) representations of the same core string which may then be used in unlimited contexts, eg. in PHP Associative Array Keys, URL Paths, HTML Attributes, CSS Classes, as plain text content in Headings, Menu Items etc." } ]
[ { "body": "<p>Most of such advises are crystal clear bullshit, on so many levels. You need to understand that such recommendations are never a result of some quality research, but just a rephrase of some vague rumor. <a href=\"https://security.stackexchange.com/a/33471/40115\">The internet is full of chimpanzees.</a> </p>\n\n<p>This particular advise didn't make any sense even for PHP5.</p>\n\n<p>That said, a set of consequent function calls apparently should be less efficient than a single call (but again if only it made any real life difference whatsoever). </p>\n\n<p>That said, str_replace accepts array arguments, so it can be </p>\n\n<pre><code>$Page = str_replace(['-&amp;-','-&amp;amp;-','&amp;amp;','-and-','-et-','-und-','-y-'], '-[+]-', $Page);\n</code></pre>\n\n<p>But you can use whatever version you like, as any difference is unnoticeable. Personally I find preg_replace() approach the cleanest and would prefer that. </p>\n\n<p>As a rule of thumb, do not trust some random pieces of advise from Internet, especially performance-related. It's always just random rubbish. Bother with any optimizations only if your code actually has performance issues. And even in this case do not optimize random irrelevant parts but find the actual bottleneck and optimize it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T12:09:16.417", "Id": "463547", "Score": "0", "body": "Thank you for an excellent and comprehensive answer. I didn't know that `str_replace` also accepts array arguments, so thanks for educating me on that, too." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T11:42:42.297", "Id": "236496", "ParentId": "236492", "Score": "6" } }, { "body": "<p>I am going to post my thoughts without using profanity or defame thousands of developers that I've never met. I hope this will not lessen the perceived value or correctness of this content.</p>\n<p>First things first, I think <strong>it is important to know all of the viable tools at your disposal with php</strong>. Yes, <code>str_replace()</code> and <code>preg_replace()</code> are the two widely used replacing functions, but do you also know about <a href=\"https://www.php.net/manual/en/function.strtr.php\" rel=\"nofollow noreferrer\">strtr()</a>? Through my own experiences supporting other developers in the Stack Exchange Network, it is clear to me that <code>strtr()</code> is a lesser known/used function. For the exact case that you have provided, it does not enjoy the most concise syntax, but it does make a single pass through the input string (like your piped <code>preg_replace()</code> call). This function has a special/useful behavior in that it will never replace replacements - this is sometimes an issue with the other two functions mentioned here. The truth is: due to the fact that your process has no risk of replacing replacements, the other functions are both adequate tools. <em>You have done well to order <code>&amp;amp</code> after\n<code>-&amp;amp;-</code>.</em></p>\n<p>Before I go any further, <strong>I will state my complete agreement with YCS about his advised solution.</strong> I would be using a single <code>str_replace()</code> call with an array of search strings. Assuming your project does not require word boundaries/lookarounds, case-sensitivity, or multibyte support, <code>str_replace()</code> is going to behave reliably and accurately.</p>\n<p>So how do you choose what is the best tool for your project? Well...</p>\n<ol>\n<li><p>Do you fully understand the coding technique and the fringe cases that may arise? <strong>Copy-pasting code that you don't understand will lead to a project that you cannot confidently maintain.</strong> If you understand it <em>now</em>, but might not <em>later</em> that is what comments / docblocks are for. When in doubt, read the php docs; when you have time, read the upvoted comments.</p>\n</li>\n<li><p>What is the scope/usage of the technique? <strong>If the data being processed is relatively small, is not iterated, and is not likely to be extended/expanded, then performance may never be an issue -- so toiling with benchmark tests will be a waste of dev time.</strong></p>\n<p>If there is <em>any</em> chance that the input data will be relatively large, that the process will be executed in a loop, or that the data may grow in size as your application matures, then you are going to want to <strong>pay a sensible amount of attention to performance</strong>.</p>\n</li>\n<li><p><strong>Do you (or your dev team or your supervisor) have a preconceived bias against regular expressions?</strong> Some people may laugh at this one, but it happens because of maintainability (see #1). When I use regular expressions in a team build and I know other members on the team do not have the same level of understanding that I do, I will include demo links from 3v4l.org and/or regex101.com so that other devs can understand the intricacies when maintenance is required.</p>\n</li>\n<li><p>Let's not forget one of the golden rules of string manipulation: do not use regex unless there is a clear and valuable benefit. <strong>The documentation is not telling lies -- <code>str_replace()</code> will always outperform with the same data.</strong> So make educated and purposeful choices and give future developers reason to be confident in your scripting abilities -- you might even inspire someone.</p>\n</li>\n</ol>\n<p>p.s. your regex doesn't need a capture group, so you can safely remove the parentheses.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T09:49:53.480", "Id": "463700", "Score": "0", "body": "Thank you for this well-thought-out response. As recommended, I have adopted `str_replace()` using an array of search strings as my approach." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T08:12:35.077", "Id": "236569", "ParentId": "236492", "Score": "4" } } ]
{ "AcceptedAnswerId": "236496", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T11:21:08.047", "Id": "236492", "Score": "4", "Tags": [ "performance", "php" ], "Title": "Do I need still to be concerned about favouring str_replace over preg_replace in PHP 7?" }
236492
<p>So I'm writing a big server and I've made a simple start on console commands. I'm not sure if the way I'm doing it in is correct so I'd like to have it reviewed.</p> <p>I have a class called <code>ServiceCollectionExtensions</code> where extension methods are defined that can be used on ServiceCollection. In there I have a function to register all console commands:</p> <pre><code>public static void RegisterConsoleCommands(this IServiceCollection serviceDescriptors) { serviceDescriptors.AddTransient&lt;ICommand, ClearCommand&gt;(); } </code></pre> <p>In my <code>Nordlys</code> class in my entry point, I have the following code:</p> <pre><code>IServiceCollection serviceDescriptors = new ServiceCollection(); serviceDescriptors.AddLogging(builder =&gt; builder.AddConsole()); serviceDescriptors.AddSingleton&lt;ConsoleCommandHandler&gt;(); serviceDescriptors.RegisterConsoleCommands(); </code></pre> <p>And at the end of the entry point I have this code to wait for user input:</p> <pre><code>while (true) { string input = await System.Console.In.ReadLineAsync(); if (input.Length &gt; 0) { await serviceProvider.GetService&lt;ConsoleCommandHandler&gt;().TryHandleCommandAsync(input); } } </code></pre> <p>And this is my ConsoleCommandHandler class:</p> <pre><code>public class ConsoleCommandHandler { private readonly ILogger&lt;ConsoleCommandHandler&gt; logger; private readonly Dictionary&lt;string, ICommand&gt; commands; public ConsoleCommandHandler(ILogger&lt;ConsoleCommandHandler&gt; logger, IEnumerable&lt;ICommand&gt; commands) { this.logger = logger; this.commands = commands.ToDictionary(command =&gt; command.Command); } public async Task TryHandleCommandAsync(string input) { int spacePosition = input.IndexOf(' '); string header = spacePosition &gt;= 0 ? input.Substring(0, spacePosition) : input; if (commands.Any(command =&gt; command.Key == header)) { await commands[header].RunAsync(input.Substring(spacePosition + 1).Split(' ')); } else { logger.LogWarning("'{0}' is not recognized as an internal command", header); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T00:43:39.890", "Id": "463666", "Score": "2", "body": "Is this working code? You should also include entry class as there is not enough context in the currently provided post to provide a meaningful review." } ]
[ { "body": "<p>If you're not using C# 8's <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references\" rel=\"nofollow noreferrer\">nullable references</a>, you should be checking for <code>null</code> whenever you're supplied with input.</p>\n\n<ul>\n<li>In the <code>ConsoleCommandHandler</code> constructor, throw <code>ArgumentNullException</code> if <code>logger</code> or <code>commands</code> is <code>null</code>.</li>\n<li>In <code>ConsoleCommandHandler.TryHandleCommandAsync</code>, throw <code>ArgumentNullException</code> if <code>input</code> is <code>null</code>. Even though you're only ever passing non-empty strings from your entry point, this method is publicly visible which sends a signal that anybody could potentially use it differently in the future.</li>\n</ul>\n\n<p>In <code>ConsoleCommandHandler</code>, you create a <code>Dictionary</code> that maps command names to <code>ICommand</code>s. You would do this if you wanted constant-time lookup of commands from command names. But then you wrote <code>commands.Any(command =&gt; command.Key == header)</code> which will instead do a linear search over every key-value pair in the dictionary until it finds a matching key. This defeats the purpose of using a dictionary. Use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.trygetvalue?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>TryGetValue</code></a> to check-and-retrieve a value from a dictionary in one shot:</p>\n\n<pre><code> if (commands.TryGetValue(header, out var command)\n {\n await command.RunAsync(input.Substring(spacePosition + 1).Split(' '));\n }\n else\n {\n logger.LogWarning(\"'{0}' is not recognized as an internal command\", header);\n }\n</code></pre>\n\n<p><code>TryHandleCommandAsync</code> really does two things -- it parses user input into a command + arguments, and then it finds/runs the associated command. It may be worth separating those concerns into methods. Then, if the format of those command strings ever changes then you'll know exactly where and what to change in the code.</p>\n\n<p>Depending on how sophisticated your command line interface needs to be, consider a <a href=\"https://github.com/commandlineparser/commandline\" rel=\"nofollow noreferrer\">third-party library</a> that does all the gross string parsing stuff for you. For example, do you need to support commands or arguments that contain spaces? Your implementation currently doesn't.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T22:38:00.263", "Id": "236611", "ParentId": "236503", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-01T19:05:58.293", "Id": "236503", "Score": "0", "Tags": [ "c#", "dependency-injection" ], "Title": "Console Commands with dependency injection (C#)" }
236503
<p>I'm basically wondering what the optimal method for returning to the top of <code>src/main.rs::main()</code> is? </p> <p>Maybe something like this:</p> <pre><code>mod main; pub fn main() { crate::main(); } </code></pre> <p>Or maybe there's a keyword built in?</p> <p>I want to handle certain kinds of errors by 'restarting the program'.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T02:00:07.660", "Id": "463576", "Score": "3", "body": "generally people use a loop" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T07:20:11.483", "Id": "463583", "Score": "0", "body": "@Stargateur Yes, I thought people might do something using returns and breaks (so some kind of loop), but I don't know how to reference it (for example should I search for \"main loop\"? What kind of book would I find this info in (like an algorithms book, or a basic programming patterns book)? I'm trying to break into programming, and I feel like I'm puzzling through every little thing like this after having finished reading the primer and going through its examples: just putting the pieces together is a much bigger challenge." } ]
[ { "body": "<p>There is a lot of way, I advice the simple one, use a loop:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>enum Error {\n A,\n}\n\nfn run() -&gt; Result&lt;(), Error&gt; {\n if rand::random() {\n Ok(())\n } else {\n Err(Error::A)\n }\n}\n\npub fn main() {\n while let Err(_) = run() {\n println!(\"Hello\");\n }\n}\n</code></pre>\n\n<p>However, be sure the program end maybe add a maximum fail counter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-03T01:17:57.923", "Id": "463669", "Score": "0", "body": "Thanks. I feel the program can end because: if a module fails in a specific way, I hope it returns to main. Picture a game where if you die at a specific time/place, you go back to the main menu. There are ways to succeed and ways to die that don't cause you to go back to the main menu (like find a save point)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T14:07:19.180", "Id": "236537", "ParentId": "236506", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T01:26:03.837", "Id": "236506", "Score": "1", "Tags": [ "rust" ], "Title": "Target src/main.rs::main()?" }
236506
<p>I am currently learning JAVA. I barely have any coding experience. I wrote a program which asks a user for a sentence. It then swaps the words of the sentence (first with last, second with second to last, etc.). Program will then output the new sentence. </p> <p>I know that this is not the most optimal way this task could be solved so please ignore that. My question is: <strong>"Do I use classes and methods correctly? If not, how would I adjust them in this code? In particular, I feel my main method looks weird (the way parameters are added to the methods)."</strong></p> <p>The code compiles and works as intended. My question is more in regards to style.</p> <p>I add the code, in 2 classes</p> <p>main class:</p> <pre><code>package com.test; public class ND2_Task1 { public static void main(String[] args) { ND2_Task1_Core run = new ND2_Task1_Core(); run.getInput(); // gets userSentence run.getWordCount(run.getUserSentence()); run.checkValidity(run.getWordCount()); run.toArray(run.getUserSentence()); // transforms String into an array run.reverseArray(run.getSeperatedSentence()); run.showResult(run.getSeperatedSentence()); } } </code></pre> <p>2nd. class:</p> <pre><code>package com.test; import java.util.Arrays; import java.util.Scanner; public class ND2_Task1_Core { private static String userSentence; private static int wordCount; private static String[] seperatedSentence; private static String[] reversedSentence; public void getInput() { System.out.println( "Please enter a sentence.\nFirst word will be swapped with the last one.\nSecond word will be swapped with second to last\netc."); setUserSentence(new Scanner(System.in).nextLine()); } public void getWordCount(String userSentence) { wordCount = 1; for (int i = 0; i &lt; userSentence.length(); i++) { if (userSentence.charAt(i) == ' ') { wordCount++; } } } public void checkValidity(int wordCount) { if (wordCount &lt; 2) { System.out.println( "You have entered an insufficient number of words. Enter at least 2 words for program to swap them"); System.out.println("Exiting now"); System.exit(0); } } public void toArray(String userSentence) { setSeperatedSentence(userSentence.split(" ")); } public void reverseArray(String[] seperatedSentence) { reversedSentence = new String[seperatedSentence.length]; reversedSentence = seperatedSentence; for (int i = 0; i &lt; reversedSentence.length / 2; i++) { String temp = reversedSentence[i]; reversedSentence[i] = reversedSentence[reversedSentence.length - i - 1]; reversedSentence[reversedSentence.length - 1 - i] = temp; } } public void showResult(String[] reversedSentence) { System.out.println(Arrays.toString(reversedSentence)); } public String getUserSentence() { return userSentence; } public void setUserSentence(String userSentence) { ND2_Task1_Core.userSentence = userSentence; } public String[] getSeperatedSentence() { return seperatedSentence; } public void setSeperatedSentence(String[] seperatedSentence) { ND2_Task1_Core.seperatedSentence = seperatedSentence; } public int getWordCount() { return wordCount; } public void setWordCount(int wordCount) { ND2_Task1_Core.wordCount = wordCount; } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T16:15:36.093", "Id": "463630", "Score": "1", "body": "If you're just starting, then it doesn't matter too much. Simple programs like this don't have an obvious \"correct\" way to write them. They're mostly procedural anyway and don't really benefit from object oriented design. When your assignments become more complex you'll see more opportunities to usefully use objects and breakdown code into structured design elements. One criticism is that you've put all your code into a single object, which is normally a poor choice. However the resulting object really isn't that complex, so it's fine." } ]
[ { "body": "<p>You seem to be under the impression that efficient code and good design are two separate things. A good design will help you write efficient code. </p>\n\n<p>In this particular case, you need to learn about separation of concern. Specifically what is the user concerned about and what should be handled by the class?</p>\n\n<p>The user basically just wants the words in the supplied string swapped. Everything else should be handled inside the class.</p>\n\n<p>In the class itself, you don't really need all those properties and helper methods. The main purpose of the code can easily be summed in one function. I would suggest a utility class(<code>StringUtils</code>?) with a public static function to swap the words and return a string.</p>\n\n<p>The solution could look like this:</p>\n\n<p>Main.java</p>\n\n<pre><code>import java.util.Scanner;\n\nclass Main {\n public static void main(String[] args) {\n String sentence;\n System.out.println(\n \"Please enter a sentence.\\nFirst word will be swapped with the last one.\\nSecond word will be swapped with second to last\\netc.\");\n try (Scanner sc = new Scanner(System.in)) {\n sentence = sc.nextLine(); \n } \n String swapped = StringUtils.swapWords(sentence);\n System.out.println(swapped);\n }\n}\n</code></pre>\n\n<p>StringUtils.java</p>\n\n<pre><code>public class StringUtils {\n\n public static String swapWords(String input) {\n String[] usersWords = input.split(\" \");\n if(usersWords.length &lt; 2){\n inputError();\n }\n String[] words = new String[usersWords.length];\n int mid = (words.length / 2) + 1;\n for (int front = 0, back = words.length - 1; front &lt; mid; ++front, --back) {\n words[front] = usersWords[back];\n words[back] = usersWords[front];\n }\n return String.join(\" \", words);\n }\n\n private static void inputError(){\n System.out.println(\n \"You have entered an insufficient number of words. Enter at least 2 words for program to swap them\");\n System.out.println(\"Exiting now\");\n System.exit(0); \n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T11:43:07.810", "Id": "236531", "ParentId": "236509", "Score": "3" } }, { "body": "<p>I have some suggestion for you.</p>\n<h1><code>ND2_Task1</code> class</h1>\n<p>Instead of adding comment near the methods calls, I suggest that you rename the method to a name that explains what it's doing and remove the comment. Also, most of the method that has parameters can be refactored to use the internal reference of the variable.</p>\n<p>The best way to do this, is to think the <code>ND2_Task1_Core</code> class as a container that doesn’t expose the variables with getter or setters, but instead have methods to handle the data directly, so the <code>ND2_Task1</code> class can use them.</p>\n<h2><code>getInput</code> Method</h2>\n<p>I suggest that you rename this method to <code>askAndStoreUserSentenceInput</code> and remove the comment.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ND2_Task1 {\n public static void main(String[] args) {\n //[...]\n ND2_Task1_Core run = new ND2_Task1_Core();\n run.askAndStoreUserSentenceInput();\n //[...]\n }\n}\n</code></pre>\n<h2><code>getWordCount</code> method</h2>\n<p>This method is more than a getter, since it updates the <code>wordCount</code>; the name can be confusing, I suggest <code>updateWordCount</code>.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ND2_Task1 {\n public static void main(String[] args) {\n //[...]\n ND2_Task1_Core run = new ND2_Task1_Core();\n run.updateWordCount();\n //[...]\n }\n}\n \n</code></pre>\n<h2><code>checkValidity</code> method</h2>\n<p>Same for other methods, you can remove the parameter and uses the local variable.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ND2_Task1 {\n public static void main(String[] args) {\n //[...]\n ND2_Task1_Core run = new ND2_Task1_Core();\n run.checkValidity();\n //[...]\n }\n}\n\npublic class ND2_Task1_Core {\n //[...]\n public void checkValidity() {\n if (wordCount &lt; 2) {\n System.out.println(&quot;You have entered an insufficient number of words. Enter at least 2 words for program to swap them&quot;);\n System.out.println(&quot;Exiting now&quot;);\n System.exit(0);\n }\n }\n //[...]\n}\n</code></pre>\n<h2><code>toArray</code> method</h2>\n<p>In my opinion, the name is confusing; since it does more than convert to an array (also set the result).</p>\n<p>Personally, I suggest that you make a new method called <code>convertUserSentence</code> in the class <code>ND2_Task1_Core</code> that handle the logic.</p>\n<p><strong>ND2_Task1</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ND2_Task1 {\n public static void main(String[] args) {\n //[...]\n run.convertUserSentence();\n //[...]\n }\n}\n</code></pre>\n<p><strong>ND2_Task1_Core</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ND2_Task1_Core {\n //[...]\n public void convertUserSentence() {\n String userSentence = getUserSentence();\n setSeperatedSentence(userSentence.split(&quot; &quot;));\n }\n //[...]\n}\n</code></pre>\n<h2><code>reverseArray</code> method</h2>\n<p>You can remove the parameter and uses the local variable and rename the name to <code>reverseSentenceArray</code>.</p>\n<p><strong>ND2_Task1</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ND2_Task1 {\n public static void main(String[] args) {\n //[...]\n run.reverseSentenceArray();\n //[...]\n }\n}\n</code></pre>\n<p><strong>ND2_Task1_Core</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ND2_Task1_Core {\n //[...]\n public void reverseSentenceArray() {\n for (int i = 0; i &lt; reversedSentence.length / 2; i++) {\n String temp = reversedSentence[i];\n reversedSentence[i] = reversedSentence[reversedSentence.length - i - 1];\n reversedSentence[reversedSentence.length - 1 - i] = temp;\n }\n }\n //[...]\n}\n</code></pre>\n<h2><code>showResult</code> method</h2>\n<p><strong>ND2_Task1</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ND2_Task1 {\n public static void main(String[] args) {\n //[...]\n run.showResult();\n //[...]\n }\n}\n</code></pre>\n<p><strong>ND2_Task1_Core</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ND2_Task1_Core {\n //[...]\n public void showResult() {\n System.out.println(Arrays.toString(reversedSentence));\n }\n //[...]\n}\n</code></pre>\n<h1><code>ND2_Task1_Core</code> class</h1>\n<ol>\n<li>The use of the <code>static</code> keyword on the variables is useless in this case, since you have only one instance of the class <code>ND2_Task1_Core</code>. The <code>static</code> is used to share the same value over all the instances of the same class.</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nprivate String userSentence;\nprivate int wordCount;\nprivate String[] seperatedSentence;\nprivate String[] reversedSentence;\n//[...]\n</code></pre>\n<ol start=\"2\">\n<li>Instead of creating a new instance of the <code>Scanner</code> each time you call the <code>getInput</code> method, I suggest that you store it in a variable.</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>public class ND2_Task1_Core {\n private Scanner scanner;\n\n public ND2_Task1_Core() {\n scanner = new Scanner(System.in);\n }\n\n public void getInput() {\n System.out.println(&quot;Please enter a sentence.\\nFirst word will be swapped with the last one.\\nSecond word will be swapped with second to last\\netc.&quot;);\n setUserSentence(scanner.nextLine());\n }\n}\n</code></pre>\n<h1>Refactored code</h1>\n<p><strong>ND2_Task1</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ND2_Task1 {\n public static void main(String[] args) {\n ND2_Task1_Core run = new ND2_Task1_Core();\n run.askAndStoreUserSentenceInput();\n run.updateWordCount();\n run.checkValidity();\n run.convertUserSentence();\n run.reverseSentenceArray();\n run.showResult();\n }\n}\n</code></pre>\n<p><strong>ND2_Task1_Core</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ND2_Task1_Core {\n private String userSentence;\n private int wordCount;\n private String[] seperatedSentence;\n private String[] reversedSentence;\n private Scanner scanner;\n\n public ND2_Task1_Core() {\n scanner = new Scanner(System.in);\n }\n\n public void askAndStoreUserSentenceInput() {\n System.out.println(&quot;Please enter a sentence.\\nFirst word will be swapped with the last one.\\nSecond word will be swapped with second to last\\netc.&quot;);\n setUserSentence(scanner.nextLine());\n }\n\n public void updateWordCount() {\n wordCount = 1;\n for (int i = 0; i &lt; userSentence.length(); i++) {\n if (userSentence.charAt(i) == ' ') {\n wordCount++;\n }\n }\n }\n\n public void checkValidity() {\n if (wordCount &lt; 2) {\n System.out.println(&quot;You have entered an insufficient number of words. Enter at least 2 words for program to swap them&quot;);\n System.out.println(&quot;Exiting now&quot;);\n System.exit(0);\n }\n }\n\n public void reverseSentenceArray() {\n for (int i = 0; i &lt; reversedSentence.length / 2; i++) {\n String temp = reversedSentence[i];\n reversedSentence[i] = reversedSentence[reversedSentence.length - i - 1];\n reversedSentence[reversedSentence.length - 1 - i] = temp;\n }\n }\n\n public void showResult() {\n System.out.println(Arrays.toString(reversedSentence));\n }\n\n public String getUserSentence() {\n return userSentence;\n }\n\n public void setUserSentence(String userSentence) {\n this.userSentence = userSentence;\n }\n\n public String[] getSeperatedSentence() {\n return seperatedSentence;\n }\n\n public void setSeperatedSentence(String[] seperatedSentence) {\n this.seperatedSentence = seperatedSentence;\n }\n\n public int getWordCount() {\n return wordCount;\n }\n\n public void setWordCount(int wordCount) {\n this.wordCount = wordCount;\n }\n\n public void convertUserSentence() {\n String userSentence = getUserSentence();\n setSeperatedSentence(userSentence.split(&quot; &quot;));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T17:39:29.357", "Id": "463644", "Score": "0", "body": "Thank you! This is exactly what I was looking for and it will help me improve my understanding of how coding works a lot!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T16:03:52.143", "Id": "236542", "ParentId": "236509", "Score": "2" } }, { "body": "<p>I'm agree with all considerations expressed by @tinstaafl in his <a href=\"https://codereview.stackexchange.com/a/236531/203649\">answer</a>, so I'm adding just two thoughts. </p>\n\n<p>First point: I noticed that you used the <code>Arrays</code> class in your code so if you want to reverse the String <code>words</code> array without any loop but just using the standard library you can do in one line with the help of <code>Collections</code> class like below:</p>\n\n<pre><code>Collections.reverse(Arrays.asList(words));\n</code></pre>\n\n<p>The cost is the creation of one <code>List</code> object , but it is a concise solution.</p>\n\n<p>Second point : you called your classes <code>ND2_Task1</code> and <code>ND2_Task1_Core</code> ; following the <a href=\"https://www.oracle.com/technetwork/java/codeconventions-135099.html\" rel=\"nofollow noreferrer\">java code conventions for class names</a>:</p>\n\n<blockquote>\n <p>Class names should be nouns, in mixed case with the first letter of\n each internal word capitalized.</p>\n</blockquote>\n\n<p>So you could rename them <code>Nd2Task1</code> and <code>Nd2Task1Core</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T16:54:06.513", "Id": "236544", "ParentId": "236509", "Score": "1" } } ]
{ "AcceptedAnswerId": "236542", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T03:00:32.137", "Id": "236509", "Score": "1", "Tags": [ "java" ], "Title": "Is this a correct way to utilize classes and methods in JAVA?" }
236509
<h3>The Task</h3> <p>A task I've been given recently is to design a data entry form which transfers data from the form to a table on a worksheet.<br> Depending on the answers given to various questions, other questions are displayed or hidden. For the most part I've achieved this by using different forms.<br> There is one route that requires a single form to ask too many questions to sit comfortably on the screen, so on my first build I figured out what I needed and am now working on various refactoring exercises. </p> <h3>What the code does</h3> <p>The class I've written handles the positioning and visibility of frames on the form. Frames added at design time can be moved, hidden or shown without ending up with empty spaces in the middle of the form. It only handles a single column of frames, so haven't added code where two frames might have the same Top value. When the class is initialised it makes a dictionary of all top level (that have the form as a parent) frames on the form.</p> <pre><code>Set FrameSorter = New cFrameSorter FrameSorter.Initialise Me </code></pre> <p>These frames can then be removed or added to the form, where they'll appear beneath the last visible frame. Their position on the form can be moved up, down or to a specified position.</p> <pre><code>FrameSorter.AddFrame Me.Frame1 FrameSorter.MoveUp Me.Frame1 FrameSorter.Move Me.Frame1, 2 FrameSorter.Remove Me.Frame1 </code></pre> <h3>Review</h3> <p>Open to all suggested improvements. Naming conventions, order of procedures, sub, function or property? Should I use an interface (never used one before), any ideas on how to have a subclass looking at frames within frames?<br> I know I haven't included any error handling yet - it's a first draft, so wanted to see all errors and handle the ones I could.</p> <h3>The Code</h3> <p>To use the code: </p> <ul> <li>Create a class named <code>cFrameSorter</code> </li> <li>Create a userform and add these controls: <ul> <li>a combobox named <code>cmbFrames</code></li> <li>a texbox named <code>txtPosition</code></li> <li>5 command buttons named: <code>cmdMoveFrame</code>, <code>cmdShowFrame</code>, <code>cmdHideFrame</code>, <code>cmdMoveFrameUp</code> and <code>cmdMoveFrameDown</code>. </li> <li>A few frames. The names don't matter and frames within frames will be ignored. Have a few visible and a few not. </li> </ul></li> </ul> <p>When the form opens it will populate the combo box with a list of frames - select a frame and click show/hide/up/down or add a number to the text box and click move.</p> <p>Add this code to the class module: </p> <pre><code>Option Explicit 'FrameDictionary contains all frames that have the form as the parent. 'VisibleFrames contain all frames within FrameDictionary that have a 'True Visible property in the order they appear. Private FrameDictionary As Dictionary Private VisibleFrames As Dictionary Private pStartPosition As Long Private pSpacer As Long Private Sub Class_Initialize() Set FrameDictionary = New Dictionary Set VisibleFrames = New Dictionary Me.StartPosition = 6 Me.Spacer = 10 End Sub 'The position of the first frame on the form. Public Property Get StartPosition() As Long StartPosition = pStartPosition End Property Public Property Let StartPosition(Value As Long) pStartPosition = IIf(Value &gt;= 0, Value, 0) End Property 'This is the distance between frames. Public Property Get Spacer() As Long Spacer = pSpacer End Property Public Property Let Spacer(Value As Long) pSpacer = IIf(Value &gt;= 0, Value, 0) End Property 'This property would not normally exist. 'It exists to populate the combo box on the UserForm. Public Property Get FrameDict() As Dictionary Set FrameDict = FrameDictionary End Property 'Adds a frame to the VisibleFrames dictionary providing 'it exists within the FrameDictionary. The frames Visible 'property is set to TRUE and it will appear beneath 'the last visible frame. Public Sub AddFrame(SourceFrame As Frame) If Not SourceFrame Is Nothing Then If FrameDictionary.Exists(SourceFrame.Name) Then With SourceFrame If Not VisibleFrames.Exists(.Name) Then .Visible = True VisibleFrames.Add .Name, SourceFrame ArrangeFrames End If End With End If End If End Sub 'The frame is removed from the VisibleFrames dictionary. 'The frames Visible property is set to FALSE and the 'remaining visible frames are rearranged to close any 'gaps left. Public Sub RemoveFrame(SourceFrame As Frame) If Not SourceFrame Is Nothing Then With SourceFrame If VisibleFrames.Exists(.Name) Then .Visible = False VisibleFrames.Remove (.Name) ArrangeFrames End If End With End If End Sub Public Sub MoveUp(SourceFrame As Frame, Optional Position As Long = 1) Dim lPosition As Long lPosition = GetPositionInDict(SourceFrame) If lPosition &gt; 1 Then MoveFrame SourceFrame, lPosition - 1 ArrangeFrames End If End Sub Public Sub MoveDown(SourceFrame As Frame, Optional Position As Long = 1) Dim lPosition As Long lPosition = GetPositionInDict(SourceFrame) If lPosition &gt; 0 And lPosition &lt; VisibleFrames.Count Then MoveFrame SourceFrame, lPosition + 1 ArrangeFrames End If End Sub Public Sub Move(SourceFrame As Frame, Position As Long) MoveFrame SourceFrame, Position ArrangeFrames End Sub 'Looks at each frame on the SourceForm. Any that have 'the form as a parent rather than another frame is added 'to the FrameDictionary. These represent the top level frames. ' 'As frames are looked at in the order they were added to the 'form the FrameDictionary is sorted using the Top property of 'each frame. ' 'Any frames with a TRUE visible property at design time are 'added to the VisibleFrames dictionary and are displayed in 'order when the form first opens. Public Sub Initialise(SourceForm As Object) Dim ctrl As Control Dim tmpSubSorter As cFrameSorter Dim vSortArray As Variant For Each ctrl In SourceForm.Controls If TypeName(ctrl) = "Frame" Then Select Case TypeName(ctrl.Parent) Case TypeName(SourceForm) With FrameDictionary If Not .Exists(ctrl.Name) Then .Add ctrl.Name, ctrl End If End With Case "Frame" 'Do nothing yet. End Select End If Next ctrl 'Sort the frames contained in the dictionary into 'order based on their Top property. vSortArray = FrameDictToArray(FrameDictionary) Sort2DArray vSortArray SortDictByArray vSortArray, FrameDictionary 'Create a dictionary of visible frames and then 'arrange them on the form in order. GetVisibleFrames ArrangeFrames End Sub 'Returns the ordinal position of a frame within the VisibleFrames dictionary. 'If the frame doesn't exist within the dictionary -1 is returned. Private Function GetPositionInDict(SourceFrame As Frame) As Long Dim vItem As Variant Dim x As Long If Not SourceFrame Is Nothing Then If VisibleFrames.Exists(SourceFrame.Name) Then For Each vItem In VisibleFrames.Items x = x + 1 If SourceFrame.Name = vItem.Name Then GetPositionInDict = x Exit For End If Next vItem Else GetPositionInDict = -1 End If End If End Function 'Populates the VisibleFrames dictionary with frames 'from the FrameDictionary that have a TRUE visible property. Private Sub GetVisibleFrames() Dim tmpDict As Dictionary Dim vItem As Variant If Not FrameDictionary Is Nothing Then If FrameDictionary.Count &gt; 0 Then Set tmpDict = New Dictionary For Each vItem In FrameDictionary.Items If vItem.Visible Then tmpDict.Add vItem.Name, vItem End If Next vItem End If End If Set VisibleFrames = tmpDict End Sub 'Moves a frames position within the VisibleFrames dictionary, 'to a specified position. 'If the required position is higher or lower than the number 'of frames then the highest or lowest value is used. Private Sub MoveFrame(SourceFrame As Frame, Position As Long) Dim tmpDict As Dictionary Dim vItem As Variant Dim x As Long If Not SourceFrame Is Nothing Then Set tmpDict = New Dictionary SourceFrame.Visible = True If Not VisibleFrames.Exists(SourceFrame.Name) Then VisibleFrames.Add SourceFrame.Name, SourceFrame End If If Position &gt; VisibleFrames.Count Then Position = VisibleFrames.Count ElseIf Position &lt; 0 Then Position = 0 End If If Position = VisibleFrames.Count Then VisibleFrames.Remove SourceFrame.Name VisibleFrames.Add SourceFrame.Name, SourceFrame Else VisibleFrames.Remove SourceFrame.Name For x = 0 To VisibleFrames.Count - 1 If x = Position - 1 Then tmpDict.Add SourceFrame.Name, SourceFrame End If tmpDict.Add VisibleFrames.Items(x).Name, VisibleFrames.Items(x) Next x Set VisibleFrames = tmpDict End If End If End Sub 'Positions the frames contained within the VisibleFrames dictionary on the 'parent form in the order they occur within the dictionary. Private Sub ArrangeFrames() Dim vItem As Variant Dim lTopRow As Long If Not VisibleFrames Is Nothing Then If VisibleFrames.Count &gt; 0 Then lTopRow = Me.StartPosition For Each vItem In VisibleFrames.Items vItem.Top = lTopRow lTopRow = lTopRow + vItem.Height + Me.Spacer Next vItem End If End If End Sub 'Sorts TargetDict dictionary in the order of the array. 'The vSortArray holds the frame names Private Sub SortDictByArray(vSortArray As Variant, TargetDict As Dictionary) Dim tmpDict As Dictionary Dim vItem As Variant Dim x As Long If Not TargetDict Is Nothing Then If UBound(vSortArray) = TargetDict.Count - 1 Then Set tmpDict = New Dictionary For x = LBound(vSortArray) To UBound(vSortArray) tmpDict.Add vSortArray(x, 1), TargetDict.Item(vSortArray(x, 1)) Next x Set TargetDict = tmpDict End If End If End Sub 'Takes the frame Top property and frame name to create 'an array from the SourceDictionary items. Private Function FrameDictToArray(SourceDict As Dictionary) As Variant Dim tmpDict As Dictionary Dim x As Long Dim tmpArr As Variant Dim itm As Variant If Not SourceDict Is Nothing Then If SourceDict.Count &gt; 0 Then Set tmpDict = New Dictionary ReDim tmpArr(0 To SourceDict.Count - 1, 0 To 1) For Each itm In SourceDict.Items tmpArr(x, 0) = itm.Top tmpArr(x, 1) = itm.Name x = x + 1 Next itm FrameDictToArray = tmpArr End If End If End Function 'Sorts the array using the frames Top property. Private Sub Sort2DArray(vArray As Variant, _ Optional ByVal lLowStart As Long = -1, _ Optional ByVal lHighStart As Long = -1) Dim vPivot As Variant Dim lLow As Long Dim lHigh As Long lLowStart = IIf(lLowStart = -1, LBound(vArray), lLowStart) lHighStart = IIf(lHighStart = -1, UBound(vArray), lHighStart) lLow = lLowStart lHigh = lHighStart vPivot = vArray((lLowStart + lHighStart) \ 2, 0) While lLow &lt;= lHigh While (vArray(lLow, 0) &lt; vPivot And lLow &lt; lHighStart) lLow = lLow + 1 Wend While (vPivot &lt; vArray(lHigh, 0) And lHigh &gt; lLowStart) lHigh = lHigh - 1 Wend If (lLow &lt;= lHigh) Then Swap vArray, lLow, lHigh lLow = lLow + 1 lHigh = lHigh - 1 End If Wend If (lLowStart &lt; lHigh) Then Sort2DArray vArray, lLowStart, lHigh End If If (lLow &lt; lHighStart) Then Sort2DArray vArray, lLow, lHighStart End If End Sub Private Sub Swap(vArray As Variant, lItem1 As Long, lItem2 As Long) Dim vTemp0 As Variant Dim vTemp1 As Variant vTemp0 = vArray(lItem1, 0) vTemp1 = vArray(lItem1, 1) vArray(lItem1, 0) = vArray(lItem2, 0) vArray(lItem1, 1) = vArray(lItem2, 1) vArray(lItem2, 0) = vTemp0 vArray(lItem2, 1) = vTemp1 End Sub </code></pre> <p>Add this code to the form: </p> <pre><code>Option Explicit Private FrameSorter As cFrameSorter Private Sub UserForm_Initialize() Dim vItem As Variant Set FrameSorter = New cFrameSorter FrameSorter.Initialise Me 'Populate the combobox. For Each vItem In FrameSorter.FrameDict.Items Me.cmbFrames.AddItem vItem.Name Next vItem End Sub Private Sub cmdHideFrame_Click() FrameSorter.RemoveFrame Me.Controls(Me.cmbFrames.Value) End Sub Private Sub cmdMoveFrame_Click() FrameSorter.Move Me.Controls(Me.cmbFrames.Value), CLng(Me.txtPosition) End Sub Private Sub cmdMoveFrameDown_Click() FrameSorter.MoveDown Me.Controls(Me.cmbFrames.Value) End Sub Private Sub cmdMoveFrameUp_Click() FrameSorter.MoveUp Me.Controls(Me.cmbFrames.Value) End Sub Private Sub cmdShowFrame_Click() FrameSorter.AddFrame Me.Controls(Me.cmbFrames.Value) End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-06T01:47:59.863", "Id": "464095", "Score": "0", "body": "Read [About Class Modules](https://rubberduckvba.wordpress.com/2019/07/08/about-class-modules/) and the other post and your knowledge will increase (try the addin too). Also [riptutorial.com](https://riptutorial.com/vba/example/3832/variable-names) shows why to avoid Hungarian Notation (yours just one char but usually unwanted) and many other tipps!." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-06T08:51:06.250", "Id": "464114", "Score": "1", "body": "Thanks for your feedback @ComputerVersteher. I'd love to install RubberDuck, but I only have my work laptop at the moment and they won't let me - hopefully that might change soon. I do get the point with naming variables after what they're used for, not what data type they are. I guess that's just a bad habit which I'm trying to get out of - I'm down to one character per variable. Bit like smoking I guess - I'm down to one a day on that too. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-06T09:36:23.190", "Id": "464122", "Score": "0", "body": "Have read the posts on Interfaces, etc.?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-06T10:07:44.713", "Id": "464127", "Score": "0", "body": "As no reviews (but votes, so basics match) till now, you can visit the rubberduck war room on chat (just search for rd) and leave a link. That may cause one of the knowing ones to notice your qoestion and review (my knowledge is not sufficent at now, as I am just reading through the blog and try to understand, when to use an interface)" } ]
[ { "body": "<p>The UserForm implemented here is specifically designed to demonstrate the CFrameSorter class functions. In doing so, the UI fulfills two roles: The CFrameSorter command initiator, and results viewer. In the actual system where the CFrameSorter is used, the CFrameSorter would most likely be commanded to Move and Hide Frames by a component other than the UI. That is a communication sequence something like: </p>\n\n<p>Application object(s)issue Frame manipulation commands ==> CFrameSorter(issues frame position and visibility commands) ==> FrameDisplayUI (View) places and shows Frames in response to CFrameSorter input. </p>\n\n<p>In the above sequence, the UI does not issue commands going right to left. The UI in this post (because it is a CFrameSorter tester/demonstrator) is playing the roles of both the Application and View. To prepare the CFrameSorter for use in your final system, making the visual test tool (the UserForm) better simulate the interactions described above is the theme for the following review. </p>\n\n<p>The primary comment is this: The UI in the final design should be completely unaware of the concrete object(s) that are manipulating it. This is also the goal of the TestUI. Currently, when the UserForm is first created, UserForm_Initialize is called. The first thing it does is:</p>\n\n<pre><code>Set FrameSorter = New CFrameSorter\nFrameSorter.Initialise Me\n</code></pre>\n\n<p>If these two commands were described in terms of human relationships, it would be the same as the UserForm telling the CFrameSorter, \"I know who you are and everything about you. You are more than a member variable to me. You...complete me\". In this scenario, interfaces is probaby the best way for the CFrameSorter to break out of this relationship \"and still be friends\".</p>\n\n<p>We want to remove any awareness of the CFrameSorter class from the View..and, unltimately, any awareness of the View, from the CFrameSorter. \"FrameSorter.Initialise Me\" has to go. We want to do this for a few reasons, but the primary reason is that in the final system, the CFrameSorter will not be taking frame positioning commands from the UI. It will be issued commands from one or more application objects. The simplest way to set this up here is to create a StandardModule (FrameSorterTester). It's job is to simulate the Application. It will create a CFrameSorter instance as well as the View instance. Add an entry point to initiate the testing.</p>\n\n<pre><code>Sub TestCFrameSorter()\n Dim frameSorter As CFrameSorter\n Set frameSorter = New CFrameSorter\n\n Dim testView As TestFrameSorterView\n Set testView = New TestFrameSorterView\n\n Load testView\n testView.Show\nEnd Sub\n</code></pre>\n\n<p>So, how to wire up the system if TestFrameSorterView is not to know anything about CFrameSorter class. Answer: Interfaces. Every VBA module that has Public subroutines, functions, or properties defines an interface. The interface is fundamentally a set of methods that define interactions. The implicit interface of CFrameSorter is:</p>\n\n<pre><code> Public Property Get StartPosition() As Long\n End Property\n\n Public Property Let StartPosition(Value As Long)\n End Property\n\n Public Property Get Spacer() As Long\n End Property\n\n Public Property Let Spacer(Value As Long)\n End Property\n\n Public Property Get FrameDict() As Dictionary\n End Property\n\n Public Sub AddFrame(SourceFrame As Frame)\n End Sub\n\n Public Sub RemoveFrame(SourceFrame As Frame)\n End Sub\n\n Public Sub MoveUp(SourceFrame As Frame, Optional Position As Long = 1)\n End Sub\n\n Public Sub MoveDown(SourceFrame As Frame, Optional Position As Long = 1)\n End Sub\n\n Public Sub Move(SourceFrame As Frame, Position As Long)\n End Sub\n\n Public Sub Initialise(SourceForm As Object)\n End Sub\n</code></pre>\n\n<p>As you can see, all that I've done is copied Public methods from CFrameSorter and deleted everything else. Now, create a new ClassModule \"IFrameSorter\" with the above empty methods in it...you've just created an interface. When an object (any object) 'implements' the IFrameSorter interface, it MUST provide logic behind every method of the interface - even if it is to raise an error that says \"Public Sub Move not implemented\" (for example). To 'force' CFrameSorter to implement IFrameSorter you add \"Implements IFrameSorter\" at the top of the CFrameSorter class module. This defines a set of methods that CFrameSorter MUST implement (it already has the logic). A simple search on 'Implement an Interface in Excel VBA' will provide the rest of the details to get to the following version of CFrameSorter:</p>\n\n<pre><code> Option Explicit\n\n Implements IFrameSorter\n\n\n Private FrameDictionary As Dictionary\n Private VisibleFrames As Dictionary\n Private pStartPosition As Long\n Private pSpacer As Long\n\n Private Sub Class_Initialize()\n Set FrameDictionary = New Dictionary\n Set VisibleFrames = New Dictionary\n pStartPosition = 6\n pSpacer = 10\n End Sub\n\n Private Property Let IFrameSorter_Spacer(RHS As Long)\n pSpacer = RHS\n End Property\n\n Private Property Get IFrameSorter_Spacer() As Long\n IFrameSorter_Spacer = pSpacer\n End Property\n\n Private Property Let IFrameSorter_StartPosition(RHS As Long)\n pStartPosition = RHS\n End Property\n\n Private Property Get IFrameSorter_StartPosition() As Long\n IFrameSorter_StartPosition = pStartPosition\n End Property\n\n Private Property Get IFrameSorter_FrameDict() As Scripting.IDictionary\n Set IFrameSorter_FrameDict = FrameDictionary\n End Property\n\n Private Sub IFrameSorter_AddFrame(SourceFrame As MSForms.IOptionFrame)\n If Not SourceFrame Is Nothing Then\n If FrameDictionary.Exists(SourceFrame.Name) Then\n With SourceFrame\n If Not VisibleFrames.Exists(.Name) Then\n .Visible = True\n VisibleFrames.Add .Name, SourceFrame\n ArrangeFrames\n End If\n End With\n End If\n End If\n End Sub\n\n Private Sub IFrameSorter_RemoveFrame(SourceFrame As MSForms.IOptionFrame)\n If Not SourceFrame Is Nothing Then\n With SourceFrame\n If VisibleFrames.Exists(.Name) Then\n .Visible = False\n VisibleFrames.Remove (.Name)\n ArrangeFrames\n End If\n End With\n End If\n End Sub\n\n Private Sub IFrameSorter_MoveUp(SourceFrame As MSForms.IOptionFrame, Optional Position As Long = 1&amp;)\n Dim lPosition As Long\n lPosition = GetPositionInDict(SourceFrame)\n If lPosition &gt; 1 Then\n MoveFrame SourceFrame, lPosition - 1\n ArrangeFrames\n End If\n End Sub\n\n Private Sub IFrameSorter_Move(SourceFrame As MSForms.IOptionFrame, Position As Long)\n MoveFrame SourceFrame, Position\n ArrangeFrames\n End Sub\n\n Private Sub IFrameSorter_MoveDown(SourceFrame As MSForms.IOptionFrame, Optional Position As Long = 1&amp;)\n Dim lPosition As Long\n lPosition = GetPositionInDict(SourceFrame)\n If lPosition &gt; 0 And lPosition &lt; VisibleFrames.Count Then\n MoveFrame SourceFrame, lPosition + 1\n ArrangeFrames\n End If\n End Sub\n\n Private Sub IFrameSorter_Initialise(SourceForm As Object)\n Dim ctrl As Control\n Dim tmpSubSorter As CFrameSorter\n Dim vSortArray As Variant\n For Each ctrl In SourceForm.Controls\n If TypeName(ctrl) = \"Frame\" Then\n Select Case TypeName(ctrl.Parent)\n Case TypeName(SourceForm)\n With FrameDictionary\n If Not .Exists(ctrl.Name) Then\n .Add ctrl.Name, ctrl\n End If\n End With\n Case \"Frame\"\n 'Do nothing yet.\n End Select\n End If\n Next ctrl\n 'Sort the frames contained in the dictionary into\n 'order based on their Top property.\n vSortArray = FrameDictToArray(FrameDictionary)\n Sort2DArray vSortArray\n SortDictByArray vSortArray, FrameDictionary\n 'Create a dictionary of visible frames and then\n 'arrange them on the form in order.\n GetVisibleFrames\n ArrangeFrames\n End Sub\n\n Private Function GetPositionInDict(SourceFrame As Frame) As Long\n Dim vItem As Variant\n Dim x As Long\n If Not SourceFrame Is Nothing Then\n If VisibleFrames.Exists(SourceFrame.Name) Then\n For Each vItem In VisibleFrames.Items\n x = x + 1\n If SourceFrame.Name = vItem.Name Then\n GetPositionInDict = x\n Exit For\n End If\n Next vItem\n Else\n GetPositionInDict = -1\n End If\n End If\n End Function\n\n Private Sub GetVisibleFrames()\n Dim tmpDict As Dictionary\n Dim vItem As Variant\n If Not FrameDictionary Is Nothing Then\n If FrameDictionary.Count &gt; 0 Then\n Set tmpDict = New Dictionary\n For Each vItem In FrameDictionary.Items\n If vItem.Visible Then\n tmpDict.Add vItem.Name, vItem\n End If\n Next vItem\n End If\n End If\n Set VisibleFrames = tmpDict\n End Sub\n\n Private Sub MoveFrame(SourceFrame As Frame, Position As Long)\n Dim tmpDict As Dictionary\n Dim vItem As Variant\n Dim x As Long\n If Not SourceFrame Is Nothing Then\n Set tmpDict = New Dictionary\n SourceFrame.Visible = True\n If Not VisibleFrames.Exists(SourceFrame.Name) Then\n VisibleFrames.Add SourceFrame.Name, SourceFrame\n End If\n If Position &gt; VisibleFrames.Count Then\n Position = VisibleFrames.Count\n ElseIf Position &lt; 0 Then\n Position = 0\n End If\n If Position = VisibleFrames.Count Then\n VisibleFrames.Remove SourceFrame.Name\n VisibleFrames.Add SourceFrame.Name, SourceFrame\n Else\n VisibleFrames.Remove SourceFrame.Name\n For x = 0 To VisibleFrames.Count - 1\n If x = Position - 1 Then\n tmpDict.Add SourceFrame.Name, SourceFrame\n End If\n tmpDict.Add VisibleFrames.Items(x).Name, VisibleFrames.Items(x)\n Next x\n Set VisibleFrames = tmpDict\n End If\n End If\n End Sub\n\n Private Sub ArrangeFrames()\n Dim vItem As Variant\n Dim lTopRow As Long\n If Not VisibleFrames Is Nothing Then\n If VisibleFrames.Count &gt; 0 Then\n lTopRow = pStartPosition\n For Each vItem In VisibleFrames.Items\n vItem.Top = lTopRow\n lTopRow = lTopRow + vItem.Height + pSpacer\n Next vItem\n End If\n End If\n End Sub\n\n Private Sub SortDictByArray(vSortArray As Variant, TargetDict As Dictionary)\n Dim tmpDict As Dictionary\n Dim vItem As Variant\n Dim x As Long\n If Not TargetDict Is Nothing Then\n If UBound(vSortArray) = TargetDict.Count - 1 Then\n Set tmpDict = New Dictionary\n For x = LBound(vSortArray) To UBound(vSortArray)\n tmpDict.Add vSortArray(x, 1), TargetDict.Item(vSortArray(x, 1))\n Next x\n Set TargetDict = tmpDict\n End If\n End If\n End Sub\n\n Private Function FrameDictToArray(SourceDict As Dictionary) As Variant\n Dim tmpDict As Dictionary\n Dim x As Long\n Dim tmpArr As Variant\n Dim itm As Variant\n If Not SourceDict Is Nothing Then\n If SourceDict.Count &gt; 0 Then\n Set tmpDict = New Dictionary\n ReDim tmpArr(0 To SourceDict.Count - 1, 0 To 1)\n For Each itm In SourceDict.Items\n tmpArr(x, 0) = itm.Top\n tmpArr(x, 1) = itm.Name\n x = x + 1\n Next itm\n FrameDictToArray = tmpArr\n End If\n End If\n End Function\n\n Private Sub Sort2DArray(vArray As Variant, _\n Optional ByVal lLowStart As Long = -1, _\n Optional ByVal lHighStart As Long = -1)\n\n Dim vPivot As Variant\n Dim lLow As Long\n Dim lHigh As Long\n\n lLowStart = IIf(lLowStart = -1, LBound(vArray), lLowStart)\n lHighStart = IIf(lHighStart = -1, UBound(vArray), lHighStart)\n lLow = lLowStart\n lHigh = lHighStart\n\n vPivot = vArray((lLowStart + lHighStart) \\ 2, 0)\n While lLow &lt;= lHigh\n While (vArray(lLow, 0) &lt; vPivot And lLow &lt; lHighStart)\n lLow = lLow + 1\n Wend\n\n While (vPivot &lt; vArray(lHigh, 0) And lHigh &gt; lLowStart)\n lHigh = lHigh - 1\n Wend\n\n If (lLow &lt;= lHigh) Then\n Swap vArray, lLow, lHigh\n lLow = lLow + 1\n lHigh = lHigh - 1\n End If\n Wend\n\n If (lLowStart &lt; lHigh) Then\n Sort2DArray vArray, lLowStart, lHigh\n End If\n If (lLow &lt; lHighStart) Then\n Sort2DArray vArray, lLow, lHighStart\n End If\n\n End Sub\n\n Private Sub Swap(vArray As Variant, lItem1 As Long, lItem2 As Long)\n Dim vTemp0 As Variant\n Dim vTemp1 As Variant\n vTemp0 = vArray(lItem1, 0)\n vTemp1 = vArray(lItem1, 1)\n vArray(lItem1, 0) = vArray(lItem2, 0)\n vArray(lItem1, 1) = vArray(lItem2, 1)\n vArray(lItem2, 0) = vTemp0\n vArray(lItem2, 1) = vTemp1\n End Sub\n</code></pre>\n\n<p>In order for the View to work with the interface, we will modify it as follows:\n(old code commented out)</p>\n\n<pre><code> 'Private FrameSorter As CFrameSorter\n Private frameSorter As IFrameSorter\n\n Private Sub UserForm_Initialize()\n 'Dim vItem As Variant\n\n 'Set FrameSorter = New CFrameSorter\n 'FrameSorter.Initialise Me\n\n 'Populate the combobox.\n 'For Each vItem In frameSorter.FrameDict.Items\n ' Me.cmbFrames.AddItem vItem.Name\n 'Next vItem\n\n End Sub\n\n Public Sub ApplyFrameSorter(sorter As IFrameSorter)\n Set frameSorter = sorter\n frameSorter.Initialise Me\n\n 'Populate the combobox.\n Dim vItem As Variant\n For Each vItem In frameSorter.FrameDict.Items\n Me.cmbFrames.AddItem vItem.Name\n Next vItem\n End Sub\n</code></pre>\n\n<p>And the FrameSorterTester module as follows:</p>\n\n<pre><code> Sub TestCFrameSorter()\n Dim frameSorter As IFrameSorter '&lt;=== declare the interface\n Set frameSorter = New CFrameSorter '&lt;== create the implementing object\n\n Dim testView As TestFrameSorterView\n Set testView = New TestFrameSorterView\n\n Load testView\n\n testView.ApplyFrameSorter frameSorter\n\n\n testView.Show\n End Sub\n</code></pre>\n\n<p>Initiating macro TestCFrameSorter will run your code and UI just as it did before.</p>\n\n<p>Although functionally equivalent, an important change has just occurred. The View no longer creates CFrameSorter. All that the View knows is that there is now a set of methods (the IFrameSorter interface) that it has access to. Now the relationship can be described as: (View to IFrameSorter): \"I don't know who you are, but you are more than an interface someone gave me. You...complete me\" </p>\n\n<p>Now, it is time to get rid of \"Initialise Me\" because is passes a UI element (itself) as the parameter. So, the task becomes: how to replace the functionality of <code>Initialise</code> without passing a reference to the <code>View</code> in the <code>IFrameSorter</code> interface methods. </p>\n\n<p>The <code>Initialise</code> subroutine basically looks at all the <code>Frame</code> controls on the <code>View</code> and loads its Dictionaries. <code>CFrameSorter</code> does not need the <code>UserForm</code> to do this - it only needs a collection of <code>Frame</code> objects. So, let the <code>View</code> provide a collection of <code>Frame</code> objects by adding a public property (read-only) <code>Frames</code>.</p>\n\n<pre><code> Public Property Get Frames() As Collection\n Dim myFrames As Collection\n Set myFrames = New Collection\n\n Dim ctrl As Control\n For Each ctrl In Me.Controls\n If TypeName(ctrl) = \"Frame\" Then\n Select Case TypeName(ctrl.Parent)\n Case TypeName(Me)\n myFrames.Add ctrl\n Case \"Frame\"\n 'Do nothing yet.\n End Select\n End If\n Next ctrl\n Set Frames = myFrames\n End Property\n</code></pre>\n\n<p>And replace/comment out <code>Initialise</code> on the <code>IFrameSorter</code> interface with a new method - \"LoadDictionaries\":</p>\n\n<pre><code> 'Remove Initialise from the interface and add LoadDictionaries\n 'Public Sub Initialise(SourceForm As Object)\n 'End Sub\n\n Public Sub LoadDictionaries(vFrames As Collection)\n End Sub\n</code></pre>\n\n<p>Removing <code>Initialise</code> from the <code>IFrameSorter</code> means that it can no longer be called from the <code>View</code>. Method <code>ApplyFrameSorter</code> is the current user of <code>Initialise</code>.</p>\n\n<p>In addition to setting the <code>IFrameSorter</code> variable, <code>ApplyFrameSorter</code> also loads the <code>ComboBox</code> items. So, a better name might have been \"<em>ApplyFrameSorterAndLoadComboBoxItems</em>\". But, that 'better' name betrays the fact that the method is doing two things. The <em>Single Responsibility Principle</em> (SRP) encourages us to always write methods that 'do one thing' - and the 'one thing' should be identified by the method's name. So, in the spirit of SRP...Let's add a public Property <code>FrameSorterInterface</code> to the <code>View</code> in order to set/get the <code>IFrameSorter</code> interface - one thing. And load the <code>ComboBox</code> (the second 'thing') some other way (Note: if we load the ComboBox as part of setting the property <code>FrameSorterInterface</code>, it would be considered an unadvertised <em>side-effect</em> of calling the property - always a good idea to avoid this). </p>\n\n<p>Loading the ComboBox items: The <code>ComboBox</code> can be loaded by the the <code>View</code>. There is no need to use the <code>IFrameSorter</code> interface to help do this. From the moment it is created, the <code>View</code> knows everything it needs (names of all the 'Frame' controls) in order to load the <code>ComboBox</code>. So, the code that loads the ComboBox items can be moved <em>back</em> into <code>UserForm_Initialize</code>. </p>\n\n<p>So now, property <code>FrameSorterInterface</code> and subroutine <code>UserForm_Initialize</code> are each doing one thing related to their names, and together, have replaced the functionality lost by removing <code>Initialise</code> from the <code>IFrameSorter</code> interface. The <code>View</code> code now looks like this:</p>\n\n<pre><code> 'TestFrameSorterView (UserForm) after removing \"Initialise\" from\n ' the IFrameSorter interface and adding property FrameSorterInterface\n\n Private Sub UserForm_Initialize()\n 'Populate the combobox.\n Dim vItem As Variant\n For Each vItem In Frames 'frameSorter.FrameDict.Items\n Me.cmbFrames.AddItem vItem.Name\n Next vItem\n End Sub\n\n Public Property Set FrameSorterInterface(sorter As IFrameSorter)\n Set frameSorter = sorter\n End Property\n\n Public Property Get FrameSorterInterface() As IFrameSorter\n Set FrameSorterInterface = frameSorter\n End Property\n</code></pre>\n\n<p>Now let the FrameSorterTester be responsible for managing the initialization transactions between the <code>CFrameSorter</code> and the <code>TestFrameSorterView</code>. The macro now looks like this:</p>\n\n<pre><code> Sub TestCFrameSorter()\n Dim frameSorter As IFrameSorter\n Set frameSorter = New CFrameSorter\n\n Dim testView As TestFrameSorterView\n Set testView = New TestFrameSorterView\n\n Load testView\n\n 'Provide the View with the IFrameSorterInterface\n Set testView.FrameSorterInterface = frameSorter\n\n 'Retrieve the Frame objects from the view and provide\n 'them to CFrameSorter so that it can load its dictionaries\n Dim vFrames As Collection\n Set vFrames = testView.Frames \n frameSorter.LoadDictionaries vFrames\n\n testView.Show\n End Sub\n</code></pre>\n\n<p>Again, after all that, from a functional perspective, nothing has changed. However, any awareness of the CFrameSorter class has been extracted from the View. It only knows that it can call the IFrameSorter interface and expect the right behavior. Further, CFrameSorter no longer knows about the TestFrameSorterView - it is handed a collection of Frame controls 'from somewhere' and initializes <em>itself</em>. So now (View to IFrameSorter): \"I don't know who you are, you are only an interface someone gave me. So, don't call me, I'll call you if (and only if) I want something\". The CFrameSorter now operates in a vacuum: \"I don't know where these Frame control references are coming from, but I'll do what I'm asked to do\".</p>\n\n<p>There is still more that can be done. The IFrameSorter interface accepts Frame control references in the method signatures. This means, that if you ever want any object to implement the IFrameSorter interface, it needs to be connected to a UI that will provide actual controls. This implies that there is no opportunity to test CFrameSorter without using an actual UI. A better version of the IFrameSorter interface eliminates UI control references.</p>\n\n<p>Removing the UI controls from the interface makes IFrameSorter independent of UI elements. Writing test code without an actual UI is now possible - and preferred. So, how to move the Frames without passing a <code>Frame</code> control reference?...again - an interface, but this interface is on the <code>View</code>. Let's call this new interface <code>IFrameSorterView</code>.</p>\n\n<p>So, the <code>IFrameSorter</code> will look something like:</p>\n\n<pre><code> Public Sub ShowFrame(frameName As String, IFrameSorterView view)\n End Sub\n\n Public Sub HideFrame(frameName As String, IFrameSorterView view)\n End Sub\n\n Public Sub MoveUp(frameName As String, IFrameSorterView view, Optional Position As Long = 1)\n End Sub\n\n Public Sub MoveDown(frameName As String, IFrameSorterView view, Optional Position As Long = 1)\n End Sub\n\n Public Sub Move(frameName As String, IFrameSorterView view, Position As Long)\n End Sub\n\n Public Sub LoadDictionaries(frameNames As Collection)\n End Sub\n</code></pre>\n\n<p>And <code>IFrameSorterView</code> can be something like:</p>\n\n<pre><code> Public Sub ModifyFramePosition(frameName As String, topValue As Long)\n End Sub\n\n Public Sub ModifyFrameVisibility(frameName As String, isVisible As Boolean)\n End Sub\n</code></pre>\n\n<p>There are a lot of details to sort out to implement these two interfaces. But the goal is to extract UI and UI controls awareness from <code>CFrameSorter</code>.</p>\n\n<p>Regarding the <code>CFrameSorter</code> code, there are a couple of Dictionaries that are storing position and visibility information. This replicates what is already stored and available from the <code>View</code>. So, there is probably an opportunity to eliminate the Dictionaries from <code>CFrameSorter</code> if the <code>IFrameSorterView</code> interface also includes some properties like:</p>\n\n<pre><code> Public Property Get Top(frameName As String) As Long\n End Property \n\n Public Property Get Height(frameName As String) As Long\n End Property\n\n Public Property Get IsVisible(frameName As String) As Boolean\n End Property \n</code></pre>\n\n<p>Or, collect them all at once...and let IFrameSorterView act as your dictionaries </p>\n\n<pre><code> 'Dictionary of Frame names to Top position values\n Public Property Get FrameNamesToTop() As Dictionary \n End Property \n\n 'Dictionary of Frame names to Visible values\n Public Property Get FrameNamesToIsVisible() As Dictionary \n End Property \n\n 'Dictionary of Frame names to Height values\n Public Property Get FrameNamesToHeight() As Dictionary\n End Property\n</code></pre>\n\n<p>Hope this was helpful. Good luck!</p>\n\n<p>I am certain that you will find <a href=\"https://rubberduckvba.wordpress.com/2017/10/\" rel=\"nofollow noreferrer\">this</a> useful for your task.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T22:25:19.260", "Id": "467104", "Score": "0", "body": "Thanks for your feedback. On first read it looks like you're explaining what I've been trying to get my head around for a while now. I'll have a better read through when I haven't got half a bottle of Jack inside me & get back to you. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T10:58:30.460", "Id": "467218", "Score": "0", "body": "Trying to work through this and have understood up to the point where you state \"_Initialise is gone from the interface, but the ComboBox was being loaded using the CFrameSorter. Let the View do this - it knows what Frames it has. Now ApplyFrameSorter can become a Property_\" - the code block below this is adding values to the combobox, although earlier in the answer you'd commented this out and moved it to the `ApplyFrameSorter` procedure. Should it still be commented out, or be in the `ApplyFrameSorter`? Feels like I was understanding it perfectly until I reached that point. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T15:40:59.963", "Id": "467255", "Score": "0", "body": "I've expanded the comments/explanations in that area. Hopefully it becomes more clear. And, to your specific question - I moved combo box loading out of `UserForm_Initialize` and then back _in_ to `UserForm_Initialize` as part of the step-by-step refactoring process that kept the code functioning after each set of modifications." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T09:22:34.230", "Id": "468252", "Score": "0", "body": "Have been working through your examples. It's slowly starting to click although I've still got a way to go. Again, thankyou for your feedback. It's definitely helped in taking my code to the next level." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T18:16:12.307", "Id": "238167", "ParentId": "236510", "Score": "3" } } ]
{ "AcceptedAnswerId": "238167", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T03:16:41.150", "Id": "236510", "Score": "5", "Tags": [ "vba", "excel" ], "Title": "Class to organise frames on an Excel userform" }
236510
<p>I would like to know if this is a good approach to finding out all the expressions within brackets. (I was actually asked to find out the smallest bracket expression, I have omitted the function to check for the smallest string and spaces within the expression).</p> <pre><code>s = "((a+b*d)*(x/2))*(1+(y+(x-2)/10))" b = [] j = 0 b.append(j) stack = [] for i in range(0, len(s)): if s[i] == '(': j = j + 1 b.append(j) b[j] = '' elif s[i] == ')': b[j] = b[j] + ')' stack.append(b[j]) j = j - 1 # 0 is omitted to exclude characters outside of brackets for k in range(1, j + 1): b[k] = b[k] + s[i] print(s) print(stack) </code></pre>
[]
[ { "body": "<p>Your code works, but is difficult to understand. Especially it is hard to understand what exactly is stored in <code>b</code>, this list contains both integers and strings. The name <code>b</code> also does not give a clue what it used for.</p>\n\n<p>I would suggest a more straight forward method with more descriptive names for variables:</p>\n\n<pre><code>s = \"((a+b*d)*(x/2))*(1+(y+(x-2)/10))\"\n\nopening_bracket_pos = []\nstack = []\n\nfor i in range(0, len(s)):\n if s[i] == '(':\n opening_bracket_pos.append(i)\n elif s[i] == ')':\n start_pos = opening_bracket_pos.pop()\n stack.append(s[start_pos: i+1])\n\nprint(s)\nprint(stack)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T11:30:13.230", "Id": "463596", "Score": "0", "body": "Thank you for your review, Jan. Also, thanks for the pop line. It reduced the need for an additional loop which I made with k. Question : How can I measure which one is faster ? time python3 brackets.py gives 0 seconds." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T08:52:31.063", "Id": "236521", "ParentId": "236511", "Score": "0" } } ]
{ "AcceptedAnswerId": "236521", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-02T04:25:13.123", "Id": "236511", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Smallest expression within brackets" }
236511