body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I passed a technical test the other day, one part included a cheap string validation and I am wondering this can be further improved to be more versatile to requirement changes.</p> <p>The requirements were something like that </p> <blockquote> <p>Create a <code>Validate</code> method, which accepts a string and returns <code>true</code> if it's valid and <code>false</code> if it's not.</p> <p>A string is valid if it satisfies the rules below:</p> <ul> <li>The string must be at least 6 characters long and not exceed 16 characters.</li> <li>The string must contain only letters, numbers and optionally one hyphen (-).</li> <li>The string must start with a letter, and must not end with a hyphen. For example, <code>validate("Michelle Belle");</code> would return false because it contains a space.</li> </ul> </blockquote> <p>My solution was like that:</p> <pre><code>public static class ComparableExtensions { public static bool IsStrictlyLowerThan&lt;TComparable&gt;(this TComparable comparable, TComparable value) where TComparable : IComparable&lt;TComparable&gt; { return comparable.CompareTo(value) &lt; 0; } public static bool IsStrictlyGreaterThan&lt;TComparable&gt;(this TComparable comparable, TComparable value) where TComparable : IComparable&lt;TComparable&gt; { return comparable.CompareTo(value) &gt; 0; } public static bool IsStrictlyNotBetween&lt;TComparable&gt;(this TComparable comparable, TComparable lowerBound, TComparable upperBound) where TComparable : IComparable&lt;TComparable&gt; { if (lowerBound.IsStrictlyGreaterThan(upperBound)) { throw new ArgumentOutOfRangeException(nameof(lowerBound) + nameof(upperBound)); } return comparable.IsStrictlyLowerThan(lowerBound) || comparable.IsStrictlyGreaterThan(upperBound); } } public static class CharExtensions { public static bool IsLetterOrDigit(this char c) { return char.IsLetterOrDigit(c); } public static bool IsLetter(this char c) { return char.IsLetter(c); } public static bool IsHyphen(this char c) { return c == '-'; } } public class Test { public static bool Validate(string str) { if (str.Length.IsStrictlyNotBetween(6, 16)) { return false; } if (!str.First().IsLetter() || str.Last().IsHyphen()) { return false; } var hyphenCount = 0; for (var i = 1; i &lt; str.Length - 1; i++) { if (str[i].IsLetterOrDigit()) { continue; } if (str[i].IsHyphen()) { hyphenCount++; if (hyphenCount &gt; 1) { return false; } } else { return false; } } return true; } } </code></pre> <p>I purposefully decided to not go with Regular Expressions to keep the logic readable and I am wondering if my code can be further refactored to incorporate new business rules.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:34:31.107", "Id": "410797", "Score": "0", "body": "I'd be good idea to take a look a this question [Enforcing string validity with the C# type system](https://codereview.stackexchange.com/questions/208291/enforcing-string-validity-with-the-c-type-system) and its answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:52:50.433", "Id": "410800", "Score": "1", "body": "Would the regular expression for these rules really be that unreadable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:56:21.150", "Id": "410801", "Score": "0", "body": "@t3chb0t I am gonna check this out, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:56:51.780", "Id": "410802", "Score": "0", "body": "@Kenneth K well at the beginning it's fine but if it starts piling up new business rules it can be a pain to go through all of them" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:07:44.000", "Id": "410804", "Score": "6", "body": "Why do you have all of those \"extentions\"? They make the code way harder to read! `IsHyphen`? `IsStrictlyGreaterThan`? Why? Just write `== '-'` in the code itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:53:35.177", "Id": "410823", "Score": "0", "body": "@ToddSewell for the grand sake of consistency ;-), I was thinking the solution as a starter for new business rules which would also leverage extension methods, and trying to make specification pattern somehow emerge from that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T23:05:22.883", "Id": "410872", "Score": "2", "body": "Your solution reminds me of the [Enterprise Rules Engine](https://thedailywtf.com/articles/The_Enterprise_Rules_Engine). (That is not a good thing.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T01:44:52.130", "Id": "410889", "Score": "1", "body": "@EhouarnPerret yeah, please as little extra code as possible (YAGNI). those extension methods have similar names, so sure, they're kinda readable, but considering they do very little, I'd say you should leave them out in this case" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T12:38:39.520", "Id": "410963", "Score": "1", "body": "To me, this huge overkilling with the comparables and charextentions makes it very unreadable." } ]
[ { "body": "<p>Not much to say about the extensions methods, as they are mostly wrappers.</p>\n\n<p>However if you're looking for ways to make the algorithm more readable, LINQ is your friend. You can replace most of your logic with a one-liner:</p>\n\n<blockquote>\n<pre><code>var hyphenCount = 0;\n\nfor (var i = 1; i &lt; str.Length - 1; i++)\n{\n if (str[i].IsLetterOrDigit())\n {\n continue;\n }\n if (str[i].IsHyphen())\n {\n hyphenCount++;\n if (hyphenCount &gt; 1)\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n}\n\nreturn true;\n</code></pre>\n</blockquote>\n\n<p>Like this:</p>\n\n<pre><code>return str.All(c =&gt; c.IsHyphen() || c.IsLetterOrDigit()) &amp;&amp; str.Count(c =&gt; c.IsHyphen()) &lt;= 1;\n</code></pre>\n\n<p>Which more clearly explains your intent, you can also move those expression to their separate methods to make it as readable as possible, this way you can keep adding new conditions, without modifying the existing logic (unless they interfere with one another that is).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T14:27:52.487", "Id": "212382", "ParentId": "212381", "Score": "7" } }, { "body": "<ul>\n<li>There's a bug: you're not checking if the last character is a letter or digit, only that it isn't a hyphen, so this fails to reject <code>\"abcdef&amp;\"</code>. Denis' solution may be less efficient (2 iterations instead of 1), but with at most 16 characters that's not much of a concern, and it's both easier to read and it works correctly.</li>\n<li>The first two rules read very nicely. I especially like that the business rules are translated to code almost 1:1, that will make updating easier. However, I do think those extension methods are over-engineered. <code>str.Length &lt; 6 || str.Length &gt; 16</code> and <code>!char.IsLetter(str.First()) || str.Last() == '-'</code> is already quite readable, and that doesn't require extra code that needs to be understood and maintained.</li>\n<li>You can use <code>=&gt;</code> syntax for methods with single-expression bodies.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:05:29.250", "Id": "410780", "Score": "0", "body": "I agree on the extension methods part, another positive for using standard types and methods is that, experienced developers, know right away the way they function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:13:33.760", "Id": "410784", "Score": "0", "body": "@Pieter Witvoet true, my bad, wrong copy and paste =/" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T14:53:55.090", "Id": "212385", "ParentId": "212381", "Score": "8" } }, { "body": "<p>About versatility my thought is a separate class to stipulate the different possible rules:</p>\n\n<pre><code>class ValidationRules\n{\n public const char HYPHEN = '-';\n public readonly int hyphenCount;\n public readonly bool needUpper;\n public readonly bool needLower;\n public readonly bool needDigit;\n public readonly bool allowSpaces;\n public readonly int minLength;\n public readonly int maxLength;\n /// &lt;summary&gt;\n /// Constructor with min and max length and default rules:\n /// needUpper = true\n /// needLower = true\n /// allowSpaces = false\n /// hyphenCount = 1;\n /// &lt;/summary&gt;\n public ValidationRules(int minLength, int maxLength)\n {\n this.minLength = minLength;\n this.maxLength = maxLength;\n hyphenCount = 1;\n needLower = true;\n needUpper = true;\n needDigit = true;\n allowSpaces = false;\n }\n /// &lt;summary&gt;\n /// Constructor with min and max length and supplied rules:\n /// &lt;/summary&gt;\n public ValidationRules(int minLength, int maxLength, int hyphenCount, bool needUpper, bool needLower, bool needDigit, bool allowSpaces)\n {\n this.minLength = minLength;\n this.maxLength = maxLength;\n this.hyphenCount = hyphenCount;\n this.needLower = needLower;\n this.needUpper = needUpper;\n this.needDigit = needDigit;\n this.allowSpaces = allowSpaces;\n }\n}\n</code></pre>\n\n<p>the method to validate is still quite simple:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Validate string according to validation rules\n/// &lt;/summary&gt;\n/// &lt;returns&gt;&lt;/returns&gt;\npublic static bool Validate(string input,ValidationRules rules)\n{\n if(input.Length &lt; rules.minLength || input.Length &gt; rules.maxLength)\n {\n return false;\n }\n if(!Char.IsLetter(input[0]) || input[input.Length-1] == ValidationRules.HYPHEN)\n {\n return false;\n }\n return input.Count(x =&gt; x == ValidationRules.HYPHEN) &lt;= rules.hyphenCount &amp;&amp; input.All(x =&gt; \n (rules.needUpper &amp;&amp; char.IsUpper(x)) || \n (rules.needLower &amp;&amp; char.IsLower(x)) || \n (rules.allowSpaces &amp;&amp; char.IsWhiteSpace(x)) ||\n (rules.needDigit &amp;&amp; char.IsDigit(x)) ||\n (x == ValidationRules.HYPHEN));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:11:38.527", "Id": "410782", "Score": "0", "body": "I like your approach!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:17:00.350", "Id": "410786", "Score": "0", "body": "For an approach that targets extendability, it will quickly become a mini god class, requiring changes on several different locations. Multiple types with a single visitor would be much better off SOLID and elegance-wise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:27:35.280", "Id": "410794", "Score": "0", "body": "@Denis actually I was thinking about a set of rules that could be built out of a builder: https://github.com/JeremySkinner/FluentValidation" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:30:33.420", "Id": "410795", "Score": "2", "body": "@EhouarnPerret That's similar to what I meant, but this implementation would add way too much overhead for such a simple task, if it were an interview question, you should also consider time. Show off some techniques but don't overdo it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:09:55.670", "Id": "212386", "ParentId": "212381", "Score": "1" } }, { "body": "<p>I think you've seen enough alternative solutions so I'll just review your code.</p>\n\n<ul>\n<li>You should not invent new terms for <code>x &lt; 0</code> like <code>IsStrictlyLowerThan</code> as this makes things unnecessarily more difficult to understand. Instead, you should stick to the well known naming. In this case that would be <code>IsLessThan</code> or in case of <code>x &lt;= 0</code> it would be <code>IsLessThanOrEqual</code> - Everyone who write code would understand these without any further explanation. Or in case of <code>IsStrictlyNotBetween</code> should be <code>IsNotInRangeExclusive</code> etc.</li>\n<li>There are voices in comments that suggest using <code>== '-'</code> instead of your extensions. I don't agree with that. Your extensions are much better because they make the code look clean and consistent. Having extensions for some operations and not for others would make it look dirty.</li>\n<li>I don't however agree with your decision for not using Regex. With regex it's usually simpler and easier to express complex validations. It's also easier to make your validations case-insensitive or match other patterns or use such services as <a href=\"https://regex101.com\" rel=\"noreferrer\">regex101.com</a> to test them. It might be enough for now but sooner or later you will need it so don't be so strict about always consider other solutions.</li>\n<li><p>Keep also in mind that your <code>IsStrictlyLowerThan</code> APIs are currently case sensitive so you might consider using <code>IEqualityComparer&lt;string&gt;</code> as the last argument and not the <code>TComparable</code> that doesn't offer you any additional functionality in this context. So your API should have signatures similar to this one:</p>\n\n<pre><code>public static bool IsLessThan(this string value, string other, IComparer&lt;string&gt; comaprer = default)\n{\n return (comaprer ?? StringComparer.Ordinal).Compare(value, other) &lt; 0;\n}\n</code></pre>\n\n<p>Then you can use it with other comparers if necessary, e.g.:</p>\n\n<pre><code>\"FOO\".IsLessThan(\"foo\", StringComparer.OrdinalIgnoreCase)\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:32:36.883", "Id": "212399", "ParentId": "212381", "Score": "5" } }, { "body": "<p>Little bit late but let me add <em>another</em> alternative solution, t3chb0t already took care of your code.</p>\n\n<p>You have extension methods for <code>IComparable&lt;T&gt;</code> and <code>Char</code>, this forces you to write your <em>business logic</em> in code instead of a (pseudo) high-level language which resembles your business rules. If you do not want to use a regular expression (I'd use it) then you should try to match 1:1 the language of your requirements:</p>\n\n<pre><code>StringValidator.Validate(str)\n .LengthIsInRange(6, 16)\n .ContainsOnly(Matches.LetterOrDigits, Matches.Hyphen).HasAtMost(1, Matches.Hyphen)\n .StartsWith(Matches.Letter)\n .DoesNotEndWith(Matches.Hyphen);\n</code></pre>\n\n<p>This is simple enough to be self-describing. Does it hurt performance? Maybe but it's seldom a problem in LoB applications and business rules can become incredibly convoluted. Is it a problem? Measure it, for performance critical code it's easy to write an extension method (for <code>StringValidator</code>) to perform a specific task. </p>\n\n<p>Note that I'm using an hypothetical <code>Matches.LetterOrDigits()</code> function with <code>string -&gt; bool</code> signature instead of, let's say, <code>Char.IsLetterOrDigit()</code> with <code>char -&gt; bool</code>. Why? Because not every <em>character</em> (OK, I won't repeat this again...) is a single <code>Char</code> then you have to compare strings (few examples: <kbd>à</kbd> or <kbd>dž</kbd> or <kbd></kbd>).</p>\n\n<p>Your <strong>requirements are, probably, vague</strong> and your code broken regardless the interpretation you picked. What do they mean with <em>letter</em>? An US-ASCII Latin character? In that case your code is wrong because <kbd>ā</kbd> (LATIN SMALL LETTER A MACRON) is accepted. Is is a <em>letter</em> everything in the <em>Letter</em> Unicode category (or even just in the <em>Latin Extended</em> Unicode block)? Your code is wrong again because <kbd>ā</kbd> (LATIN SMALL LETTER A + COMBINING MACRON) is rejected. This very example can be solved normalizing the string before starting the validation but it's not always that easy.</p>\n\n<p>Imagine that instead of a single validation rule you have...1,000 of them. Or 10,000. I'm not a fan of extension method for primitive types (especially when they're trivial) but the <em>mistake</em> (IMHO) is to work with a <strong>too low level of abstraction</strong>: you do not want to <em>extend</em> <code>String.Length</code> to replicate what <code>&gt;</code> does: you want to extend <code>String</code> to support high level composable and chainable assertions.</p>\n\n<p>Note: <code>ContainsOnly()</code> may even accept regexes, pseudo code:</p>\n\n<pre><code>static ContainsOnly(this StringValidator validator, ...string[] matches) =&gt; ...\n\nstatic class Matches {\n public static string LetterOrDigit = \"a-zA-Z0-9\";\n}\n</code></pre>\n\n<p>Composition should now be fast enough even when you cannot really ignore performance (and you can always have a <code>MatchRegEx()</code> extension method).</p>\n\n<hr>\n\n<p>How to extend this? In previous example I assumed a pseudo-implementation like this:</p>\n\n<pre><code>public StringValidator LengthInRange(int min, int max) {\n if (IsValid) {\n IsValid = Value.Length &gt;= min &amp;&amp; Value.Length &lt;= max;\n }\n\n return this;\n}\n</code></pre>\n\n<p>You can easily extend it to run all validators to generate a list of errors:</p>\n\n<pre><code>var result = StringValidator.Validate(str)\n .LengthIsInRange(6, 16)\n .StartsWith(Matches.Letter)\n .DoesNotEndWith(Matches.Hyphen);\n\nif (result.HasErrors)\n Console.WriteLine(String.Join(Environment.NewLine, result.Errors));\n</code></pre>\n\n<p>Or to throw an exception:</p>\n\n<pre><code>StringValidator.Validate(str)\n .LengthIsInRange(6, 16)\n .StartsWith(Matches.Letter)\n .DoesNotEndWith(Matches.Hyphen)\n .ThrowIfInvalid();\n</code></pre>\n\n<p>I think you've got the point.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T18:27:40.663", "Id": "410842", "Score": "1", "body": "So if, for example, length is not between 6 and 16 this throws an exception?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T19:09:49.420", "Id": "410846", "Score": "1", "body": "No as per requirements it should return false (the other validators simply fall through after the first one marked the result as invalid?). You can throw explicitly or with an option in `Configure()` or with a call to `ThrowIfInvalid()`. For a future requirement it may add an `IEnumerable<string>` property to collect all errors (for example)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T18:09:19.077", "Id": "212411", "ParentId": "212381", "Score": "7" } }, { "body": "<p>Stop it. Just stop it. Unless you have some kind of unusual performance requirements, <strong>keep it simple</strong>:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Regular expression pattern that matches strings containing only Unicode\n/// letters, digits, and hyphens.\n/// &lt;/summary&gt;\npublic static Regex AllUnicodeLettersNumsHyphen = new Regex(@\"^[\\p{L}\\p{Nd}-]*$\");\n\npublic static bool IsValid(string s)\n{\n return (\n s.Length &gt;= 6 &amp;&amp; s.Length &lt;= 16\n &amp;&amp; AllUnicodeLettersNumsHyphen.IsMatch(s)\n &amp;&amp; s.Count(c =&gt; c == '-') &lt;= 1\n &amp;&amp; Char.IsLetter(s, 0)\n &amp;&amp; s[s.Length - 1] != '-'\n );\n}\n</code></pre>\n\n<p>(Those parentheses are optional. I find them visually appealing. Follow your group's coding guidelines on style choices like that.)</p>\n\n<p>Given the requirements you specify, there's no reason for loops, extension methods, or <em>any</em> of that stuff. I promise you that 2 years down the line, anyone reading this code (including you!) will be much happier understanding the 5 liner than your code. The smaller the scope the better when you're reading. It will take someone 30 seconds to fully understand these 6 lines of code. It will take 10 minutes to dive through all yours.</p>\n\n<p>And this isn't any less flexible. In fact it's more so. You can trivially add new rules to this 6 line method. That is <em>not</em> the case with your code. Your patterns require adding 20 extra lines of boilerplate that then has to be tested and presents more opportunities for mistakes.</p>\n\n<p>And look how I dealt with the regular expression impenetrability: </p>\n\n<ul>\n<li>Encode as many rules as possible outside the regex.</li>\n<li>Only use one fairly simple, <em>appropriately named and documented</em> regex for just the one check: that it matches the character classes. That and a comment are all you need.</li>\n</ul>\n\n<hr>\n\n<p>If you are completely dead set against regular expressions, consider this LINQ based alternative:</p>\n\n<pre><code>public static bool IsValid(string s)\n{\n return (\n s.Length &gt;= 6 &amp;&amp; s.Length &lt;= 16\n &amp;&amp; s.All(c =&gt; Char.IsLetterOrDigit(c) || '-' == c)\n &amp;&amp; s.Count(c =&gt; c == '-') &lt;= 1\n &amp;&amp; Char.IsLetter(s, 0)\n &amp;&amp; s[s.Length - 1] != '-'\n );\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T23:30:17.447", "Id": "410874", "Score": "0", "body": "I'd tend to agree to use a single regex but in that case everything can be expressed with a single regex without any other surrounding code (including the length and the first/last character)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T23:33:54.747", "Id": "410876", "Score": "0", "body": "@AdrianoRepetti Yes, but then it's not simple anymore. Putting most of these checks outside the regex vastly improves readability for very little cost." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T23:38:39.333", "Id": "410877", "Score": "1", "body": "Hmmmmm POV, I guess. To me a well written regex can express clearly the requirement while `UnicodeLettersNumsHyphen` has the _disadvantages_ of regexes (less easy to write and read) without its advantages (concise, fast and complete). Nitpick: I'd change `UnicodeLettersNumsHyphen` to a meaningful name because you can't understand what the regex is for without fully _decoding_ it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T23:43:19.283", "Id": "410879", "Score": "0", "body": "@AdrianoRepetti I added documentation instead of making the name too complicated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T23:56:00.303", "Id": "410881", "Score": "0", "body": "Honestly I like it even less (and I wouldn't replace a good descriptive name with a comment) but as I said it's really just my POV" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T01:36:25.100", "Id": "410887", "Score": "0", "body": "@AdrianoRepetti Don't get me wrong. I love descriptive names. I made this one pretty descriptive, if not perfectly so. I just don't think it's possible to capture the entire description in the name without making it take up nearly the whole line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T06:21:17.540", "Id": "410907", "Score": "2", "body": "_I promise you that 2 years down the line, anyone reading this code (including you!) will be much happier understanding the 5 liner than your code._ - this is so not true. I wouldn't let this code pass to production." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T06:23:01.767", "Id": "410908", "Score": "1", "body": "_Your patterns require adding 20 extra lines of boilerplate that then has to be tested and presents more opportunities for mistakes._ - not that _has to be tested_ but one that **can be tested**. Your code isn't testable and is so easy to make a mistake there that you wouldn't notice until something goes wrong for the client. This isn't an improvement. It's a great degradation of both readability and testability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T12:44:36.140", "Id": "410964", "Score": "3", "body": "@t3chb0t This is testable..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T15:20:08.823", "Id": "410988", "Score": "0", "body": "@t3chb0t How is this not testable? You literally just have the test call the method and check the output without any boilerplate setup; that's maximum testability. Every line of code is an additional possibility for a mistake and therefore a bug. Every line of code is another line a reader has to understand. How can you look at this code and think it's harder to understand than 50 lines of extra methods? It's literally just a short list of conditions to check, **just like the requirements are**. What are the *practical* disadvantages of this code you're concerned about?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T10:58:31.580", "Id": "411271", "Score": "0", "body": "I partially agree with t3, I don't think this is \"not testable\" but I think that (assuming you will have similar requirements for different properties) writing ad-hoc code like this will make testing MUCH harder. Don't take me wrong, in your tests you will need to go through all the requirements (for each property), this isn't changed, but you want (must) test corner cases. And corner cases when handling text are A LOT and not so _corner_. Having reusable functions (NOT the way OP did but more general, even if - at first - you have to write more code) lets you test all those cases just ONCE." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T11:05:05.110", "Id": "411272", "Score": "0", "body": "Let me add an example. Unfortunately requirements are _vague_ and open to interpretation so let's assume - for the sake of discussion - that _letter_ has the meaning an average Joe would assume (not a programmer who might think that it's a synonym for a Latin US-ASCII character). In this case this simple string \"\" passes your length validation test (because each is encoded as two UTF-16 code units then for your code its length is 6) and it's wrongfully rejected by `Char.IsLetterOrDigit()`. You obviously don't want to repeat this kind of tests each time you have length validation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T11:13:53.090", "Id": "411273", "Score": "0", "body": "If you are thinking that \"\" is not a _letter_ (!) and it's rightfully rejected then you should try with \"ā\" (LATIN SMALL LETTER A MACRON): it's accepted. If you think \"ā\" is OK but \"\" is not) then you should try with \"ā\" (LATIN SMALL LETTER A + COMBINING MACRON): it's rejected. As you can see to write some more code to handle (and test) this correctly once and for all is a VERY good investment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T15:46:06.510", "Id": "411302", "Score": "0", "body": "@AdrianoRepetti Your objections boil down to \"Unicode is hard,\" and that is 100% true, especially when you get into the realm of combining characters. But deal with those problems with this method is not any harder. The OP's code notably suffer these same problems, and it's *even harder* to detect them because the logic is so scattered. If dealing with those cases led to a level of complexity where inlining each check became unwieldy, I'd obviously factor the checks out into a separate static method. But until it *does* become that complex, there's no reason to insist on separating them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T15:48:35.543", "Id": "411304", "Score": "0", "body": "@AdrianoRepetti And in fact, it would be harder to *fix* these problems with the OP's code because it's designed to process one character at a time. You'd have to change that fact to deal with combining characters, which means scrapping every line of code he has. Would you rather scrap 7 lines of code like my method or scrap 50 like his? These problems demonstrate that the time spent on all the OP's boilerplate was not a good investment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T16:02:56.953", "Id": "411307", "Score": "0", "body": "I agree that OP took it the wrong way, that's why in the comment I wrote (emphasis added now): _\"...Having reusable... **NOT the way OP did**...\"_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T16:16:11.300", "Id": "411310", "Score": "0", "body": "@AdrianoRepetti Okay, fine, but that's only reinforcing my point. Abstract when the complexity grows and not before. Simple *is* better when it's possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T17:42:31.473", "Id": "411325", "Score": "0", "body": "I agree but only if you have to validate one single property." } ], "meta_data": { "CommentCount": "18", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T23:25:39.830", "Id": "212432", "ParentId": "212381", "Score": "1" } }, { "body": "<p>N.B. I thought I'd answer the original test question myself in F# as a Kata, so this is a functional suggestion based on what I found.</p>\n\n<p>I'll only talk about the versatility part of the solution, others have touched on using Linq and I think your code is already quite readable.</p>\n\n<hr>\n\n<p>If you can divide the original requirement into a number of smaller rules, where each rule has the same \"Shape\".</p>\n\n<p>This \"Shape\" is <em>take a sequence of characters and return a Boolean</em>.</p>\n\n<p>So in C# we'd have: </p>\n\n<pre><code>bool LengthIsValid(string s) =&gt; s.Length &gt;= 6 &amp;&amp; s.Length &lt;= 16;\n\nbool Rule2(string s) =&gt; true; //e.g must start with Letter, or doesn't with with '-'\n</code></pre>\n\n<p>Now that we have each rule in the same \"Shape\", you can create a composite set of rules and validate them all together:</p>\n\n<pre><code>var rules = new List&lt;Func&lt;string, bool&gt;&gt; \n{ \n LengthIsValid, \n Rule2,\n //etc.\n};\n</code></pre>\n\n<p>Checking the rules is then just a matter of applying those rules to the input string:</p>\n\n<pre><code>bool CheckAllRules (string s) =&gt;\n rules\n .All(rule =&gt; rule(s));\n</code></pre>\n\n<p>With this approach you get versatility from been able to create any number of composition of rules.</p>\n\n<p>e.g. Creating Rules where the powerUsers don't need to check the length (I can be <code>root</code>).</p>\n\n<pre><code>IEnumerable&lt;Func&lt;string, bool&gt;&gt; CreateRules(bool powerUser)\n{\n if (!powerUser)\n yield return LengthIsValid;\n\n yield return Rule2;\n}\n</code></pre>\n\n<p><sub>\nThe F# version if you're interested in <a href=\"https://gist.github.com/xdaDaveShaw/a21142852d1bf9aff772b07e2523a946\" rel=\"nofollow noreferrer\">here</a>\n</sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T23:33:27.833", "Id": "410875", "Score": "0", "body": "In C# you might want to write `rules.All(x => x(s))` (unless you want to evaluate all the rules without stopping with the first failed one)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T23:47:08.577", "Id": "410880", "Score": "0", "body": "It's OK, because LINQ is lazy evaluated \"All\" will only keep pulling whilst the predicate returns \"true\", as soon the result of the predicate is \"false\" it will stop iterating through the rules. The \"select\" code only executes when \"All\" asks for the one more item.\nTry changing it to `.Select(rule => { Console.WriteLine(\"test\"); return rule(s); })` and you will only see one \"test\" if the first rule fails." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T23:59:21.970", "Id": "410882", "Score": "0", "body": "Yep, I worded that very poorly. The two parts of my comments were unrelated. 1) you don't need `Select()` and 2) unless you want to extract them all (but in that case you obviously need `ToArray()` or similar before `All()`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T00:07:38.753", "Id": "410883", "Score": "0", "body": "Yes, I have a habit of using .Select and .Where followed by .Any/All/Single.First/etc. - it usually makes things clearer for me :) In this case, I think you're correct that just .All would suffice." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T23:30:22.157", "Id": "212433", "ParentId": "212381", "Score": "2" } } ]
{ "AcceptedAnswerId": "212382", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T13:52:02.033", "Id": "212381", "Score": "11", "Tags": [ "c#", "interview-questions", "validation" ], "Title": "Versatile string validation" }
212381
<p>I would like to transform a dict of one format into a dict of another format.</p> <p>The <code>raw_input</code> dict will have the shape:</p> <pre><code>'key': ['list of strings'] </code></pre> <p>I would like to reformat it into a list of dicts with the following shape:</p> <pre><code>[ {'key': 'string'}, {'key': 'string'}, ...etc for each item in the list of strings ] </code></pre> <p>My implementation is functional but naive, using a doubly nested for loop:</p> <pre><code>raw_input = { 'error': ['string 1', 'string2'], 'error2': ['string 3'] } def return_dict_as_list(raw_input): mylist = [] for foo in raw_input: for bar in raw_input[foo]: mylist.append( { 'mykey': foo, 'myvalue': bar } ) return mylist </code></pre> <p>The output is as expected but I can't help but think there's a better way.</p> <p>I did try a couple of list comprehensions, but the output was not what was desired:</p> <p>for example this:</p> <pre><code>elist = [[{'field': item, 'message': msg} for msg in raw[item]] for item in raw] </code></pre> <p>returns nested lists within a list, which I could unpack but doesn't seem very zen.</p> <p>here's an online repl with the code: <a href="https://repl.it/repls/UnpleasantBiodegradableSystems" rel="nofollow noreferrer">https://repl.it/repls/UnpleasantBiodegradableSystems</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:10:47.923", "Id": "410805", "Score": "2", "body": "Also, you should make the purpose of your code the title of your question, not what you want out of a review. Have a look at [ask]." } ]
[ { "body": "<p>You can at least turn the inner <code>for</code> loop into a list/generator comprehension and use <code>list.extend</code> (\"Flat is better than nested\"):</p>\n\n<pre><code>def return_dict_as_list(raw_input):\n mylist = []\n for key, values in raw_input.items():\n my_list.extend({'mykey': key, 'myvalue': value} for value in values)\n return mylist\n</code></pre>\n\n<p>But you can even turn it into one list comprehension with two <code>for</code> loops in it (and no nested lists):</p>\n\n<pre><code>def return_dict_as_list(raw_input):\n return [{'mykey': key, 'myvalue': value}\n for key in raw_input\n for value in raw_input[key]]\n</code></pre>\n\n<p>This will be a bit faster, too, since list comprehensions loop at C speed.</p>\n\n<p>Another approach is to make it a generator:</p>\n\n<pre><code>def to_list_generator(d):\n for key, values in d.items():\n for value in values:\n yield {'mykey': key, 'myvalue': value}\n</code></pre>\n\n<p>This makes it a lot easier to see what is happening (depending on your taste). It also means that you don't need to hold the new list in memory but can process one item at a time in some other function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:32:39.297", "Id": "410813", "Score": "0", "body": "Thanks @Graipher - if you don't mind, could you help me understand why these options might be considered more Pythonic? I am a beginner with Python and am seeking to increase my understanding." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:35:21.207", "Id": "410816", "Score": "2", "body": "@tim: All of them would be more Pythonic because they have better naming. The first one is only slightly better, because it avoids one nested level (\"Flat is better than nested\"), which is why the second one is even better (plus, list comprehensions are usually a bit faster than plain `for` loops). The third one might be considered more Pythonic because it is very clear what is happening and generators are very nice in general because they allow you to setup a pipeline of things being done with some data without having to create temporary lists for every step." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:37:39.273", "Id": "410818", "Score": "1", "body": "@tim: Edited the answer to include those points." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:02:50.743", "Id": "212392", "ParentId": "212387", "Score": "3" } } ]
{ "AcceptedAnswerId": "212392", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:49:00.180", "Id": "212387", "Score": "1", "Tags": [ "python", "beginner", "hash-map" ], "Title": "Transforming a dict of lists into a list of dicts" }
212387
<p>Can this be done more efficiently?</p> <p>The code does the following: </p> <ol> <li>Do Stuff</li> <li>Show UserForm and ask user to confirm the shown data is ok</li> <li>User can manipulate and controll excel as usual</li> <li>As soon as user clicks the "yes" button "do some other stuff" is called</li> </ol> <p><strong>The Module</strong></p> <pre><code>Sub ControlDataUI() Dim Ui As New UserForm1 Dim IsConfirmed As Boolean Debug.Print "dostuff" Application.ScreenUpdating=True With Ui .Show (0) While Not .IsHiden DoEvents Wend If .IsCancelled Then Exit Sub IsConfirmed = .Confirmed End With Debug.Print "Do some more stuff!" If IsConfirmed Then Debug.Print "SaveStuff" End If Debug.Print "I will die!!" End Sub </code></pre> <p><strong>The UserForm</strong></p> <pre><code>Private Type TView IsCancelled As Boolean Confirmed As Boolean IsHiden As Boolean End Type Private this As TView Public Property Get IsCancelled() As Boolean IsCancelled = this.IsCancelled End Property Public Property Get Confirmed() As Boolean Confirmed = this.Confirmed End Property Public Property Get IsHiden() As Boolean IsHiden = this.IsHiden End Property Private Sub CommandButton1_Click() Debug.Print "YES!!!!" this.Confirmed = True this.IsHiden = True Me.Hide End Sub Private Sub CommandButton2_Click() Debug.Print "NO?!?!" this.Confirmed = False this.IsHiden = True Me.Hide End Sub Private Sub UserForm_Click() End Sub Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) this.IsCancelled = True Me.Hide End Sub Private Sub UserForm_Terminate() Debug.Print "Murder! I was killed!" End Sub </code></pre> <p>So the idea was in the right direction but the while loop had to contain a <code>DoEvents</code> in order to process the events comming from the user.</p> <p>Summary: </p> <p><strong>1. Modeless Userform</strong></p> <p><strong>2. While loop with <code>DoEvents</code> until user confirmes</strong></p> <p>This allows for the user controll of the sheet and a confirmation at any time. The code will run after the user confirms the data is ok.</p>
[]
[ { "body": "<p>Yup, it's wrong<sup>1</sup> :)</p>\n\n<p>Forms (and literally everything in Windows) <em>already</em> run their own message loop: whenever you feel the need to wrap a form with a no-op \"wait until user does something\" <code>DoEvents</code> loop, you are essentially forcing your form into a procedural dialog paradigm, keeping the VBA runtime much, <em>much</em> more busy than it needs to be.</p>\n\n<p>Embrace the objects!</p>\n\n<p>The idiomatic way to handle this in VBA is to adopt an event-driven paradigm: instead of wait-looping for a state change and essentially \"poll\" your form periodically until its <code>.IsHiden</code> (typo?) state changes, have a <em>presenter</em> class that's responsible for dealing with the state of the form, by responding to its <em>events</em>.</p>\n\n<pre><code>Dim Ui As New UserForm1\n</code></pre>\n\n<p>Instead of a local (auto-instantiated?) object variable, make that a <code>WithEvents</code> variable at module level (that's why you need a class: only class modules can have <code>WithEvents</code> variables).</p>\n\n<pre><code>Option Explicit\nPrivate WithEvents UI As UserForm1\n\nPrivate Sub Class_Initialize()\n Set UI = New UserForm1\nEnd Sub\n</code></pre>\n\n<p>Now this class can handle any of the <code>UI</code> events - whether they're inherited from the <code>UserForm</code> base class, or custom-defined on the <code>UserForm1</code> default interface, like this:</p>\n\n<pre><code>Public Event ByeBye()\n\nPrivate Sub CommandButton1_Click()\n Debug.Print \"YES!!!!\"\n this.Confirmed = True\n this.IsHiden = True\n Me.Hide\n RaiseEvent ByeBye\nEnd Sub\n</code></pre>\n\n<p>Note the indentation is made more consistent (and arguably better, IMO) by adding an indent level for all members.</p>\n\n<p>Doing this allows the presenter class (the one that declares a <code>WithEvents</code> instance of the form) to handle this <code>ByeBye</code> event:</p>\n\n<pre><code>Private Sub UI_ByeBye()\n 'form is no longer displayed\nEnd Sub\n</code></pre>\n\n<p>Note that this is an entirely different paradigm: you can't <code>do stuff</code> in the same procedure that's responsible for showing the form anymore - it <em>forces</em> you to separate the responsibilies!</p>\n\n<hr>\n\n<p><sup>1</sup> Only because the form isn't modal though: a modal form suspends execution, which makes the explicit loop useless; the form's state can be read on the statement that immediately follows the call to <code>.Show</code>, since that next instruction will only run after the form is dismissed. That isn't the case for a non-modal form, so instead of loop-waiting, we need to embrace the asynchronous nature of the non-modal messenging, with events.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T17:19:37.253", "Id": "410832", "Score": "0", "body": "Not that it's particularly relevant to your review, but what do you mean by the line \"whether they're inherited from the UserForm base class, or custom-defined on the UserForm1 default interface\"? I was under the impression that the `UserForm1` class defines an interface which _extends_ the base UserForm class' interface (by inheriting methods and events like `show` etc. and defining new ones). But what's 'default' got to do with anything, we're not referring to the pre declared instance of `UserForm1` right? Sorry, I'm not hugely familiar with these concepts since they can't be copied in VBA" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T17:23:05.663", "Id": "410833", "Score": "0", "body": "@Greedo the \"default interface\" of a class is the interface presented by an object declared `As [ClassName]` - in other words `As UserForm1` includes the members of `UserForm` inherited from the base class, *and* the members of `UserForm1` defined in `UserForm1`, but not the members of `IDialogView` defined in some hypothetical `IDialogView` class that `UserForm1` would be implementing with `Implements IDialogView`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T19:41:08.363", "Id": "410848", "Score": "0", "body": "@TinMan that sample code involves a *modal* form though. Non-modal forms demand a different paradigm, an event-driven approach. I don't recall writing about non-modal forms, since I don't use them much. But yeah, I'm definitely open for debate - who's the author? ;-)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:19:50.730", "Id": "212395", "ParentId": "212389", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:53:27.273", "Id": "212389", "Score": "3", "Tags": [ "vba" ], "Title": "User Confirmation using a Userform Modeless and DoEvents" }
212389
<p>I am working on scanned documents (ID card, Driver licenses, ...). The problem I faced while I apply some preprocessing on them is that the documents occupy just a small area of the image, all the rest area is whether white/blank space or noised space. For that reason I wanted to develop a Python code that <strong>automatically</strong> trims the unwanted area and keeps only the zone where the document is located (<em>without I predefine the resolution</em>). That's possible with using <code>findContours()</code> from OpenCV. However, not all the documents (especially the old ones) have clear contour and not all the blank space is white, so this will not work.</p> <p>The idea that came to me is:</p> <ol> <li><p>Read the image and convert it to gray-scale.</p> </li> <li><p>Apply the <code>bitwise_not()</code> function from OpenCV to separate the background from the foreground.</p> </li> <li><p>Apply adaptive mean threshold to remove as much possible of noise (and eventually to whiten the background).</p> <p>At this level, I have the background almost white and the document is in black but containing some white gaps.</p> </li> <li><p>I applied erosion to fill the gaps.</p> </li> <li><p>Read each row of the image and if 20% of it contains black, then keep it, if it is white, delete it. And do the same with each column of the image.</p> </li> <li><p>Crop the image according to the min and max of the index of the black lines and columns.</p> </li> </ol> <p>Here is my code with some comments:</p> <pre><code>import cv2 import numpy as np def crop(filename): #Read the image img = cv2.imread(filename) #Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Separate the background from the foreground bit = cv2.bitwise_not(gray) #Apply adaptive mean thresholding amtImage = cv2.adaptiveThreshold(bit, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 35, 15) #Apply erosion to fill the gaps kernel = np.ones((15,15),np.uint8) erosion = cv2.erode(amtImage,kernel,iterations = 2) #Take the height and width of the image (height, width) = img.shape[0:2] #Ignore the limits/extremities of the document (sometimes are black, so they distract the algorithm) image = erosion[50:height - 50, 50: width - 50] (nheight, nwidth) = image.shape[0:2] #Create a list to save the indexes of lines containing more than 20% of black. index = [] for x in range (0, nheight): line = [] for y in range(0, nwidth): line2 = [] if (image[x, y] &lt; 150): line.append(image[x, y]) if (len(line) / nwidth &gt; 0.2): index.append(x) #Create a list to save the indexes of columns containing more than 15% of black. index2 = [] for a in range(0, nwidth): line2 = [] for b in range(0, nheight): if image[b, a] &lt; 150: line2.append(image[b, a]) if (len(line2) / nheight &gt; 0.15): index2.append(a) #Crop the original image according to the max and min of black lines and columns. img = img[min(index):max(index) + min(250, (height - max(index))* 10 // 11) , max(0, min(index2)): max(index2) + min(250, (width - max(index2)) * 10 // 11)] #Save the image cv2.imwrite('res_' + filename, img) </code></pre> <p>Here is an example. I used an image from the internet to avoid any confidentiality problem. It is to notice here that the image quality is much better (the white space does not contain noise) than the examples I work on.</p> <p><strong>Input:</strong> 1920x1080</p> <p><a href="https://i.stack.imgur.com/NHnV7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NHnV7.png" alt="Input" /></a></p> <p><strong>Output:</strong> 801x623</p> <p><a href="https://i.stack.imgur.com/yIyrR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yIyrR.png" alt="Output" /></a></p> <p>I tested this code with different documents, and it works well. The problem is that it takes a lot of time to process a single document (because of the loops and reading each pixel of the image twice: once with lines and the second with columns). I am sure that it is possible to do some modifications to optimize the code and reduce the processing time. But I am very beginner with Python and code optimization.</p> <p>Maybe using numpy to process the matrix calculations or optimizing the loops would improve the code quality.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:22:25.870", "Id": "410810", "Score": "1", "body": "@Graipher, I added an example. The Image I used is from the internet to avoid any problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T16:10:48.247", "Id": "410997", "Score": "1", "body": "I don't have time at this moment for a full review, but you don't have to loop over the image twice. You start looping over it from each side (4 times), but stop at the first line which is of the id. To identify a line, you also don't need to append the value of the pixel to a new list, but just increment a counter" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T16:13:59.160", "Id": "410999", "Score": "0", "body": "@MaartenFabré, that seems so smart! Thank you for these hints, I'll work on them." } ]
[ { "body": "<h1>Split the code</h1>\n\n<p>This long method does a lot of things:</p>\n\n<ul>\n<li>it reads the file</li>\n<li>preprocesses it</li>\n<li>searches for the bounding box of the area of interest</li>\n<li>crops the result </li>\n<li>writes the result to a file</li>\n</ul>\n\n<p>Better would be to split this into more parts. This way, you don't need to comment as much, but let the function names speak for themselves.</p>\n\n<h1>Comments</h1>\n\n<p>If you do feel the need to comment, you can do that in the docstring. If you want to comment on the code, explain <em>why</em> you do it, not <em>how</em>.</p>\n\n<pre><code>#Ignore the limits/extremities of the document (sometimes are black, so they distract the algorithm)\n</code></pre>\n\n<p>is a useful comment.</p>\n\n<pre><code># Apply adaptive mean thresholding\n</code></pre>\n\n<p>is not. It doesn't explain what problem this adaptive thresholding solves, and how you got to the parameters you use: <code>255</code>, <code>ADAPTIVE_THRESH_MEAN_C</code>, <code>35</code> and <code>15</code></p>\n\n<h1>Indexing</h1>\n\n<p>negative indices start counting from the back of a sequence, so </p>\n\n<pre><code>(height, width) = img.shape[0:2]\nimage = erosion[50:height - 50, 50: width - 50]\n</code></pre>\n\n<p>can be replaced by <code>erosion[50:-50, 50:-50]</code></p>\n\n<p>There is also no need to put the parentheses around the <code>height, width</code> tuple.</p>\n\n<h1>Magic numbers</h1>\n\n<p>There are a lot of magic number in your code: <code>15</code> and <code>35</code> in the adaptive threshold, <code>15</code> in the kerneling, <code>50</code> in the cropping,...</p>\n\n<p>Better would be to give them names, and define them in the function or use them as parameters to pass into the function.</p>\n\n<h1>Keyword arguments</h1>\n\n<pre><code>amtImage = cv2.adaptiveThreshold(bit, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 35, 15)\n</code></pre>\n\n<p>would be a lot clearer as: </p>\n\n<pre><code>blocksize = 35\nconstant = 15\nmax_value = 255 # 8 bits\namtImage = cv2.adaptiveThreshold(\n src=bit, \n maxValue=max_value ,\n adaptiveMethod=cv2.ADAPTIVE_THRESH_MEAN_C, \n thresholdType=cv2.THRESH_BINARY, \n blockSize=blocksize , \n C=constant,\n)\n</code></pre>\n\n<h1>Vectorizing</h1>\n\n<p><code>opencv</code> uses <code>numpy arrays</code> internally, so you can use all the vectorisation goodies, instead of iterating over each pixel twice in python land.</p>\n\n<pre><code>bw_threshold = 150\nlimits = 0.2, 0.15\n\nmask = image &lt; bw_threshold\nedges = []\nfor axis in (0, 1):\n count = mask.sum(axis=axis)\n limit = limits[axis] * image.shape[axis]\n index = np.where(count &gt; limit)\n _min, _max = index[0][0], index[0][-1]\n edges.append((_min, _max))\n</code></pre>\n\n<p>does the same, but vectorized and about 1000 times faster.</p>\n\n<hr>\n\n<h1>Final result</h1>\n\n<pre><code>def preproces_image(\n image,\n *,\n kernel_size=15,\n crop_side=50,\n blocksize=35,\n constant=15,\n max_value=255,\n):\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n bit = cv2.bitwise_not(gray)\n image_adapted = cv2.adaptiveThreshold(\n src=bit,\n maxValue=max_value,\n adaptiveMethod=cv2.ADAPTIVE_THRESH_MEAN_C,\n thresholdType=cv2.THRESH_BINARY,\n blockSize=blocksize,\n C=constant,\n )\n kernel = np.ones((kernel_size, kernel_size), np.uint8)\n erosion = cv2.erode(image_adapted, kernel, iterations=2)\n return erosion[crop_side:-crop_side, crop_side:-crop_side]\n\ndef find_edges(image_preprocessed, *, bw_threshold=150, limits=(0.2, 0.15)):\n mask = image_preprocessed &lt; bw_threshold\n edges = []\n for axis in (1, 0):\n count = mask.sum(axis=axis)\n limit = limits[axis] * image_preprocessed.shape[axis]\n index_ = np.where(count &gt;= limit)\n _min, _max = index_[0][0], index_[0][-1]\n edges.append((_min, _max))\n return edges\n\n\ndef adapt_edges(edges, *, height, width):\n (x_min, x_max), (y_min, y_max) = edges\n x_min2 = x_min\n x_max2 = x_max + min(250, (height - x_max) * 10 // 11)\n # could do with less magic numbers\n y_min2 = max(0, y_min)\n y_max2 = y_max + min(250, (width - y_max) * 10 // 11)\n return (x_min2, x_max2), (y_min2, y_max2)\n\nif __name__ == \"__main__\":\n\n filename_in = \"NHnV7.png\"\n filename_out = \"res_NHnV7.png\"\n\n image = cv2.imread(str(filename_in))\n height, width = image.shape[0:2]\n image_preprocessed = preproces_image(image)\n edges = find_edges(image_preprocessed)\n (x_min, x_max), (y_min, y_max) = adapt_edges(\n edges, height=height, width=width\n )\n image_cropped = image[x_min:x_max, y_min:y_max]\n cv2.imwrite(str(filename_out), image_cropped)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T15:30:00.983", "Id": "212555", "ParentId": "212391", "Score": "4" } } ]
{ "AcceptedAnswerId": "212555", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:57:39.773", "Id": "212391", "Score": "10", "Tags": [ "python", "performance", "image", "opencv" ], "Title": "Trimming blank space from images" }
212391
<p>This script counts consecutive number strikes of a number that you determine in a number-sequence that you also determine.</p> <p>I would be very pleased if this script can be reviewed in terms of compactness, readability and quality. If this is perfect, please also let me know. But I am shure it will not be.</p> <p><a href="https://repl.it/@Dexter1997/Count-Consecutive-Strikes?language=python3&amp;folderId=" rel="nofollow noreferrer">The script can be tested here</a></p> <pre><code>import random desired_number = int(input("Desired number: ")) lower_range = int(input("Lower range: ")) upper_range = int(input("Upper range: ")) iterations = int(input("Iterations: ")) consecutive_strikes = 0 biggest_strike = 0 for i in range(iterations): actual_number = random.randint(lower_range, upper_range) print("Actual number: ", actual_number) if actual_number == desired_number: consecutive_strikes += 1 else: if (consecutive_strikes &gt; biggest_strike): biggest_strike = consecutive_strikes consecutive_strikes = 0 # if all numbers are the desired number, the second if-statement in the for-loop # would never be executed if (consecutive_strikes &gt; biggest_strike): biggest_strike = consecutive_strikes print("Biggest consecutive strike: ", biggest_strike) </code></pre>
[]
[ { "body": "<p>You can use the <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"noreferrer\"><code>itertools</code></a> for this.</p>\n\n<p>Just <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"noreferrer\"><code>groupby</code></a> the value to get groups of equal values, filter for the desired value, then get the length of each streak and finally take the <code>max</code> of that length:</p>\n\n<pre><code>from itertools import groupby\n\ndef longest_streak(values, desired_value):\n return max(len(list(group))\n for value, group in groupby(values)\n if value == desired_value)\n</code></pre>\n\n<p>(I think it should be <a href=\"https://www.dictionary.com/browse/streak\" rel=\"noreferrer\">streak</a>, 4. b: \"an uninterrupted series\" and not <a href=\"https://www.dictionary.com/browse/strike?s=t\" rel=\"noreferrer\">strike</a>.)</p>\n\n<p>Then your main can code become this:</p>\n\n<pre><code>from random import randint\n\nif __name__ == \"__main__\":\n desired_number = int(input(\"Desired number: \"))\n lower_range = int(input(\"Lower range: \"))\n upper_range = int(input(\"Upper range: \"))\n iterations = int(input(\"Iterations: \"))\n\n numbers = (randint(lower_range, upper_range) for _ in range(iterations))\n print(\"Biggest consecutive strike: \", longest_streak(numbers, desired_number))\n</code></pre>\n\n<p>Here <code>numbers</code> is a <a href=\"https://wiki.python.org/moin/Generators\" rel=\"noreferrer\">generator</a>, so the function can just consume the numbers as they are generated (meaning that this will occupy at most <code>len(group)</code> space in memory). </p>\n\n<p><a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> is a guard</a> so that the code under it is only executed when directly executing this script, but not when importing from it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:29:20.917", "Id": "212398", "ParentId": "212394", "Score": "7" } }, { "body": "<p>When you never need to use the loop index, you should name it <code>_</code> instead of <code>i</code>.</p>\n\n<pre><code>for _ in range(iterations):\n</code></pre>\n\n<p>If statements don’t need parentheses around the entire condition. You did it properly for the first <code>if</code>, but the last two you added extra parentheses. </p>\n\n<p>You can use the <code>max</code> function to simplify the tracking of the <code>biggest_strike</code>:</p>\n\n<pre><code>biggest_strike = max(biggest_strike, consecutive_strikes)\n</code></pre>\n\n<p>replacing two lines of code with one. And you get to do that twice. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:40:03.803", "Id": "212401", "ParentId": "212394", "Score": "6" } } ]
{ "AcceptedAnswerId": "212401", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:13:16.417", "Id": "212394", "Score": "5", "Tags": [ "python", "random", "statistics", "simulation" ], "Title": "Counting consecutive selections of a given number when sampling integers in a range" }
212394
<p>My code already works perfectly. Here is the JS file:</p> <pre class="lang-js prettyprint-override"><code>var movieData = { count: 6, movies: [{ id: 1, title: "Lorem Ipsum", thumb: "assets/img/placehold.png" }, { id: 2, title: "Lorem Ipsum", thumb: "assets/img/placehold.png" }, { id: 3, title: "Lorem Ipsum", thumb: "assets/img/placehold.png" }, { id: 4, title: "Lorem Ipsum", thumb: "assets/img/placehold.png" }, { id: 5, title: "Lorem Ipsum", thumb: "assets/img/placehold.png" }, { id: 6, title: "Lorem Ipsum", thumb: "assets/img/placehold.png" }, ] }; $(document).ready(function() { if (typeof movieData === 'object' &amp;&amp; typeof movieData !== null) { // List the movies for (var i in movieData.movies) { var movie = movieData.movies[i]; var movieDiv = '&lt;li class="movie-item" data-id="' + movie.id + '"&gt;' + '&lt;a href="#"&gt;' + '&lt;img src="' + movie.thumb + '" width="280" height="150" /&gt;' + '&lt;span class="text-content"&gt;&lt;i class="fa fa-chevron-up" aria-hidden="true"&gt;&lt;/i&gt;&lt;br&gt;&lt;br&gt;&lt;i class="fa fa-4x fa-play-circle-o"&gt;&lt;/i&gt;&lt;br&gt;&lt;br&gt;' + movie.title + '&lt;/span&gt;&lt;/span&gt;' + '&lt;/a&gt;' + '&lt;/li&gt;'; $('#films').append(movieDiv); } } }); </code></pre> <p>I actually have everything into one file. As a code review I am asking your help if you have any idea about how to improve the code.</p> <p>Knowing that as an improvement I already though about making this code into 2 different files (one JS and one JSON) but I would like to know your point of view.</p>
[]
[ { "body": "<p>I would recommend removing <code>count</code> if all it does is represent the number of items in <code>movies</code>. Otherwise, you'll have 2 sources of truth in the data (<code>count</code> and the <code>length</code> of <code>movies</code>) and code that takes sides down the line (one that believes in <code>count</code> and one that believes in the length of <code>movies</code>). So as much as possible, avoid duplicating data.</p>\n\n<p>Now it's not always feasible to recompute data all the time (i.e. if you had to filter thousands of rows to count \"selected\" items). This is one case where I'd put a fixed number instead of recomputing it from some property. Just make sure it's documented somewhere.</p>\n\n<pre><code>for (var i in movieData.movies) {\n</code></pre>\n\n<p>Use regular <code>for</code> loops when looping through arrays. The problem with <code>for-in</code> is that it runs through all enumerable properties, indices <em>and other enumerable properties</em>. You might be getting more than what's just in the array. An even better suggestion is to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"nofollow noreferrer\"><code>array.forEach</code></a>.</p>\n\n<pre><code>$('#films').append(movieDiv);\n</code></pre>\n\n<p>The problem with this approach is that you're doing a <code>jquery.append</code> on every item. That means the browser has to re-render every time you add an item. What I suggest is to create a DOM element in memory and append to that in your loop. Then, at the very end, slap the contents of that DOM element onto the page <em>once</em>. This way, the browser only ever renders once.</p>\n\n<pre><code>// Creates a &lt;ul&gt; that's in memory, not yet appended to the DOM.\nconst replacementFilms = $('&lt;ul/&gt;', { id: '#films' })\n\nmovieData.movies.forEach(movie =&gt; {\n var movieDiv = '...the markup...'\n\n // Appends to our &lt;ul&gt; that's \"in memory\".\n replacementFilms.append(movieDiv)\n})\n\n// Replace the #films in the DOM with the one in memory in one go.\n$('#films').replaceWith(replacementFilms)\n</code></pre>\n\n<p>In this example, I replaced the existing <code>#films</code> in the DOM. But you could also create a dummy element, append the items to it, then append its contents to a container element in the DOM. The operation doesn't have to be a total replace. But the idea is that you only ever touch the DOM once.</p>\n\n<pre><code> '&lt;li class=\"movie-item\" data-id=\"' + movie.id + '\"&gt;' +\n '&lt;a href=\"#\"&gt;' +\n '&lt;img src=\"' + movie.thumb + '\" width=\"280\" height=\"150\" /&gt;' +\n '&lt;span class=\"text-content\"&gt;&lt;i class=\"fa fa-chevron-up\" aria-hidden=\"true\"&gt;&lt;/i&gt;&lt;br&gt;&lt;br&gt;&lt;i class=\"fa fa-4x fa-play-circle-o\"&gt;&lt;/i&gt;&lt;br&gt;&lt;br&gt;' + movie.title + '&lt;/span&gt;&lt;/span&gt;' +\n '&lt;/a&gt;' +\n '&lt;/li&gt;';\n</code></pre>\n\n<p>See <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"nofollow noreferrer\">Template Literals</a> for multi-line strings and string interpolation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T15:23:24.473", "Id": "410990", "Score": "0", "body": "Thank you for your answer ! What do you mean by *create a DOM element in memory and append to that in your loop. Then, at the very end, slap the contents of that DOM element onto the page once.* How can do it can you please provide me more details about it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T15:26:52.837", "Id": "410991", "Score": "0", "body": "@Ced sure. Will update my answer in a bit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T14:25:33.197", "Id": "411128", "Score": "0", "body": "Thank you for the update, this part still looks a bit unclear to me but I'll go though it this week-end. I appreciate the effort :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T17:17:59.883", "Id": "212405", "ParentId": "212400", "Score": "1" } } ]
{ "AcceptedAnswerId": "212405", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:36:25.427", "Id": "212400", "Score": "2", "Tags": [ "javascript", "json" ], "Title": "Create a separate JSON + syntax" }
212400
<p>I'm running a package that downloads data from the internet. This package makes logging calls from different modules.</p> <p>Suppose I have a package 'demopackage'. Here is how my logging is currently set up. Is it possible to improve this way of working? The main.py script runs triggered by a cron job.</p> <p>demopackage/<strong>init</strong>.py</p> <pre><code>""" __init__.py """ import logging from demopackage.core import Logs Logs.config_root_logger() </code></pre> <p>I set up 3 handlers, a console handler with color, a file handler, and an email handler for critical log entries (Amazon SES handler). I would prefer the stream and file handler to inherit a handler like the email handler. </p> <p>demopackage/core.py</p> <pre><code>import boto.ses import coloredlogs class Logs: fs_head = '%(asctime)s.%(msecs)03d %(levelname)1.1s L%(lineno)d ' fs = fs_head + '%(filename)s %(funcName)s %(name)s | %(message)s' dfs = '%d/%m/%y %H:%M:%S' formatter = demopackage.logging.Formatter(fmt=fs, datefmt=dfs) @staticmethod def config_root_logger(): log = demopackage.logging.getLogger() # configure file handler logpath = demopackage.os.path.join('demopackage.log') rfh = demopackage.logging.handlers.RotatingFileHandler(logpath) rfh.maxBytes = 1000000000 # about 1 GB rfh.backupCount = 2 rfh.mode = 'a' rfh.setFormatter(Logs.formatter) rfh.setLevel('INFO') log.addHandler(rfh) # configure email handler smtp_handler = Logs.demopackage_SESHandler() smtp_handler.setFormatter(Logs.formatter) smtp_handler.setLevel('CRITICAL') log.addHandler(smtp_handler) # configure root logger StreamHandler # blue, cyan, green, magenta, red, white and yellow level_dict = {'debug': {'color': 'blue'}, 'info': {'color': 'green'}, 'warning': {'color': 'yellow'}, 'error': {'color': 'red', 'bold': True}, 'critical': {'color': 'magenta', 'bold': True}} field_dict = {'asctime': {'color': 'green'}, 'levelname': {'color': 'white', 'bold': True}, 'lineno': {'color': 'red'}, 'filename': {'color': 'cyan'}, 'funcName': {'color': 'magenta'}, 'name': {'color': 'green'}} coloredlogs.install(fmt=Logs.fs, datefmt=Logs.dfs, level_styles=level_dict, field_styles=field_dict) log.info('stream handler initialized with coloredlogs module') log.info('root logger file handler to {}'.format(logpath)) log.info('root logger smtp handler for AWS SES') class demopackage_SESHandler(demopackage.logging.Handler): """ A handler class which sends an email to Amazon SES for logging events. """ def __init__(self): """ Initialize the handler. """ demopackage.logging.Handler.__init__(self) def emit(self, record): """ Emit a record. Format the record and send it to the specified addressees. """ try: key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' conn = boto.ses.connect_to_region( 'eu-west-1', aws_access_key_id='XXXXXXXXXXXXXXXXXXXXXXXXXXXX', aws_secret_access_key=key) message = self.format(record) subject = 'Critical error in ' + record.pathname conn.send_email('from@sender.com', subject, message, 'to@receiver.com') except Exception: self.handleError(record) </code></pre> <p>logging calls in any module:</p> <pre><code>import demopackage log = demopackage.logging.getLogger('dwh.get_data.py') log.info('some text') log.error('some error raising an exception') log.critical('critical error with email alert') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T05:34:09.817", "Id": "410904", "Score": "0", "body": "It would be good if you'll post your `demopackage.logging.getLogger` method here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T12:23:37.983", "Id": "411101", "Score": "0", "body": "the demopackage.logging.getLogger method is the method from the standard python logging module: https://docs.python.org/3/library/logging.html#logging.getLogger It is available in this namespace since I've imported logging in __init__.py" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:42:42.543", "Id": "212403", "Score": "2", "Tags": [ "python", "object-oriented", "logging", "inheritance" ], "Title": "Python logging setup for a package" }
212403
<p>I am building a string for a search query and I think I am doing it the wrong way.</p> <p>So basically I have serveral textfields, dates, integers and so on in one form. On submit I am checking the forms if its empty or not and building the query string.</p> <p>I am submitting the model and building a kind of "pyramid" by checking if it is null or not, which is ending in a very large if statement (marked emphasis).</p> <pre><code>public string CreateSearchQuery(SearchViewModel model) { StringBuilder buildQueryString = new StringBuilder(2048); if (model == null) { //empty model: return newest results return buildQueryString.Append("SELECT * FROM newTbl.files").ToString(); } buildQueryString.Append("SELECT * FROM newTbl.files INNER JOIN newTbl.folders ON folders.id = f_folders_id WHERE "); if (model.NumberClubs &gt; 0) { buildQueryString.Append("folders.numberClubs = "); buildQueryString.Append(model.NumberClubs); } if(model.MrDateFrom != null) { //those if statements will get very large, when I have more then ten fields *if (model.NumberClubs &gt; 0)* { buildQueryString.Append(" AND "); } buildQueryString.Append("folders.mrDate = '"); buildQueryString.Append(model.MrDateFrom.Value.ToString("dd/MM/yyyy")); buildQueryString.Append("'"); } if (model.Period &gt; 0) { //those if statements will get very large, when I have more then ten fields *if (model.NumberClubs &gt; 0 || model.MrDateFrom != null)* { buildQueryString.Append(" AND "); } buildQueryString.Append("folders.period = "); buildQueryString.Append(model.Period); } buildQueryString.Append(" ORDER BY newTbl.period DESC"); return buildQueryString.ToString(); } </code></pre> <p>I don't think that this is the correct way. So I have a model with several values, but to build a query string I have to check if it is empty or not to append the <code>AND</code>? I mean it is working, but it is really complicated (in my opinion).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T17:52:44.590", "Id": "410835", "Score": "4", "body": "Is there any particular reason your are not using [`SqlParameter`](https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlparameter?view=netframework-4.7.2)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T06:35:32.003", "Id": "410909", "Score": "0", "body": "@t3chb0t Yes, our aim is first use stringbuilder, then use NpgsqlParameter (Postgres) and after that we should use Dapper. To see the different things (pros & cons - so also SQL Injection) and how it is working." } ]
[ { "body": "<p>As t3chb0t suggested, when creating SQL based on user input use <strong>ALWAYS</strong> SqlParameters to prevent sql injection!</p>\n\n<p>Instead of creating SQL using a StringBuilder, I would try to abstract common structures and create classes to represent them. That makes the code more readable and maintainable.</p>\n\n<p>A more structured solution could look like that:</p>\n\n<pre><code> private class Condition\n {\n public Condition(string field, string parameterName, object paramerterValue)\n {\n this.Field = field;\n this.ParameterName = parameterName;\n this.ParameterValue = paramerterValue;\n }\n\n public string Field { get; }\n public string ParameterName { get; }\n public object ParameterValue { get; }\n\n public override string ToString() =&gt; $\"{Field} = @{ParameterValue}\";\n }\n\n public class SqlQuery\n {\n public SqlQuery(string sql, SqlParameter[] parameters = null)\n {\n this.Sql = sql;\n this.SqlParameters = parameters ?? new SqlParameter[0];\n }\n\n public string Sql { get; }\n public SqlParameter[] SqlParameters { get; }\n }\n\n public SqlQuery CreateSearchQuery(SearchViewModel model)\n {\n if (model == null) return new SqlQuery(\"SELECT * FROM newTbl.files\");\n\n var sql = \"SELECT * FROM newTbl.files fi INNER JOIN newTbl.folders fo ON fo.id = fi.f_folders_id\";\n\n var conditions = new List&lt;Condition&gt;();\n var sqlParameters = new SqlParameter[0];\n var pcount = 1;\n\n if (model.NumberClubs &gt; 0) conditions.Add(new Condition(\"fo.numberClubs\", $\"p{pcount++}\", model.NumberClubs));\n if (model.MrDateFrom != null) conditions.Add(new Condition(\"fo.mrDate\", $\"p{pcount++}\", model.MrDateFrom.Value));\n if (model.Period &gt; 0) conditions.Add(new Condition(\"fo.period\", $\"p{pcount++}\", model.Period));\n\n if (conditions.Count &gt; 0)\n {\n var whereClause = \" WHERE \" + string.Join(\" AND \", conditions);\n sqlParameters = conditions.Select(c =&gt; new SlqParameter(c.ParameterName, c.ParameterValue)).ToArray();\n sql += whereClause;\n }\n\n sql += \" ORDER BY newTbl.period DESC\";\n\n return new SqlQuery(sql, sqlParameters);\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T06:43:23.790", "Id": "410910", "Score": "0", "body": "I answered techbot. ;) Yes, there is a reason, to see how the stuff is working/changing. So my question was about the if clauses. What is `$\"p{pcount++}\"`. I am new to C#, but I don't know this syntax. If I am right, it should be the parameterName? Yes, it is easier to read, but when I have 10+ textfields, i will came up with +10 if statements? Is that ok or bad?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T19:51:15.710", "Id": "212418", "ParentId": "212408", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T17:50:27.047", "Id": "212408", "Score": "2", "Tags": [ "c#", "sql" ], "Title": "Build a string for a search query" }
212408
<p>I have coded a simple card game that updates the GUI each second and contains many nodes in game which are used to display game events and animation.</p> <p>People who have tried the game said that their system slows down and memory and CPU usage goes up (I was shocked when I saw from one of my friend's screen that it used around 1.4 GB RAM) is this supposed to happen?</p> <p>I have checked some questions related to JavaFX memory usage problems but could not relate to my matter. In one article, I read that using many nodes in a JavaFX game might result in high memory usage.</p> <p>In a short runtime:</p> <blockquote> <p>minimum memory usage is around 100-250 MB</p> <p>maximum memory usage is around 800-1200 MB </p> <p>average memory usage is around 500-700 MB</p> </blockquote> <p><strong>IMPORTANT:</strong></p> <p><strong>THERE ARE 100 BUTTONS IN A 10X10 GRIDPANE WHICH DO NOT HAVE FX IDS</strong></p> <p><strong>In <code>gameButtonClicked</code> matches are found <code>buttons.indexOf(event.getSource())</code></strong></p> <p><a href="https://i.imgur.com/QMACDQQ.png" rel="nofollow noreferrer">UML DIAGRAM</a></p> <p><strong>Main.java</strong></p> <pre><code>import javafx.application.Application; import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.stage.Stage; import javafx.util.Duration; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Random; import java.util.concurrent.atomic.AtomicLong; public class Main extends Application { static boolean isMuted; static Stage window; static MediaPlayer mediaPlayerBGM; static MediaPlayer mediaPlayerSFX; private static HashMap&lt;String, Media&gt; sounds; private static ArrayList&lt;Long&gt; usage; private final String[] SOUND_LIST = {"bgm_credits.mp3", "bgm_game.mp3", "bgm_game_1.mp3", "bgm_game_2.mp3", "bgm_game_3.mp3", "bgm_how_to.mp3", "bgm_menu.mp3", "bgm_victory.mp3", "sfx_button_clicked.wav", "sfx_card_unfold.wav", "sfx_toggle.wav" }; public static void main(String[] args) { launch(args); AtomicLong sum = new AtomicLong(); usage.forEach(sum::addAndGet); long average = sum.get() / usage.size(); System.out.printf("minimum usage: %d, maximum usage: %d, average usage: %d", Collections.min(usage), Collections.max(usage), average); } static void playBGM(String key) { mediaPlayerBGM.stop(); mediaPlayerBGM.setStartTime(Duration.ZERO); if (key.equals("bgm_game")) { String[] suffix = {"", "_1", "_2", "_3"}; Random random = new Random(); mediaPlayerBGM = new MediaPlayer(sounds.get(key + suffix[random.nextInt(4)])); } else { mediaPlayerBGM = new MediaPlayer(sounds.get(key)); } mediaPlayerBGM.setCycleCount(MediaPlayer.INDEFINITE); if (isMuted) { mediaPlayerBGM.setVolume(0.0); } mediaPlayerBGM.play(); } static void playSFX(String key) { if (mediaPlayerSFX != null) { mediaPlayerSFX.stop(); } mediaPlayerSFX = new MediaPlayer(sounds.get(key)); if (isMuted) { mediaPlayerSFX.setVolume(0.0); } mediaPlayerSFX.play(); } @Override public void start(Stage primaryStage) throws Exception { sounds = new HashMap&lt;&gt;(); usage = new ArrayList&lt;&gt;(); isMuted = false; for (String soundName : SOUND_LIST) { URL resource = getClass().getResource("/" + soundName); System.out.println(soundName); System.out.println(resource.toString()); sounds.put(soundName.substring(0, soundName.lastIndexOf('.')), new Media(resource.toString())); } mediaPlayerBGM = new MediaPlayer(sounds.get("bgm_menu")); mediaPlayerBGM.setCycleCount(MediaPlayer.INDEFINITE); mediaPlayerBGM.play(); window = primaryStage; Parent root = FXMLLoader.load(getClass().getResource("menu.fxml")); // long running operation runs on different thread Thread thread = new Thread(() -&gt; { Runnable updater = () -&gt; { if (!Game.isGameIsOver() &amp;&amp; Game.getScore() != 0 &amp;&amp; window.getTitle().equals("The Main Pick") &amp;&amp; Game.firstClickHappened()) { Game.scoreCalculator(); } }; while (true) { try { usage.add(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()); System.out.printf("Used memory: %d\n", Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()); Thread.sleep(1000); } catch (InterruptedException ex) { System.out.println("Interrupted"); } // UI update is run on the Application thread Platform.runLater(updater); } }); // don't let thread prevent JVM shutdown thread.setDaemon(true); thread.start(); window.setTitle("Main Menu"); window.setScene(new Scene(root, 600, 600)); window.setResizable(false); window.show(); } } </code></pre> <p><strong>Controller.java</strong></p> <pre><code>package com.sample; import javafx.animation.FadeTransition; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.layout.GridPane; import javafx.util.Duration; import java.io.IOException; public class Controller { @FXML public RadioButton musicOnOff; @FXML public Button newGame; @FXML public Button howTo; @FXML public Button credits; @FXML public Button exit; @FXML public Button menu; @FXML public GridPane pane; @FXML public Label score; @FXML public Label time; @FXML public Label tries; private boolean animating; public void initialize() { if (score != null &amp;&amp; time != null &amp;&amp; tries != null) { score.textProperty().bind(Game.scoreProperty); time.textProperty().bind(Game.timeProperty); tries.textProperty().bind(Game.triesProperty); animating=false; } if (musicOnOff!=null){ if(Main.isMuted){ musicOnOff.setSelected(true); } } } public void newGameButtonClicked() { try { Main.playSFX("sfx_button_clicked"); new Game(); Main.window.hide(); Main.window.setScene(getScene("game")); Main.window.setTitle("The Main Pick"); Main.window.setMaximized(true); Main.playBGM("bgm_game"); Main.window.show(); } catch (IOException e) { System.out.println("could not change the scene to: game"); } } public void menuButtonClicked() { try { Main.playSFX("sfx_button_clicked"); Main.playBGM("bgm_menu"); if (Main.window.getTitle().equals("The Main Pick")) { Main.window.hide(); Game.setGameOver(); Main.window.setScene(getScene("menu")); Main.window.setMaximized(false); Main.window.show(); } else { Main.window.setScene(getScene("menu")); } Main.window.setTitle("Main Menu"); } catch (IOException e) { System.out.println("could not change the scene to: game"); } } public void gameButtonClicked(ActionEvent event) { ObservableList&lt;Node&gt; buttons = pane.getChildren(); int index = buttons.indexOf(event.getSource()); int column = index % 10; int row = (index - index % 10) / 10; if (!((Button) event.getSource()).getStyleClass().toString().equals("button button-treasure") &amp;&amp; !((Button) event.getSource()).getStyleClass().toString().equals("button button-uncovered")) { FadeTransition transition = new FadeTransition(); transition.setNode((Button) event.getSource()); transition.setDuration(new Duration(500)); transition.setFromValue(1.0); transition.setToValue(0.0); transition.setCycleCount(1); transition.setOnFinished(actionEvent -&gt; { if (((Button) event.getSource()).getStyleClass().toString().equals("button button-treasure")) { loadVictoryScene(); } if (!((Button) event.getSource()).getStyleClass().toString().equals("button button-treasure") &amp;&amp; !((Button) event.getSource()).getStyleClass().toString().equals("button button-uncovered")) { transition.setFromValue(0.0); transition.setToValue(1.0); System.out.println(((Button) event.getSource()).getStyleClass().toString()); ((Button) event.getSource()).getStyleClass().remove("button-covered"); ((Button) event.getSource()).getStyleClass().add(Game.click(row, column)); transition.play(); transition.setOnFinished(ActionEvent-&gt;animating=false); } }); System.out.println(animating); if(!animating){ animating=true; transition.play(); Main.playSFX("sfx_card_unfold");} } System.out.printf("button index:%d,row:%d,column:%d\n", index, row, column); } public void howToPlayButtonClicked() { try { Main.playSFX("sfx_button_clicked"); Main.playBGM("bgm_how_to"); Main.window.setScene(getScene("howTo")); Main.window.setTitle("How to Play"); } catch (IOException e) { System.out.println("could not change the scene to: how to play"); } } public void creditsButtonClicked() { try { Main.playSFX("sfx_button_clicked"); Main.playBGM("bgm_credits"); Main.window.setScene(getScene("credits")); Main.window.setTitle("Credits"); } catch (IOException e) { System.out.println("could not change the scene to: credits"); } } public void exitButtonClicked() { Main.playSFX("sfx_button_clicked"); Main.window.close(); } public void musicOnOffRadioButtonChecked() { Main.playSFX("sfx_toggle"); if (musicOnOff.isSelected()) { Main.isMuted=true; Main.mediaPlayerBGM.setVolume(0.0); Main.mediaPlayerSFX.setVolume(0.0); System.out.println("now selected"); } else { Main.isMuted=false; Main.mediaPlayerBGM.setVolume(1.0); Main.mediaPlayerSFX.setVolume(1.0); System.out.println("unselected"); } } private void loadVictoryScene() { try { Main.window.hide(); Main.playBGM("bgm_victory"); Main.window.setScene(getScene("victory")); Main.window.setTitle("Victory"); Main.window.setMaximized(false); Main.window.show(); } catch (IOException e) { System.out.println("could not change the scene to: victory"); } } private Scene getScene(String name) throws IOException { Parent root = FXMLLoader.load(getClass().getResource(name + ".fxml")); if (name.equals("game")) { return new Scene(root, 800, 800); } return new Scene(root, 600, 600); } } </code></pre> <p><strong>Game.java</strong> </p> <pre><code>package com.sample; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import java.util.Random; public class Game { static StringProperty scoreProperty; static StringProperty timeProperty; static StringProperty triesProperty; private static int time; private static int score; private static int tries; private static int[][] tiles; private static boolean gameIsOver; private static boolean firstClick; public Game() { System.out.println("Game created..."); tries = 0; score = 100000; time = 0; gameIsOver = false; firstClick = false; scoreProperty = new SimpleStringProperty("" + score); timeProperty = new SimpleStringProperty("0"); triesProperty = new SimpleStringProperty("0"); tiles = new int[10][10]; Random random = new Random(); int treasureColumn = random.nextInt(10); int treasureRow = random.nextInt(10); tiles[treasureRow][treasureColumn] = 1; } static boolean firstClickHappened() { return firstClick; } static void setGameOver() { gameIsOver = true; } static boolean isGameIsOver() { return gameIsOver; } static int getScore() { return score; } static void scoreCalculator() { time++; if (time &lt; 10) { score = score - 100; } else if (time &lt; 20) { score = score - 200; } else if (time &lt; 30) { score = score - 300; } else if (time &lt; 50) { score = score - 500; } else { score = score - 1000; } if (score &lt; 0) { score = 0; } scoreProperty.setValue("" + score); timeProperty.setValue("" + time); triesProperty.setValue("" + tries); System.out.printf("Score:%s,Time:%s,Tries%s\n", scoreProperty.getValue(), timeProperty.getValue(), triesProperty.getValue()); } static String click(int row, int column) { if (!firstClickHappened()) firstClick = true; System.out.println(row + "," + column); int clickValue = tiles[row][column]; System.out.println(clickValue); if (clickValue == 0) { tries++; score -= 1000; } else { setGameOver(); } return (clickValue == 1) ? "button-treasure" : "button-uncovered"; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T19:02:32.363", "Id": "410844", "Score": "1", "body": "What is your definition of \"adequate resources\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T19:50:32.327", "Id": "410850", "Score": "2", "body": "@Mast I am a second year cs student so I do not know many things about performance stuff, by adequate I mean for example calculating the sum of positive integers 5-10 can be easily done with a loop and will require less time and processing(?) but doing it recursively will require more time and processing; so maybe \"optimum values\"?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T17:51:18.433", "Id": "212409", "Score": "1", "Tags": [ "java", "javafx" ], "Title": "Simple card game with updating GUI" }
212409
<p>Here is the working code (intended to be executed with <code>perl -e '&lt;code&gt;' ~/.ssh/config</code>):</p> <p>Actual version: </p> <pre class="lang-perl prettyprint-override"><code>while(&lt;&gt;){if(/^Host (.+)/){$_=$1;foreach $i(/([^ ]+)/g){$h{$i}=1}}}print "$_ " for keys %h; </code></pre> <p>Identical version with whitespace for reading:</p> <pre class="lang-perl prettyprint-override"><code>while(&lt;&gt;) { if(/^Host (.+)/) { $_=$1; foreach $i(/([^ ]+)/g) { $h{$i}=1 } } } print "$_ " for keys %h; </code></pre> <p>I'm sort of a perl newbie. Is <code>$_=$1</code> kosher? Is there a straight-forward way to do this with a single regex? Is there anything else I should be doing better here?</p> <p><strong>Example input output:</strong></p> <p>For a config file with contents like this:</p> <pre><code>Host build HostName build.myserver.com Host build build.myserver.com User ubuntu IdentityFile ~/.ssh/build Host tunnel LocalForward 6397 redis.production.com:6379 </code></pre> <p>The output should be (order is not required, trailing space is not required but acceptable):</p> <pre><code>build build.myserver.com tunnel </code></pre>
[]
[ { "body": "<p>I would use something like</p>\n\n<pre><code>perl -lane '@h{@F[1..$#F]}=()if/^Host\\b/;END{$,=\" \";print keys %h}' -- file\n</code></pre>\n\n<p>or</p>\n\n<pre><code>perl -lane '@h{ @F[ 1 .. $#F ] } = () if /^Host\\b/;\n END {\n $, = \" \";\n print keys %h;\n }' -- file\n</code></pre>\n\n<ul>\n<li><code>-l</code> removes newlines from input and adds them to <code>print</code>s</li>\n<li><code>-n</code> runs the code for each line of the input</li>\n<li><code>-a</code> splits each line on whitespace into the @F array</li>\n<li>the hash <code>%h</code> is populated by all the non-whitepsace strings following <code>Host</code></li>\n<li>at the end, all the keys are printed separated by space</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T20:22:25.697", "Id": "410858", "Score": "1", "body": "Commenting some other things I learned from this answer that I didn't know previously: `$#array` returns the last index of an array, `$,` is the \"output field separator\" printed automatically between fields, `END{}` gives a block of code that is executed when exiting, useful for doing final one-time code while still using the `-n` option." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T13:21:10.077", "Id": "411289", "Score": "0", "body": "can shave a few characters there by switching to `print \"@{[ EXPR ]}\"` and using `eof` in place of an END block. And the spaces after `-e` and `keys` are optional. `perl -lane'@h{@F[1..$#F]}=()if/^Host\\b/;eof&&print\"@{[keys%h]}\"' -- file`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T20:01:41.480", "Id": "212419", "ParentId": "212413", "Score": "8" } } ]
{ "AcceptedAnswerId": "212419", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T19:27:49.023", "Id": "212413", "Score": "7", "Tags": [ "parsing", "perl", "configuration" ], "Title": "Perl one-liner for parsing host names from ssh config file" }
212413
<p>How could I make this code more effective?</p> <pre><code>static void print_decimal(double decimal, int precision) { size_t integer; while (precision--) { decimal *= 100.; integer = (int)decimal; if (!precision &amp;&amp; (integer % 10) &gt;= 5 &amp;&amp; decimal != (double)integer) integer += 10; decimal *= .10; integer /= 10; printf("%i", integer); decimal -= integer; } } </code></pre> <p>Example of calling that show me the decimals of a double with precision</p> <p><code>print_decimal(65.226, 4)</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T21:50:00.497", "Id": "411024", "Score": "0", "body": "ken, [Code](https://codereview.stackexchange.com/q/212490/29485), should you want to compare the output to code that attempts to print an exact conversions." } ]
[ { "body": "<p>Well, there's the obvious stuff, like whitespace and declaring variables at their first point of use. For example:</p>\n\n<pre><code>static void print_decimal(double decimal, int precision)\n{\n size_t integer;\n\n while (precision--)\n {\n decimal *= 100.;\n integer = (int)decimal;\n</code></pre>\n\n<p>could usefully be rewritten as</p>\n\n<pre><code>static void print_decimal(double decimal, int precision)\n{\n while (precision--) {\n decimal *= 100.;\n size_t integer = (int)decimal;\n</code></pre>\n\n<p>This spots a bug: you fail to handle negative inputs. If you want <code>integer</code> to hold a signed <code>int</code>, you should define it as <code>int</code> (not <code>size_t</code>); and vice versa, if you want it to hold an unsigned <code>size_t</code>, you should be casting <code>(size_t)decimal</code> (not <code>(int)decimal</code>).</p>\n\n<hr>\n\n<pre><code> if (!precision &amp;&amp; (integer % 10) &gt;= 5 &amp;&amp; decimal != (double)integer)\n integer += 10;\n</code></pre>\n\n<p>This line could use some comments. I imagine it has something to do with rounding?</p>\n\n<hr>\n\n<pre><code> printf(\"%i\", integer);\n</code></pre>\n\n<p>It's more idiomatic to use <code>printf(\"%d\", integer)</code> to print a decimal integer in C (and C++). True, <code>%i</code> exists, but it's deservedly obscure.</p>\n\n<p>(Also, because of the above bug where you made <code>integer</code> a <code>size_t</code>, down here you should be using <code>%zu</code> to print it. But once you make it an <code>int</code>, you can go back to using <code>%d</code>.)</p>\n\n<p>Every compiler will warn you about the format-string mismatch between <code>%i</code> and <code>size_t</code>. Are you compiling with <code>-Wall</code>? (No.) Why not? (There's no reason not to.) So, start compiling with <code>-Wall</code> today! It'll find your bugs so that you don't have to.</p>\n\n<p>Performance-wise... I conclude from context that you expect this line to only ever print one digit, is that right? That is, your code could benefit from some \"design by contract\":</p>\n\n<pre><code> assert(0 &lt;= integer &amp;&amp; integer &lt;= 9);\n printf(\"%i\", integer);\n</code></pre>\n\n<p>If the assertion is correct, then we can speed up the code by writing simply</p>\n\n<pre><code> assert(0 &lt;= integer &amp;&amp; integer &lt;= 9);\n putchar('0' + integer);\n</code></pre>\n\n<p>However, by adding the assertion, we have made the code a little bit <em>testable</em>. We can write some simple tests — just loop over all the floating-point numbers in the world and see if any of them fail the assertion — and indeed it doesn't take long to find one that fails.</p>\n\n<pre><code>print_decimal(0.097, 2);\n</code></pre>\n\n<p>This prints</p>\n\n<pre><code>010\n</code></pre>\n\n<p>when it should actually have printed</p>\n\n<pre><code>10\n</code></pre>\n\n<p>according to my understanding of your intent.</p>\n\n<hr>\n\n<p>Which reminds me: <code>print_decimal</code> is a weird name for this function, since it literally does not have the ability to print a decimal point! Even your example <code>print_decimal(65.226, 4)</code> actually prints <code>652260</code>, not <code>65.2260</code>. This seems problematic for your prospective users.</p>\n\n<hr>\n\n<p>So in conclusion:</p>\n\n<ul>\n<li>Make your code testable.</li>\n<li>Test your code.</li>\n<li>Compile your code with <code>-Wall</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T05:11:57.767", "Id": "410903", "Score": "2", "body": "-Wextra is also often helpful. A few of the things from -Wextra can be annoying if you are doing something intentionally - like if you mean to left shift a negative value for the behavior it produces. But I find it still is more helpful than not, and each of its warnings can be individually disabled if you need to be doing something that raises them. The implicit fallthrough warning can be suppressed with just a comment saying /* intentional fallthrough */" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T22:15:36.650", "Id": "212426", "ParentId": "212415", "Score": "2" } }, { "body": "<p><strong>Limited range</strong></p>\n\n<p><code>double decimal, ... integer = (int)decimal;</code> is undefined behavior for <strike>well over 90%</strike> about half of all <code>double</code> as the value is well outside the <code>int</code> range of <code>INT_MIN...INT_MAX</code>.</p>\n\n<p>To truncate a <code>double</code>, use <code>double trunc(double)</code>.</p>\n\n<p><strong>Imprecision</strong></p>\n\n<p><code>decimal *= 100.</code> is not certainly exact. With corner cases near xxxx.xx5, OP's approach generates a nearby, though wrong, answer.</p>\n\n<p><strong>Negative numbers error</strong></p>\n\n<p><code>print_decimal(-65.226, 4);</code> --> <code>-1717987571-1932735284-1932735284-1932735283</code></p>\n\n<p><strong>Code is buggy</strong></p>\n\n<p><code>print_decimal(65.9999999999999, 4);</code> --> <code>6599910</code>. This is due to the final rounding not accounted for.</p>\n\n<hr>\n\n<p><strong>to be more effective</strong></p>\n\n<p>Avoid range errors and those due to multiple rounding.</p>\n\n<p>To do this well is a non-trivial problem and requires a fair amount of code. A suitable short answer is possible if the range of <code>double</code> allowed (OP unfortunately has not supplied a restricted range) is reduced or <code>sprintf()</code> is callable.</p>\n\n<p>Below is some quick code. It too has imprecision issues noted about, but less so than OP's. Also OP's various failing cases are corrected here.</p>\n\n<pre><code>#include &lt;limits.h&gt;\n#include &lt;math.h&gt;\n#include &lt;stdint.h&gt;\n\nstatic void print10(long double ldecimal) {\n if (ldecimal &gt;= 10.0) {\n print10(ldecimal/10);\n }\n ldouble mod10 = fmodl(ldecimal, 10);\n putchar((int) mod10 + '0');\n}\n\nstatic void print_decimal2(double decimal, unsigned precision) {\n if (!isfinite(decimal)) {\n return ; // TBD_Code();\n }\n\n if (signbit(decimal)) {\n putchar('-');\n decimal = -decimal;\n }\n\n double ipart;\n double fpart = modf(decimal, &amp;ipart);\n // By noting if there is a non-zero fraction, then this block only needs to\n // handle `double` typically in the [0 ... 2^53] range\n if (fpart) {\n long double pow10 = powl(10, precision);\n ldecimal = roundl(decimal * pow10); // use extended precision as able\n print10(ldecimal);\n } else if (decimal) {\n print10(decimal);\n while (precision) {\n precision--;\n putchar('0');\n }\n } else {\n putchar('0');\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T22:15:50.497", "Id": "212427", "ParentId": "212415", "Score": "2" } } ]
{ "AcceptedAnswerId": "212427", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T19:40:47.447", "Id": "212415", "Score": "2", "Tags": [ "c", "formatting", "floating-point" ], "Title": "Print a double as a decimal with a specified precision" }
212415
<p>Here's my code.</p> <pre><code>javascript:x=document.createElement("script");x.src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"; document.getElementsByTagName("head")[0].appendChild(x);copy(1) </code></pre> <p>Is this the correct way? Are there any flaws in it?</p> <p>Running:</p> <pre><code>copy(1) </code></pre> <p>doesn't work by itself so that's not a possibility, and </p> <pre><code>javascript:x=document.createElement("script");x.src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"; document.getElementsByTagName("head")[0].appendChild(x);copy(1) </code></pre> <p>appears to be the best so far.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T08:24:01.563", "Id": "410923", "Score": "0", "body": "Is the expected result for data to be copied to the clipboard without user action?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T08:54:23.260", "Id": "410930", "Score": "0", "body": "Welcome to Code Review! Can you confirm that the code functions correctly? If so, I recommend that you [edit] to add a summary of the testing (ideally as reproducible unit-test code). If it's not working, it isn't ready for review (see [help/on-topic]) and the question may be deleted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T16:16:55.257", "Id": "411001", "Score": "0", "body": "@guest271314 yes, after clicking the bookmarklet" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T16:17:15.920", "Id": "411002", "Score": "0", "body": "@TobySpeight It works, how would I give proof?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T16:22:32.347", "Id": "411003", "Score": "0", "body": "Just [edit] to say how you've tested it, so that it's clear that it's not an off-topic question. BTW, does the code need to be all on a single line? It might be more readable if split across lines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T18:50:56.363", "Id": "411011", "Score": "0", "body": "Bookmarklets are all on one line" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T02:08:34.167", "Id": "411034", "Score": "0", "body": "An external library is not necessary to copy text to the clipboard. Where is `copy` defined?" } ]
[ { "body": "<p>Looks fine, except for polluting the namespace, you could consider using a <a href=\"https://markdalgleish.com/2011/03/self-executing-anonymous-functions/\" rel=\"nofollow noreferrer\">self executing anonymous function</a>.</p>\n\n<pre><code>javascript:(function(){x=document.createElement(\"script\");x.src=\"https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js\"; document.getElementsByTagName(\"head\")[0].appendChild(x);copy(1);})();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T02:12:27.497", "Id": "411035", "Score": "0", "body": "Have you tried the code at the answer? `Uncaught ReferenceError: copy is not defined`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T11:41:43.397", "Id": "411095", "Score": "0", "body": "I had, it seemed to work just fine for me. His form, and the self executing form did not throw an error for me. But I now see that my browser has a copy function [Command Line API] even before running the bookmarklet. That does not take away my feedback on polluting the namespace though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T20:32:22.353", "Id": "411341", "Score": "0", "body": "@konijn it seems to work only in the console. have your tried in the bookmarklets?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T07:21:02.277", "Id": "411374", "Score": "0", "body": "There is this: https://stackoverflow.com/a/106438/7602" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T19:00:47.523", "Id": "212480", "ParentId": "212416", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T19:41:31.010", "Id": "212416", "Score": "2", "Tags": [ "javascript", "bookmarklet" ], "Title": "Copying text to the user's clipboard" }
212416
<p><strong>Edit:</strong> I got asked a lot why I need to have the <code>LightSource</code> base class or why do I keep one vector of all the light sources, so here's my explanation:</p> <p>In many points in the code I need to interact with all the lights regardless of their type. For example, I manually implemented a "shader" which looped over every face and got a direction to the light source without knowing whether it's point or parallel. Here's a code example:</p> <pre><code>const glm::vec4 Shader::calculatePhongReflection(const glm::vec4&amp; normal,const glm::vec4&amp; worldPoint, const glm::vec4&amp; toCamera) const { glm::vec4 ambientPart = calculateAmbientPart(); glm::vec4 lightSum(0); for each (LightSource* light in scene.GetLightsVector()) { glm::vec4 diffusePartSum = calculateDiffusePart (normal,worldPoint,light); glm::vec4 spectralPartSum = calculateSpecularPart(normal,worldPoint,toCamera,light); lightSum += diffusePartSum + spectralPartSum; } return ambientPart + lightSum; } </code></pre> <p>In <code>calculateDiffusePart</code> and <code>calculateSpecularPart</code> I have this line:</p> <pre><code>glm::vec4 directionToLight = glm::normalize(lightSource-&gt;GetDirectionToLightSource(worldPoint)); </code></pre> <p>So there's a benefit to maintaining one vector that holds all the lights. I don't need to iterate over two vectors (which will inevitably grow in number as I add different types of light) in this part of the code which really doesn't need to know the details of the light source. If I don't keep the base class I'd have to edit many different parts of the code every time I want to add a new type of light when all I actually need is the direction to the light (or in my current implementation which uses OpenGL, the location of the light source).</p> <p><strong>Original:</strong></p> <p>I'm working on a Computer Graphics project and I found a way to implement different types of light sources which I'm not sure is ideal.</p> <p><a href="http://www.netgraphics.sk/light-sources" rel="nofollow noreferrer">There are two types of light sources: parallel, and point.</a></p> <p>Point light source is moving around the mesh, and Parallel light source "can be imagined as a point light source lying in infinity". In other words a parallel light source has a direction which is constant throughout the mesh while a point light source is illuminating in all directions, but has a position which effects the direction of the light compared to the surface it's lighting.</p> <p>I'm having trouble figuring out the right abstraction for all these types. Here's my solution: I have one abstract base class called <code>LightSource</code>:</p> <pre><code>class LightSource: public IMovable,public IRotatable { protected: glm::vec4 color; public: ... // Virtual Setters virtual void SetDirection(const glm::vec4&amp; _direction) =0; virtual void SetLocation (const glm::vec4&amp; _location) =0; // Virtual Getters virtual const glm::vec4* GetDirection() const =0; virtual const glm::vec4* GetLocation() const =0; // Inherited via IMovable virtual void Move(const glm::vec3 direction) override =0; // Inherited via IRotatable virtual void RotateX(const float angle) override =0; virtual void RotateY(const float angle) override =0; virtual void RotateZ(const float angle) override =0; }; </code></pre> <p>and two derived classes:</p> <pre><code>class PointLightSource : public LightSource { private: ... public: // Constructors ... // Base class virtual const glm::vec4 * GetDirection() const override { return nullptr; }; virtual const glm::vec4 * GetLocation() const override { return &amp;location; }; // Base class setters virtual void SetDirection(const glm::vec4 &amp; _direction) override { return; } virtual void SetLocation(const glm::vec4 &amp; _location) override { location = _location; } // Inherited via LightSource virtual void Move(const glm::vec3 direction) override; virtual void RotateX(const float angle) override {} // Point light source emits light everywhere virtual void RotateY(const float angle) override {} virtual void RotateZ(const float angle) override {} ... }; </code></pre> <p>and:</p> <pre><code>class ParallelLightSource : public LightSource { private: ... public: ... // Setters virtual void SetDirection(const glm::vec4 &amp; _direction) override { direction = glm::normalize(_direction); } virtual void SetLocation(const glm::vec4 &amp; _location) override { return; } // Getters virtual const glm::vec4 * GetDirection() const override { return &amp;direction; } virtual const glm::vec4 * GetLocation() const override { return nullptr; }; // Inherited via LightSource virtual void RotateX(const float angle) override; virtual void RotateY(const float angle) override; virtual void RotateZ(const float angle) override; // Can't move a parallel light source virtual void Move(const glm::vec3 direction) override {} ... }; </code></pre> <p><code>LightSource</code> virtually implements two interfaces. one is called <code>IMovable</code> and it's used for every object that moves around the mesh (whether it's a model, a camera, or a light source). another interface is called <code>IRotatable</code>, and it's used for objects that can rotate. Not every movable object is rotatable, and point light source is a good example of that, so I did two interfaces.</p> <p>Essentially what I want is to be able to <strong>move</strong> point light source but not rotate them, and <strong>rotate</strong> parallel light sources without moving them, and do all that without checking for their actual type due to polymorphism. The problem is that every <code>LightSource</code> is both <code>IMovable</code> and <code>IRotatable</code>, so I can't distinguish between the derived types.</p> <p>My awkward solution was to have two virtual functions: GetLocation and GetDirection that return pointers to vectors. the ParallelLightSource will return nullptr on GetLocation, and PointLightSource will return nullptr on GetDirection.</p> <p>In the menus part of the code, I receive a vector of <code>LightSource</code> pointers and I want to display their appropriate menus. There are (as you guessed) two types of menus that are relevant here, one for <code>IMovable</code> objects and one for <code>IRotatable</code> objects. I call the <code>GetLocation</code> &amp; <code>GetDirection</code> functions and skip the appropriate controls if the pointer I got is a <code>nullptr</code>.</p> <pre><code>const glm::vec4* lightLocation = activeLight-&gt;GetLocation(); const glm::vec4* lightDirection = activeLight-&gt;GetDirection(); ... if (lightLocation != nullptr) { moveObjectControls(activeLight,"Light"); } if (lightDirection != nullptr) { newDirection = *lightDirection; xyzSliders(newDirection, "Direction", worldRadius); } </code></pre> <p>Passing around vector pointers rather than vectors by value is problematic. For example, now I actually do need <code>ParallelLightSource</code> to implement <code>GetLocation</code> and return an actual value. I'd have to either have a <code>location</code> class member which will always be equal to <code>-direction * someLargeNumber</code>, or refactor and have <code>GetLocation</code> and <code>GetDirection</code> return values, which will create another mess in the menus because I don't want to see controls that "move" a parallel light source or "rotate" a point light source because it doesn't make any sense, so I'd have to check for the derived types somehow which breaks polymorphism.</p> <p>One solution I thought of is having booleans to indicate whether I want this light to show the <code>IMovable</code>/<code>IRotatble</code> menus, but that doesn't feel right because I don't think it's the light source responsibility to know how it is presented in the menus.</p> <p>Another solution would be to hold one vector for parallel light sources and one for point light sources, but that doesn't sound smart because it's not very scalable and every time I'll implement a new type of light source I'll have to change the menus.</p> <p>I'm quite new at programming (at least in terms of OOP), so I wonder what's the ideal solution to a situation like this. Let me know if you have other comments as well.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T08:52:59.167", "Id": "410928", "Score": "4", "body": "We prefer *complete* code here on Code Review (not `...` placeholders). It's much easier to review code when we're able to compile and test it ourselves! I see you already have some answers, so it's too late to fix this question, but please re-read [ask] before posting your next review request. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T08:54:52.993", "Id": "410931", "Score": "2", "body": "You appear to have stripped out quite a lot of code, making it harder to see what you're actually doing, why and where. Please, next time, show us how your code is structured and don't leave out as much as you did. We need to see the code in it's native habitat, not as snippets." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T10:32:43.243", "Id": "410950", "Score": "0", "body": "@TobySpeight thanks for your comment. My project is quite large and my question is about a very specific part of it. Do you rather I include more relevant parts or the code in it's entirety even though many parts are irrelevant to the question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T10:37:11.927", "Id": "410952", "Score": "2", "body": "That's a good question, and I think there's some answers over on MetaCR as to how to get a good reviewable subset from a larger program. It helps if your code structure is reasonably modular to begin with; then you should be able to present the relevant classes with their unit tests (or at least a small `main()` to exercise it). If you have lots of other functionality mixed in, it might suggest possible improvements to the design (it's probably already hampering the unit tests, I guess)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T19:40:14.433", "Id": "411016", "Score": "0", "body": "@PanthersFan92 Is the entire project more or less than 60k characters?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T15:23:38.217", "Id": "411141", "Score": "0", "body": "@Mast No idea. Why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T21:52:53.300", "Id": "411214", "Score": "0", "body": "@PanthersFan92 because that's the maximum number of characters on CR questions. (65536 characters to be exact)." } ]
[ { "body": "<p>Why is <code>LightSource</code> inheriting from <code>IMovable</code> and <code>IRotatable</code> if not every <code>LightSource</code> is movable or rotatable? <code>LightSource</code> should only contain functions that relate to light sources, for instance intensity or color. The position and the direction are not properties of a light source here. Instead I'd make <code>ParallelLightSource</code> inherit from <code>IRotatable</code> and <code>PointLightSource</code> inherit from <code>IMovable</code>. </p>\n\n<p>From your minimal example I don't see any need for the base class <code>LightSource</code> but you may have left this stuff out to illustrate your problem. If you do not need it, remove it.</p>\n\n<p>I understand you want to edit your sources using menus, but I have no idea how your application organizes the data here. \nIf you really need the base class <code>LightSource</code> you may use RTTI to check whether your object is a <code>IMovable</code> or an <code>IRotatable</code> when creating the menu (<code>dynamic_cast&lt;IMovable*&gt;(ptr)</code> checks if <code>ptr</code> is a subclass of <code>IMovable</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T21:42:32.510", "Id": "410864", "Score": "0", "body": "I need the base class because I have a vector of all the lights, so it's a vector of pointers to LightSource objects" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T21:44:11.913", "Id": "410865", "Score": "0", "body": "Dynamic casting sounds interesting. I think it might solve it. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T23:18:53.720", "Id": "410873", "Score": "7", "body": "@PanthersFan92 \"I have a vector of all the lights\". I think that's your problem. You've painted yourself into this corner and now you're looking for a workaroud, not a proper solution. A proper solution can very well mean having two vectors, one for `Point` and one for `Parallel`. I would advise against using the dynamic casting which would keep you entrenched into this false-commonality situation. Use the type system to your advantage. Do not write code that actively works around it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T01:17:14.380", "Id": "410885", "Score": "2", "body": "@PanthersFan92 Just another thing to note is dynamic casting is more **expensive** than a cleaner solution since it is all done at runtime. I'd advise you avoid dynamic casts as much as you can since it forces unnecessary runtime overhead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T07:36:27.580", "Id": "410917", "Score": "0", "body": "I agree that splitting the vector of Lightsources into separate containers is far better than using runtime checking. From the example one cannot tell if this is feasible or if it would mean a greater refactoring. So if possible, @PanthersFan92, follow screwnuts advice and use two vectors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T10:19:44.423", "Id": "410947", "Score": "0", "body": "I understand your point. I wanted to generically interact with light sources in the menu without knowing the little details of the type of the light sources, because now I have two types so it's two vectors, tomorrow I'll have 3 types etc... I have many areas where I need to interact with all the lights regardless of what types they are. For example, I manually implemented a \"shader\" which looped over every face and got a direction to the light source without knowing whether it's point or parallel. It just called a generic function on the LightSource base class to get the direction." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T20:27:11.623", "Id": "212421", "ParentId": "212417", "Score": "6" } }, { "body": "<p>Overriding <code>RotateX</code>, <code>RotateY</code> and <code>RotateZ</code> to prevent rotation of your point light source is going to cause you grief when you add another type of light source: the spot light. A spot light is a directional point light source, and would be both <code>IMovable</code> and <code>IRotatable</code>. But if you try to derive it from <code>PointLightSource</code>, you’d end up having to add back in the the functionality you took out by overriding.</p>\n\n<p>You probably want to remove <code>IMovable</code> and <code>IRotatable</code> from <code>LightSource</code>, and only add them to derived types that have those attributes.</p>\n\n<p>What is a non-movable, non-rotatable light source you ask? How about <code>AmbientLight</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T10:51:22.500", "Id": "410957", "Score": "1", "body": "Your point about ambient light is true, but I choose to exclude ambient lighting from this inheritance hierarchy because other than having a color it doesn't really share behaviors or properties that other light sources has. It doesn't have a location, it doesn't have a direction, and there's only one ambient light." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T13:38:17.923", "Id": "410974", "Score": "0", "body": "@PanthersFan92 Its not exactly true. A singleton ambient light is not all that useful, and is better implemented in the shading model. On the otherhand a ambient light that has a position but no location for shading other than falloff is useful indeed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T20:41:09.227", "Id": "212422", "ParentId": "212417", "Score": "4" } } ]
{ "AcceptedAnswerId": "212421", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T19:45:17.830", "Id": "212417", "Score": "3", "Tags": [ "c++", "object-oriented", "inheritance", "polymorphism" ], "Title": "Implementing different types of light sources in a Graphics project" }
212417
<p>A friend of mine has the following issue. He has a nearly-full 1TB hard drive on which he keeps copies of all the pictures from his digital camera(s). However, he knows that he has copied the entire contents of the camera to this drive multiple times, with slightly similar--but mostly identical--contents every time. He would like to able to find out which files (mostly pictures) are duplicates.</p> <p>While I started writing this for his application, I would like this to be a general-purpose script for my own use as well. Here is what I came up with.</p> <h2>Main Ideas</h2> <p>Building on the ideas of some posts on <a href="https://codereview.stackexchange.com/questions/159569/group-duplicate-files-part-3">this</a> <a href="https://codereview.stackexchange.com/questions/132927/identify-files-within-folder-structure-that-have-common-file-sizes">site</a> and on <a href="https://stackoverflow.com/questions/748675/finding-duplicate-files-and-removing-them">SO</a>, I create a hash (albeit non-integer) for each file, consisting of (a) the size of the file, (b) some bytes read from the start of the file, and (c) an incrementable counter. This enables me to quickly check that two files are not identical, and then only compare the entire contents if the hashes are equivalent. In the case that two dissimilar files have the same hash, I increment the counter and try again.</p> <ul> <li>I realize that it may seem wasteful to open, read, and close <em>every</em> file when a simple size comparison might be initially sufficient; but I have found that this is generally not the case. In situations where there are many different similar-sized files, the algorithm approaches <span class="math-container">\$O(n^2)\$</span> where one must walk through all previous same-size files for each new one. Granted, these situations only arise in special cases (usually when traversing program files), but hitting one on accident tremendously slows down the program. Thus, taking the time initially to read some bytes can really pay off later. (YMMV, but if you use Chromium, <code>~/.cache/chromium/Default/Cache</code> clearly demonstrates this principle.) Of course, nothing is set in stone, and different hash functions may be used depending on the situation. In addition, other methods (see end of Feedback section), can be used to attempt to circumvent this issue.</li> </ul> <p>The full-file comparison is done by <code>filecmp</code>, which is very fast, although slight modification could make it faster (e.g. a larger cache, or skipping some initial checks which we already know).</p> <h2>Feedback</h2> <ol> <li><p>Of course, the main concern for this kind of program is <em>speed</em>. Is my algorithm efficient? Can it be improved? Are there edge|special-cases that I have overlooked?</p> <ul> <li>I considered that my hash method of using tuples may not be efficient, especially since very many look-ups need to be performed. However, I did not find a significant difference in speed using an equivalent integer hash method. (I tried a few things, but calling the built-in <code>hash</code> on the 3-tuple was the most straightforward.)</li> </ul></li> <li><p>I am not an expert Python programmer. Is this program written and implemented well? Are there any code-smells or bad practices? Do I make good use of Python structures and idioms? What could I do better? What have I done well?</p> <ul> <li>One in particular, I am not fond of the large <code>try</code> block. However, due to the fact that there would have to be two nearly-identical <code>try</code> blocks very close to each other (around <code>fhash = hash_by_tuple(...)</code> and <code>if filecmp.cmp(...)</code>), I thought it was better to pull it out around both.</li> </ul></li> <li><p>Any other feedback.</p></li> </ol> <p>I think there are certainly things that can improve the usability the code. For example, adding support for a list of directories, files, or even regex matches to ignore would allow us to skip certain expensive searches, like <code>~/.local</code> and <code>~/.cache</code>. Or, conversely, a regex to include only certain kinds of files (e.g., <code>r'[.]png$'</code>). However, this seems relatively straight-forward to implement, and it would clutter the code that I would really like to present, so I have not included it.</p> <h2>Code</h2> <pre><code>import filecmp import os from time import time def head (fpath, nbytes, offset=0): """ Read `nbytes` from the beginning of a file, starting at `offset`. If there are less than `nbytes`, return whatever is there (may be empty). If there is not enough room for the `offset`, move back so that we still return `nbytes` number of bytes. """ size = os.stat(fpath).st_size with open(fpath,'rb') as f: if size &lt;= nbytes: pass elif size &lt; offset+nbytes: f.seek(-nbytes,2) else: f.seek(offset) head = f.read(nbytes) return head def hash_by_tuple (fpath, nbytes=4, offset=16): """ Create a 3-tuple hash of the file at `fpath`, consisting of the file size, `nbytes` read from the file, and an incrementable counter. Start reading the bytes at some `offset` so that common headers (e.g. png/pdf) are not included. The counter is always initially 0, and is intended to be incremented on hash collisions to create a new, unique hash. """ return os.stat(fpath).st_size, head(fpath,nbytes,offset), 0 def find_dups (top_dir, **hashkwargs): """ Group duplicate files recursively in and below `top_dir`. Returns a 6-tuple with the main return value and some metadata as follows: (0) The main dictionary of all files, with the hash value from `hash_by_tuple` as the keys, and a list of the file paths with identical content as the values. (1) The total number of files included in the dict. (2) The number of files skipped for various reasons. Usually broken symlinks that are listed by `os.walk`, but are not `os.stat`-able. (3) The total size, in bytes, of all files in the dict. (4) The `top_dir` input, for output formatting. (5) The time it took to run the function, in seconds. Optional `hashkwargs` can be passed to modify the behavior of `hash_by_tuple`. Note 1: The output of this function is best viewed using the complementary function `format_find_dups_output`. Note 2: All empty files are considered "identical" and are mapped to `(0, b'', 0)`. """ t0 = time() top_dir = os.path.abspath(os.path.expanduser(top_dir)) dups = {} numfiles = numskipped = totsize = 0 for dirpath,_,fnames in os.walk(top_dir): for fname in fnames: fpath = os.path.join(dirpath,fname) try: fhash = hash_by_tuple(fpath,**hashkwargs) while True: if fhash not in dups: # a new, unique file has been found. dups[fhash] = [fpath] break # file is a duplicate, or hash collision occured. if filecmp.cmp(fpath,dups[fhash][0],shallow=False): # duplicate. dups[fhash].append(fpath) break # hash collision on actually different files; rehash. fhash = (fhash[0], fhash[1], fhash[2]+1) except OSError: numskipped += 1 continue numfiles += 1 totsize += fhash[0] return dups, numfiles, numskipped, totsize, top_dir, time()-t0 def format_find_dups_output (output, min_dups=1): """ Return a human-readable formatted string directly from the 6-tuple `output` from `find_dups`. It can then either be `print`-ed, or written to a file and read. Set `min_dups` (default=1) to control the minimum number of duplicates a file must have to be included in the returned string. 0 will print every file found. """ dups, numfiles, numskipped, totsize, top_dir, runtime = output header = ( 'In "{}", {} files were analyzed, totaling {} bytes, taking ' + '{:.3g} seconds.\n' + '{} files were skipped because they failed analysis (typically ' + 'broken symlinks).\n' + '{} unique files were found, with {} duplicates, averaging ' + '{:.3g} duplicates per unique file.\n\n' + 'There are {} unique files with &gt;= {} duplicates. In some ' + 'particular order:\n\n' ) main_str = '' numuniq_printing = 0 for fhash,fpaths in sorted(dups.items()): if len(fpaths) &gt; min_dups: numuniq_printing += 1 if len(fpaths) == 1: main_str += ( 'The following file, with the signature {}, ' + 'is unique:\n ' ).format(fhash) else: main_str += ( 'The following {} files, with the signature {}, ' + 'are identical:\n ' ).format(len(fpaths),fhash) main_str += '\n '.join(fpaths) + '\n\n' main_str += 'Done.' header = header.format( top_dir, numfiles, totsize, runtime, numskipped , len(dups), numfiles-len(dups) , (numfiles-len(dups))/len(dups) , numuniq_printing, min_dups ) return header+main_str if __name__ == '__main__': dups_output = find_dups('/a/path/with/maybe/1000/files/for/testing') print(format_find_dups_output(dups_output,min_dups=1)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T14:41:12.450", "Id": "410981", "Score": "1", "body": "There are plenty of already made libraries for this, any reason you are not using them? They usually work with perceptual hashes which work better for detecting similar images, not needed if you only need exactly same image though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T17:57:41.237", "Id": "411008", "Score": "0", "body": "@juvian Sure a quick google search can bring up freeware to do this for you (please feel free to make recommendations!). I didn't consider that to be the safest or most flexible option. This is also partially instructional and entertaining for me, but feel free to suggest the `reinventing-the-wheel` tag, if you feel it deserves it. An interesting question: are those hash/comparison methods faster and as reliable as the proposed methods here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T18:11:12.787", "Id": "411009", "Score": "2", "body": "Depends under which metrics you want to compare them. Perceptual hashes do a lot more, it is able to identify as equal 2 images with different bytes when one is a re-escaling of the other, identify how similar 2 images are, and other things. The find exact file match with same bytes is just one of its less interesting features, and for that its just easier and more efficient to do something like you propose. Also you can get data such as image size by [reading the first bytes](https://stackoverflow.com/questions/15800704/get-image-size-without-loading-image-into-memory)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T18:56:31.163", "Id": "411012", "Score": "0", "body": "@juvian That is very interesting, thank you! At the moment, I would like to be able to compare any kind of file (not just images), but a special case for image duplicates (including scaling) is interesting to consider, +1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T17:24:45.120", "Id": "506229", "Score": "0", "body": "Hashing only proves that two files are *not* the same; it doesn't prove that they *are* the same. ([ship](https://s3-eu-west-1.amazonaws.com/md5collisions/ship.jpg) vs [plane](https://s3-eu-west-1.amazonaws.com/md5collisions/plane.jpg), [PDF-1](https://shattered.io/static/shattered-1.pdf) vs [PDF-2](https://shattered.io/static/shattered-2.pdf), etc.) Reading both files, computing a hash on each, and then reading them both a second time to compare them byte-by-byte is wasteful" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T18:38:26.143", "Id": "506297", "Score": "0", "body": "@endolith Hash collisions are explicitly accounted for in this algorithm. Hashing a small number of bytes to determine non-equal files and then only reading the entire file when the hashes compare the same (to distinguish identical from collision) is both necessary and, in my testing, quite efficient. Can your share your testing that determined this was wasteful?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T16:40:04.367", "Id": "506377", "Score": "0", "body": "@nivk No, that's what you should do. Read only a small number of bytes from each file first to eliminate lots of possibilities, and then only read the complete files once each while comparing them. Hashing would be pointless if the \"small number of bytes\" is comparable to the length of the hash, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-27T00:49:01.590", "Id": "506419", "Score": "0", "body": "@endolith Please read the post that you are commenting on, because this is exactly what is already done. Also please see the accepted answer, which does a 4K read & hash." } ]
[ { "body": "<p>Others are better equipped than I to talk about the quality of the Python, but I can tell you that seeks are expensive, that all random reads cost about the same as long as you're reading less than a block, and that read+stat is worse than reading two sequential blocks, because the stat reads a directory and not the file. </p>\n\n<p>I see about a 10% speedup if you hash the first 4k and use that as your key; another 5% from not computing total size (the only thing stat is needed for, once you drop size from the key):</p>\n\n<pre><code>def find_dups (top_dir, **hashkwargs):\n t0 = time()\n top_dir = os.path.abspath(os.path.expanduser(top_dir))\n dups = {}\n numfiles = numskipped = totsize = 0\n for dirpath,_,fnames in os.walk(top_dir):\n for fname in fnames:\n fpath = os.path.join(dirpath,fname)\n try:\n with open(fpath,'rb') as f:\n fhash = hash( f.read(4096) )\n while True:\n if fhash not in dups:\n # a new, unique file has been found.\n dups[fhash] = [fpath]\n break\n # file is a duplicate, or hash collision occured.\n if filecmp.cmp(fpath,dups[fhash][0],shallow=False):\n # duplicate.\n dups[fhash].append(fpath)\n break\n # hash collision on actually different files; rehash.\n fhash += 1\n except OSError:\n numskipped += 1\n continue\n numfiles += 1\n return dups, numfiles, numskipped, totsize, top_dir, time()-t0\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T04:38:40.790", "Id": "410898", "Score": "1", "body": "Wow, this is excellent, I had no idea that `stat` and `seek` were so expensive. I would have thought they were among the least expensive operations. Can you link any references that go into more detail? And your approach is even faster in my tests, where it is 20% to 3x faster. Could there be any issue with collisions causing `dict` keys to exceed `2**64` in this solution?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T04:51:38.410", "Id": "410900", "Score": "3", "body": "Python integers have arbitrary precision and don't overflow. Is your data on a spinning drive? I was testing on an SSD, which have better seek:read speed ratios than HDD. The HDD would see more improvement from the elimination of 2 seeks per file. Seek is expensive on RAM and flash because it breaks locality (by definition) and thus defeats caching; it's expensive on HDD for the same reasons PLUS the physical need to have the platter spin to your data; it spins at the same speed whether reading or not. Stat is expensive simply because it implies a seek." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T05:00:13.407", "Id": "410902", "Score": "0", "body": "I've personally seen it a bunch of places. Basically, on a spinning drive, the drive heads are the slowest moving part - and they all move in tandem. Seek and stat make the heads move, more often than not. OMG is right about the disk spinning, but it's going much faster than the drive heads." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T06:15:59.133", "Id": "410906", "Score": "0", "body": "@OhMyGoodness Yes Python ints are not limited to 64 bit, and I didn't see any performance decrease for >2**64 keys. But I'm not sure if Python's `dict` don't do some perhaps-64-bit hashing on the keys behind the scenes--it seems unlikely, but one cannot be too careful about these things. Most of my testing is on an SSD, but my friend's drive is an external HDD. I would think it's favorable to optimize for HDDs, since they tend to be much larger. Although, there is no need to have a one-size-fits-all solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T07:45:25.187", "Id": "410921", "Score": "0", "body": "I don't know Python at all - I had to google \"python increment\" when `fhash++` threw a syntax error. But even if extra hashing is happening behind the scenes, it won't affect the correctness of the result because the `filecmp.cmp` call will always detect a false collision. It would only be a danger if we used the actual complete file contents as a hash key (which would be kind of neat, incidentally, I don't think I've ever seen that done), and accepted dict collisions alone as evidence of duplication." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T10:02:24.057", "Id": "410945", "Score": "0", "body": "@OhMyGoodness: Using the file content as dict key would have the problem of storing all files in memory. Python dictionaries don't just keep the hash of the key and the value around, but actually the hash of the key, the key and the value. This is in order to be able to efficiently deal with hash collisions (by just comparing the keys for equality)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T18:50:28.680", "Id": "411010", "Score": "0", "body": "@Graipher Thank you for this information. As I understand it then, looking up a `dict` key of, say, `2**64` will check the `dict`'s hash table for `hash(2**64)`, and then if it finds a match, check against the actual key (`2**64`) to be sure?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T17:54:03.267", "Id": "506232", "Score": "1", "body": "@nivk Python dict's internal hashes are calculated *from* the keys https://softwaremaniacs.org/blog/2020/02/05/dicts-ordered/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T18:39:36.500", "Id": "506300", "Score": "0", "body": "@endolith So then \"yes\" to my question in the most recent comment? I don't see any change to the way `dict` keys are hashed in 3.6/3.7 in your link, other than the note on ordering." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T02:34:15.867", "Id": "212436", "ParentId": "212430", "Score": "6" } } ]
{ "AcceptedAnswerId": "212436", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T23:10:48.147", "Id": "212430", "Score": "6", "Tags": [ "python", "performance", "algorithm", "file-system" ], "Title": "Identify Duplicate Files" }
212430
<p>The following code cd's into the scrape folder, and enters the command "scrapy crawl yellow". It works well, however i want to make this more object oriented looking, utilizing something like</p> <pre><code> if__name__== "__main__" </code></pre> <p>not sure how to implement this kind of code. Ultimately i want this to be an executable which is why im trying to make it more object oriented.</p> <p><strong>App.py</strong></p> <pre><code>import os import subprocess cw = os.getcwd() path = '/scrape' ourPath = cw + os.path.join(path) if(ourPath): os.chdir(ourPath) os.system('scrapy crawl yellow') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T02:14:28.183", "Id": "410895", "Score": "2", "body": "This code makes no sense. How could `ourPath` ever be false? What are you really trying to achieve with this code, and why? Please explain, and also retitle the question to state the task accomplished by the code, as per the [ask] guidelines." } ]
[ { "body": "<p>I think of OOP as being a method to promote reuse by decomposing large data sets into types which tell how to handle their own data, and which can inherit or be inherited to make more complex types without having to duplicate or rewrite the more basic methods of handling the smaller data structures.</p>\n\n<p>That said, you don't really declare any classes or other structures in here, so there isn't a way to make this more \"Object Oriented\".</p>\n\n<p>You can make it a bit more pythonic by following through on your impulse to have a main function:</p>\n\n<pre><code>import os\nimport subprocess \n\ndef main():\n cw = os.getcwd()\n path = '/scrape'\n ourPath = cw + os.path.join(path)\n\n if(ourPath):\n os.chdir(ourPath)\n os.system('scrapy crawl yellow')\n\nif__name__== \"__main__\":\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T00:29:24.383", "Id": "410884", "Score": "0", "body": "thank you so much, this is exactly what i was looking for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T09:55:18.120", "Id": "410943", "Score": "0", "body": "Nice review! In the future please try to avoid answering off-topic questions. We try to close and finish those questions and answers really slow that down (and also send the wrong message to the asker). They are also probably likely to be mostly ignored with the post closed, anyway, so don't expect many upvotes (or any). Have a look at the [Meta](https://codereview.meta.stackexchange.com/questions/6388/should-you-refrain-from-answering-questions-that-are-likely-to-get-closed) for more reasons why obviously off-topic questions should not be answered." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T00:14:25.717", "Id": "212435", "ParentId": "212431", "Score": "0" } } ]
{ "AcceptedAnswerId": "212435", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T23:20:58.500", "Id": "212431", "Score": "-3", "Tags": [ "python" ], "Title": "Whats a more object oriented way to execute a python script" }
212431
<p>In the main method, I have to call a factory to retrieve the Parser and cast it to a child parser to read the different file.</p> <p>How should I improve the code for it to make more sense? Can I avoid casting the parser?</p> <pre><code>public interface Parser&lt;T&gt;{ public Parser read(T t){}; } public class ParserFromJson implements Parser&lt;JSON&gt;{ @Override public Data read(JSON json){...}; } public class ParserFromXml implements Parser&lt;XML&gt;{ @Override public Data read(XML xml){...}; } public class ParserFactory{ public Parser create(Type type){ switch(type){ case JSON: return new ParserFromJson(); case XML: return new ParserFromXml(); } } public enum Type{ JSON, XML } public static void main(String[] args){ ((ParserFromJson)ParserFactory.create(JSON)).read(jsonfile); ((ParserFromXml )ParserFactory.create(XML)).read(xmlfile); } </code></pre> <p>=========================================================================== <strong>Update</strong></p> <p>I'm currently use @Imus Option 1 as the solution because I feel the Factory is redundant. Plus factory can not return concrete class but parent class. </p> <p>However, I'm still have a feel that this may not be the superior result. Because I'm not sure if it breaks the OOP principle to use concrete too much.</p> <p>I want to understand if my final OOP design is making sense: The code should able to parse <code>JSON</code>, <code>XML</code>(no control on this two object) and convert the content to an object Data (I'm able to define the structure). Now consider if there is a new type of input format coming in, Let's say <code>HTML</code>, then I need to create a new impl class ParserFromHtml, add a new enum in Type. </p> <p>If I keep the ParserFactory, then I also need to add a new switch case plus cast using it later on. And I've learned that good OOP design should minimal the code you need to change for the existing class. </p> <p>Therefore, I'm questioning myself if the design make sense or not? Or actually there is a more advanced pattern to handle this scenario. I personally like my idea to use Generic and have different concrete class to parse different input accordingly. But What if this fundamental thinking is wrong?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T13:31:54.583", "Id": "411113", "Score": "1", "body": "Hi, your code looks more like some stub code to illustrate a situation you have. In order to provide correct review, we need the fully working code. Please add the real implementation of this code and the review will only be better :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T14:54:34.063", "Id": "411295", "Score": "0", "body": "Hello @IEatBagels, thank you for your feedback. I can't provide concrete code for some reason. But my extraction should be able to illustrate the problem. If you think this is not appropriate, should I move this to a different forum? Or maybe I can try to add more description to concrete my question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T11:20:22.433", "Id": "411391", "Score": "0", "body": "@IEatBagels If you mean that the question is missing the code-context for how `ParserFromJson` or `ParserFromXml` actually parses the XML/JSON, then I consider that highly irrelevant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T11:24:30.320", "Id": "411392", "Score": "0", "body": "@Zingoer What could possibly be interesting is the following: What is `Data`? What is `jsonFile`/`xmlFile`? Additionally, your interface does not currently compile with that code. Also, you are saying that you have no control of the `XML`/`JSON` objects, but that you would have the possibility to add `HTML` in the enum which confuses me as `XML` and `JSON` are values of the enum - or are there other objects?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T15:12:38.813", "Id": "411411", "Score": "0", "body": "@SimonForsberg I was mostly referring to how the parsers will be used. It's hard to tell if this implementation is solid without knowing how it's used. I probably should have included that in my original comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T09:52:15.163", "Id": "411494", "Score": "0", "body": "@IEatBagels `((ParserFromJson)ParserFactory.create(JSON)).read(jsonfile);` is all I know, but yes, a bit more context in that area would be nice." } ]
[ { "body": "<p>Depending on how exactly you define your \"files\" there's 2 main options here.<br>\n1) Keep parsers entirely split without trying to force them into the same interface<br>\n2) Use a common file interface to pass onto both parsers</p>\n\n<p>Option 1 is probably the simplest one. Just implement the factory as follows:</p>\n\n<pre><code>public class ParserFactory{\n public ParserFromJson creatJSONParser(){\n return new ParserFromJson();\n }\n public ParserFromXML creatXMLParser(){\n return new ParserFromXml();\n }\n}\n</code></pre>\n\n<p>Or since you know beforehand which class you want, just instanciate that without a factory.</p>\n\n<hr>\n\n<p>The other option is to modify the separate parsers to just take a more general File instead of your specific JSON / XML file formats.</p>\n\n<pre><code>public interface Parser {\n public Parser read(File t){};\n}\n\npublic class ParserFromJson implements Parser {\n @Override\n public Data read(File jsonFile){...};\n}\n</code></pre>\n\n<p>That way you don't need the cast anymore:</p>\n\n<pre><code>Data output = ParserFactory.create(JSON).read(jsonfile);\n</code></pre>\n\n<hr>\n\n<p>That last option still requires you to first figure out which type you need to pass to the factory. You could try to go a step further and have the factory decide which parser to use for a specific file.</p>\n\n<pre><code>public class ParserFactory{\n public Parser create(File file){\n if(file.getName().endsWith(\".xml\"){\n return new ParserFromJson();\n } \n if (file.getName().endsWith(\".json\"){\n return new ParserFromXml();\n }\n throw new UnknowFileFormatException(\"No parser known to handle {}\",filegetName());\n }\n}\n</code></pre>\n\n<p>That way you can just call it as follows:</p>\n\n<pre><code>Data output = ParserFactory.create(jsonfile).read(jsonfile);\n</code></pre>\n\n<p>You could also store the file directly in the Parser when you create it so you can call it as <code>ParserFactory.create(jsonfile).read();</code> instead but I'm already feeling we're overdesigning everything for this simple example.</p>\n\n<p>Check what it's going to be used for and decide how much effort you should put in generalising these parsers. Sometimes option 1 is all you need to get things done so you can put time and effort in more important tasks instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T15:53:31.357", "Id": "410995", "Score": "0", "body": "It would make sense to re-use a parser, so storing the file reference directly in the parser doesn't sound like a good idea. Overall a nice answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T07:57:45.537", "Id": "411058", "Score": "0", "body": "@SimonForsberg That too highly depends on how you would use it. I see the parser as a small object that you create just to parse the file and then throw away so it's fine to create a new one for each file. Especially so if you would parse it in small chunks to handle instead of all at once. If a parser is expensive to create you would be correct to only create one and reuse that for each file." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T08:37:46.350", "Id": "212448", "ParentId": "212438", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T04:15:38.930", "Id": "212438", "Score": "-1", "Tags": [ "java" ], "Title": "Retrieving a parser" }
212438
<p>I have a solution to find if two values are present in a binary tree (not a BST).</p> <p>I would like to know if there is</p> <ol> <li>a more efficient way to do this?</li> <li>a more elegant way to this?</li> <li>specific improvement for the parts I've marked with comments?</li> <li>a better way to generalize the solution if we have to check if some 'n' values (all of them) are present in tree or not?</li> </ol> <p>I have a working solution mentioned in the code below but I think the same could be achieved using a more elegant and efficient code.</p> <p>Note : Please assume that <code>CheckIfValuesPresentInTree()</code> is an API that I need to implement, so I can't change the underlying data structure.</p> <pre><code>/*The structure of a Node is as follows: struct Node { int data; Node * right, * left; };*/ void IsPresent(Node* p, int n1, int n2, bool&amp; f1, bool&amp; f2); bool CheckIfValuesPresentInTree(Node* root, int n1, int n2) { auto f1 = bool{false}; auto f2 = bool{false}; IsPresent(root, n1, n2, f1, f2); return f1&amp;&amp;f2; } void IsPresent(Node* p, int n1, int n2, bool&amp; f1, bool&amp; f2) { // Too many arguments passed to the function. if (!p) { return; } if (p-&gt;data == n1) { f1 = true; } if (p-&gt;data == n2) { f2 = true; } IsPresent(p-&gt;left, n1, n2, f1, f2); IsPresent(p-&gt;right, n1, n2, f1, f2); // Second recursive call might not be needed if both n1 and n2 are found // in 1st call. // We can write something like below : but is there a better way ? /* IsPresent(p-&gt;left, n1, n2, f1, f2); if (f1 &amp;&amp; f2) { return; } IsPresent(p-&gt;right, n1, n2, f1, f2); */ } </code></pre>
[]
[ { "body": "<blockquote>\n <p>I have a solution to find if two values are present in a binary tree (not a bst).</p>\n</blockquote>\n\n<p>Why not use a BST? If you find yourself trying to hammer a square peg into a round hole, you should take a step back and see whether you can use a round peg or a square hole.</p>\n\n<hr>\n\n<blockquote>\n <p>[1] More efficient way to do this ?<br>\n [2] More elegant way to this ?</p>\n</blockquote>\n\n<p>Write code to search for a single item in a tree, aborting early when you find it, and call it twice.</p>\n\n<hr>\n\n<blockquote>\n <p>[4] How can we generalize the solution if we have to check if some 'n' values(all of them) are present in tree or not ?</p>\n</blockquote>\n\n<p>Turn the tree into a <code>std::unordered_set</code> and then test each value against the set.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T09:13:59.737", "Id": "410934", "Score": "0", "body": "Please note that I have already mentioned that CheckIfValuesPresentInTree().. is an api and I am not allowed to change underlying data structure." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T08:39:01.307", "Id": "212449", "ParentId": "212442", "Score": "1" } }, { "body": "<p>Reading the title, you want a solution that covers N values. Looking at your code, it doesn't meet that expectation. Not do I see you writing all variants from 1 to N.</p>\n\n<p>As API, you have 2 options: compile time N or runtime.\nIf you go for the compile time, use variadic templates in the call. Otherwise, go for <code>std::vector</code>. As I always mess up the ..., I'll continue with the vector.</p>\n\n<p>Your current approach makes good use of cache locality. Really interesting if the tree is big. Alternatively, you could check each element 1 by 1, really good for a big number of values if you expect a lot of miss matches.</p>\n\n<p>What I would suggest is the following:</p>\n\n<pre><code>bool CheckIfValuesPresentInTree(Node* root, const std::vector&lt;int&gt; &amp; n) {\n auto f = std::vector&lt;bool&gt;{};\n f.resize(n.size(), false);\n IsPresent(root, n, f);\n\n return std::all_of(f.cbegin(), f.cend());\n}\n\nvoid IsPresent(Node* p, const std::vector&lt;int&gt; &amp;n, std::vector&lt;bool&gt; &amp;f) {\n\n if (!p) {\n return;\n }\n\n for (size_t i = 0; i &lt; n.size(); ++i)\n {\n if (p-&gt;data == n[I]) \n f[I] = true;\n }\n\n IsPresent(p-&gt;left, n, f);\n IsPresent(p-&gt;right, n, f);\n}\n</code></pre>\n\n<p>About your question on whether to stop searching once everything if found. Ain't an easy question, given the existing API, I wouldn't bother as it might be more expensive to check.</p>\n\n<p>It can however be done by changing the way you indicate if the value is found. Instead of using the bool, you could use the <code>n</code> to keep track of values you still need to search.</p>\n\n<pre><code>void IsPresent(Node* p, std::vector&lt;int&gt; &amp;n) {\n\n if (!p) {\n return;\n }\n\n for (auto it = n.cbegin(); it != n.cend(); /**/)\n {\n if (p-&gt;data == *it) \n it = n.erase(it);\n else\n ++it;\n }\n\n if (n.empty())\n return;\n\n IsPresent(p-&gt;left, n);\n\n if (n.empty())\n return;\n IsPresent(p-&gt;right, n);\n}\n</code></pre>\n\n<p>The advantage of this, is that the amount of values you are checking reduces while searching. The check on whether you need to terminate becomes really cheap, at the expense of some bookkeeping.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T18:23:04.227", "Id": "212575", "ParentId": "212442", "Score": "2" } } ]
{ "AcceptedAnswerId": "212575", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T06:08:46.813", "Id": "212442", "Score": "0", "Tags": [ "c++", "c++11", "tree" ], "Title": "Find whether two (or 'n') particular values are present in a binary tree" }
212442
<p>I wrote a function to find the closest value in a list to a given search value. What prompted me to write it was as boilerplate for a prime number problem so I could find the closest prime to a given number. </p> <h3>My Code</h3> <pre><code>''' * This function finds the closest value in a sorted list to a given search value. * Parameters: * `lst` is the list to be searched. * `item` is the value to be searched for. * `current` stores the current best match. * `control` controls the search behaviour of the function. * `up` means find the closest value &gt;= to `item`. * `down` means find the closest value &lt;= to `item`. * `up(strict)` means find the closest value &gt; to `item`. * `down(strict)` means find the closest value &lt; to "`tem`. * `neutral` means find the closest value to `item`. * Return: * Returns the closest match in `lst`. * None is returned if no value in the list satisfies the condition (e.g an empty list). ''' def mins(lst, f = None): mn = min(lst) if f is None else min(lst, key = f) return (i for i in lst if i == mn) def maxes(lst, f = None): mx = max(lst) if key is None else max(lst, key = f) return (i for i in lst if i == mx) def xBinSearch(lst, item, control="neutral", current=None): n = len(lst) var = round(n/2) if n &gt; 1: if control == "up": if lst[var] == item: return lst[var] elif lst[var] &gt; item: #The solution is in `lst[:var+1]`. current = lst[var] if current == None or abs(current - item) &gt; abs(lst[var] - item) else current #Update "current" to contain the current closest match. return xBinSearch(lst[:var], item, control, current) #Search the eligible space. If the solution is `lst[var]`, it is already stored in `current`. else: #The solution is not in `lst[:var+1]` return xBinSearch(lst[var+1:], item, control, current) if var + 1 &lt; n else current #Search the eligible space if it exists, else (if there is no where left to search), return the current best match. elif control == "down": if lst[var] == item: return lst[var] elif lst[var] &lt; item: #The solution is not in `lst[:var]`. current = lst[var] if current == None or abs(current - item) &gt; abs(lst[var] - item) else current #Update "current" to contain the current closest match. return xBinSearch(lst[var:], item, control, current) #Search the eligible space. else: #The solution is not in lst[var:] return xBinSearch(lst[:var], item, control, current) if var + 1 &lt; n else current #Search the eligible space if it exists, else (if there is no where left to search), return the current best match. elif control == "up(strict)": if lst[var] &gt; item: #The solution is in `lst[:var+1]`. current = lst[var] if current == None or abs(current - item) &gt; abs(lst[var] - item) else current #Update "current" to contain the current closest match. return xBinSearch(lst[:var], item, control, current) #Search the eligible space. If the solution is `lst[var]`, it is already stored in `current`. else: #The solution is not in `lst[:var+1]` return xBinSearch(lst[var+1:], item, control, current) if var + 1 &lt; n else current #Search the eligible space if it exists, else (if there is no where left to search), return the current best match. elif control == "down(strict)": if lst[var] &lt; item: #The solution is not in `lst[:var]`. current = lst[var] if current == None or abs(current - item) &gt; abs(lst[var] - item) else current #Update "current" to contain the current closest match. return xBinSearch(lst[var:], item, control, current) #Search the eligible space. else: #The solution is not in lst[var:] return xBinSearch(lst[:var], item, control, current) if var + 1 &lt; n else current #Search the eligible space if it exists, else (if there is no where left to search), return the current best match. else: check = [("b", lst[var], abs(lst[var]-item))] #`check[0]` =&gt; `var`. if var-1 &gt;= 0: check.append(("a", lst[var-1], abs(lst[var-1]-item))) #`check[1]` =&gt; `var-1`. if var+1 &lt; n: check.append(("c", lst[var+1], abs(lst[var+1]-item))) #`check[2]` =&gt; `var+1`. mn = [x for x in mins(check, f = lambda x: x[2])] #The closest values to `item` from among the slice. if "a" in mn and "c" not in mn: #The solution is not in `lst[var+1:]` current = check[1][1] if current == None or abs(current - item) &gt; check[1][2] else current return xBinSearch(lst[:var+1], item, control, current) elif "b" in mn and ("a" not in mn and "c" not in mn): #The solution is neither in `lst[:var]` nor in `lst[:var+1]` so is therefore `lst[var]`. return lst[var] elif "c" in mn and "a" not in mn: #The solution is not in `lst[:var]` current = check[2][1] if current == None or abs(current - item) &gt; check[2][2] else current return xBinSearch(lst[var+1:], item, control, current) else: #The solution is in either lst[:var] or lst[var+1:] current = check[0][1] if current == None or abs(current - item) &gt; check[0][2] else current return min([xBinSearch(lst[:var], item, control, current), xBinSearch(lst[var+1:], item, control, current)], key = lambda x: abs(x - item)) else: if n == 1: if control == "up": if lst[0] &gt;= item: #If it is an eligible solution. current = lst[0] if current == None or abs(current - item) &gt; abs(lst[0] - item) else current #Modify `current` accordingly. elif control == "down": if lst[0] &lt;= item: #If it is an eligible solution. current = lst[0] if current == None or abs(current - item) &gt; abs(lst[0] - item) else current #Modify `current` accordingly. if control == "up(strict)": if lst[0] &gt; item: #If it is an eligible solution. current = lst[0] if current == None or abs(current - item) &gt; abs(lst[0] - item) else current #Modify `current` accordingly. elif control == "down(strict)": if lst[0] &lt; item: #If it is an eligible solution. current = lst[0] if current == None or abs(current - item) &gt; abs(lst[0] - item) else current #Modify `current` accordingly. else: current = lst[0] if current == None or abs(current - item) &gt; abs(lst[0] - item) else current #Modify `current` accordingly. return current </code></pre>
[]
[ { "body": "<p>Your <code>xBinSearch</code> is too large, and too recursive.</p>\n\n<p>Most binary searches are over quickly, because <code>log2(n)</code> is small. So you certainly <em>can</em> use a recursive approach. But, especially in an interpreted language like Python, setting up and tearing down function calls is a lot more expensive than iterating in a while loop. So if you have any urge to improve performance, switch from recursion to iteration.</p>\n\n<p>That said, you have made your code much too fluffy. \"Up\", \"down\", \"up(strict)\", what is all this?</p>\n\n<p>Step back and <strong>think</strong> about the problem.</p>\n\n<p>You want to find the closest value to a given query. There are two possibilities:</p>\n\n<ol>\n<li>The value is in the list. Return it.</li>\n<li>The value is not in the list. Return the closest value.</li>\n</ol>\n\n<p>Only case two is interesting from a binary-search perspective. You might not find the value, but you should be able to find the greatest-value-less-than your query, unless all values in the list are greater.</p>\n\n<p>If you find some GVLT value, then compare that value and the next value in the list: one of them is \"closest\". <code>return a if (abs(q-a) &lt; abs(q-b)) else b</code>.</p>\n\n<p>If you find no GVLT value, all values are greater. Just return <code>the_list[0].</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T00:54:41.010", "Id": "411032", "Score": "0", "body": "For the use case that inspired the function, I actually need the smallest value in the list >= the provided search value (\"up\" in my terminology). I'll look at implementing it with iteration, when next I try to refactor." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T15:34:15.863", "Id": "212473", "ParentId": "212443", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T06:30:33.337", "Id": "212443", "Score": "3", "Tags": [ "python", "performance", "algorithm", "binary-search" ], "Title": "Extended Binary Search Function (python)" }
212443
<p><a href="https://leetcode.com/problems/valid-parentheses/" rel="noreferrer">https://leetcode.com/problems/valid-parentheses/</a></p> <blockquote> <p>Given a string containing just the characters <code>(</code>, <code>)</code>, <code>{</code>, <code>}</code>, <code>[</code> and <code>]</code>, determine if the input string is valid.</p> <p>For an input string to be valid:</p> <ul> <li>Open brackets must be closed by the same type of brackets.</li> <li>Open brackets must be closed in the correct order.</li> </ul> <p>Note that an empty string is considered valid.</p> <h3>Example 1:</h3> <p>Input: <code>()</code><br /> Output: true</p> <h3>Example 2:</h3> <p>Input: <code>()[]{}</code><br /> Output: true</p> <h3>Example 3:</h3> <p>Input: <code>(]</code><br /> Output: false</p> <h3>Example 4:</h3> <p>Input: <code>([)]</code><br /> Output: false</p> <h3>Example 5:</h3> <p>Input: <code>{[]}</code><br /> Output: true</p> </blockquote> <pre><code>using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace StackQuestions { [TestClass] public class ValidParentheses { [TestMethod] public void OpenOpenClosedClosedMixTest() { string input = &quot;([)]&quot;; bool result = IsValid(input); Assert.IsFalse(result); } [TestMethod] public void OnePairTest() { string input = &quot;()&quot;; bool result = IsValid(input); Assert.IsTrue(result); } public bool IsValid(string s) { Stack&lt;char&gt; myStack = new Stack&lt;char&gt;(); foreach (var curr in s) { if (curr == '(') { myStack.Push(curr); } else if (curr == '[') { myStack.Push(curr); } else if (curr == '{') { myStack.Push(curr); } else if (curr == ')') { if (myStack.Count &gt; 0) { var top = myStack.Pop(); if (top != '(') { return false; } } else { return false; } } else if (curr == ']') { if (myStack.Count &gt; 0) { var top = myStack.Pop(); if (top != '[') { return false; } } else { return false; } } else if (curr == '}') { if (myStack.Count &gt; 0) { var top = myStack.Pop(); if (top != '{') { return false; } } else { return false; } } } return myStack.Count == 0; } } } </code></pre> <p>Please review coding style as it was a job interview with 30 minutes to code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T12:58:08.967", "Id": "410966", "Score": "0", "body": "Should `IsValidReview(\")(\"));` be true?" } ]
[ { "body": "<p>You get the job done in 30 minutes and the use of a stack is the way to go, so that's a good start. In my opinion you're writing a little too much (repetitive) code and it could be a lot easier to read if you use a <code>switch</code>-statement instead:</p>\n\n<pre><code>public bool IsValidReview(string s)\n{\n Stack&lt;char&gt; endings = new Stack&lt;char&gt;();\n\n foreach (var curr in s)\n {\n switch (curr)\n {\n case '(':\n endings.Push(')');\n break;\n case '[':\n endings.Push(']');\n break;\n case '{':\n endings.Push('}');\n break;\n case ')':\n case ']':\n case '}':\n if (endings.Count == 0 || endings.Pop() != curr)\n return false;\n break;\n\n }\n }\n\n return endings.Count == 0;\n}\n</code></pre>\n\n<p>Here the corresponding ending parenthesis is pushed to the stack instead of the starting one, which makes it easier to check when the ending shows up.</p>\n\n<p>The name <code>myStack</code> doesn't say much, so I have changed it to something more meaningful in the context.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T10:52:38.990", "Id": "410958", "Score": "1", "body": "Cool thanks I was wondering if switch case is the way to go or not" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T12:59:17.407", "Id": "410967", "Score": "1", "body": "@Gilad I think a Dictionary would suit well. [Check my answer too](https://codereview.stackexchange.com/a/212466/35439)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T13:55:25.893", "Id": "410978", "Score": "0", "body": "Since the input only consists of parentheses, the last 3 cases can be replaced by `default`, unless you also want to handle other characters, in which case there should've been a `default` at the end." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T20:54:28.013", "Id": "411019", "Score": "1", "body": "@Henrik Hansen code review just twitted your answer to my question this is why we are getting so many +1s good job!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T23:27:17.183", "Id": "411027", "Score": "3", "body": "@Voile I'd argue against using `default` as a catch-all to cover the last three cases. `default` should be used in a situation where an input doesn't match any expected cases, and I'd prefer them to be kept as distinct cases anyway to make the intent of the code clearer. I do agree that there should be a general `default` for invalid input handling, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T04:57:17.060", "Id": "411044", "Score": "0", "body": "This is beautiful code. I don't think I could ever come up with that under the pressure of a job interview." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T05:19:59.503", "Id": "411047", "Score": "2", "body": "@solarflare you do not need to write in this level. My code passed this interview. The goal here is to try and improve ourself. As you can see there is a room for that always." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T05:33:50.517", "Id": "411049", "Score": "0", "body": "I'd go with `default` to catch ending parens, since the strings are paren-only" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T10:07:38.583", "Id": "212456", "ParentId": "212445", "Score": "47" } }, { "body": "<p>A couple of small things to add:</p>\n\n<ul>\n<li><p>Maybe not applicable to a timed interview, but inline documentation (<code>///</code>) on public members is always nice, and would help to explain the otherwise vague <code>IsValid</code> method name.</p></li>\n<li><p>I'd want to throw an exception if any other character is encountered, since the behaviour is undefined and undocumented. The spec says to assume only <code>()[]{}</code> will appear in the string, which means anyone using it incorrectly (by including such characters) should be informed (maybe they assume it handles <code>&lt;&gt;</code> as well?). If a customer were to depend upon this (undocumented) behaviour of just ignoring such characters, you'd have another undocumented 'feature' to maintain in future (or else an unhappy customer).</p></li>\n<li><p>Any reason the method isn't <code>static</code>? Conceptual benefits aside, making it static would make it clear that it's not messing with any state, and makes it easier to use.</p></li>\n<li><p>That's a very limited set of test-cases: you don't test for <code>{}</code> at all.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T11:20:36.070", "Id": "212460", "ParentId": "212445", "Score": "11" } }, { "body": "<p>This is a follow up of @Henrik Hansen. Instead, of a switch I would use a <code>Dictionary&lt;T, K&gt;</code>. A Dictionary offers two main advantages: an increase readibility and the suppression of every <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic string</a> from your function.</p>\n\n<pre><code>public static readonly Dictionary&lt;char, char&gt; brackets = new Dictionary&lt;char, char&gt;\n{\n {'(', ')'},\n {'[', ']'},\n {'{', '}'}\n};\n\npublic static bool IsValidReview(string input)\n{\n var endings = new Stack&lt;char&gt;();\n foreach (var current in input)\n {\n if (brackets.ContainsKey(current))\n {\n endings.Push(brackets[current]);\n }\n else if (endings.Count == 0 || endings.Pop() != current)\n {\n return false;\n }\n }\n return endings.Count == 0;\n}\n</code></pre>\n\n<p><a href=\"https://dotnetfiddle.net/NsSj2f\" rel=\"nofollow noreferrer\">Try it Online!</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T22:25:33.813", "Id": "411025", "Score": "0", "body": "Just to add, you may also use an array of Tuple instead. `var (opening, closing) = ('(', ')')` should be valid syntax nowadays. This lets you have multiple closings for one opening, or vice versa. It also lets you use C#'s limited destructuring to make it a bit more ergonomic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T23:31:20.590", "Id": "411028", "Score": "1", "body": "I disagree that using a `Dictionary` offers improved readability. It's a bit difficult to tell what this code is supposed to do, especially if I didn't already know its purpose, whereas @HenrikHansen's answer is very clear and concise. The \"magic string suppression\" is a fair point, though in this particular case the usage of the magic strings (or, rather, characters) is limited and clear enough that I wouldn't necessarily care if I saw it in production code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T05:35:00.950", "Id": "411050", "Score": "1", "body": "Sure, the `switch` solution has magic strings, but it's 1. faster/more performant (1 less object) and 2. more readable" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T05:35:33.413", "Id": "411051", "Score": "1", "body": "Well actually, technically magic strings are very rare... these are _not_ magic strings. The reason why they are what they are is _very_ clear. Magic _numbers_, on the other hand, are very common" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T06:06:09.373", "Id": "411053", "Score": "0", "body": "@aloisdg your solution has a time complexity of `O(n^2)`, the other solution has a time complexity of `O(n)`. You can achieve a better time complexity using a multi-key dictionary" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T14:20:40.160", "Id": "411124", "Score": "0", "body": "This doesn't produce correct output. For example when there are other characters than the braces in the string. For example: `\"5\"` or `\"(5)\"`. This can be fixed by removing the `brackets.Values.Any()` statement (not sure what it does that `endings.Pop() != current` doesn't do already). [Fiddle](https://dotnetfiddle.net/oJqrYT)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T14:22:51.963", "Id": "411127", "Score": "0", "body": "Oh, I just now see that the input string only contains those brackets. That means there is no need to loop over `brackets.Values` whatsoever." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T12:54:43.653", "Id": "212466", "ParentId": "212445", "Score": "16" } } ]
{ "AcceptedAnswerId": "212456", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T07:05:16.343", "Id": "212445", "Score": "25", "Tags": [ "c#", "programming-challenge", "interview-questions", "stack" ], "Title": "Leetcode: Valid parentheses" }
212445
<p>I have a set of rules as follows:</p> <p><strong>Product One:</strong></p> <ul> <li>If either part is acceptable, update both parts</li> </ul> <p><strong>Product Two:</strong></p> <ul> <li><p>If either part is acceptable, and one age is > 55, update both parts</p></li> <li><p>If either part is acceptable, and neither age is > 55, then update whichever part needs updating (or both)</p></li> </ul> <p>I know it's not the <em>most</em> nested <code>if</code> statements you'll see, but it feels like I'm repeating code unnecessary and there should be a simpler version of what I've attempted.</p> <p><strong>The Code:</strong></p> <pre><code> if (this.isAcceptablePartOne || this.isAcceptablePartTwo) { if (this.productName.equals(PRODUCT_ONE)) { updatePartOne(); updatePartTwo(); } if (this.productName.equals(PRODUCT_TWO)) { if (Math.max(this.ageLifeOne, this.ageLifeTwo) &gt; 55) { updatePartOne(); updatePartTwo(); } else { if (this.isAcceptablePartOne) { updatePartOne(); } if (this.isAcceptablePartTwo) { updatePartTwo(); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T09:31:49.390", "Id": "410939", "Score": "5", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly. Also, there isn't enough context to review the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T09:36:31.007", "Id": "410941", "Score": "0", "body": "@Zeta fair enough on the title. But I'm not sure how I could provide more information regarding what I was trying to do with the code. Depending on specific scenarios, I need to update part one, part two or both." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T12:24:21.747", "Id": "410961", "Score": "1", "body": "If it is possible could you show us your `Product`-class. I think it could be too big and should be dismembered into several small ones.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T15:27:37.233", "Id": "410992", "Score": "3", "body": "Please show more context. What method does this code appear in? What class is `this`? I suspect that you may be able to improve the code further with a better design altogether." } ]
[ { "body": "<h2>From the requirements</h2>\n\n<blockquote>\n <p>I have a set of rules as follows:</p>\n \n <p><strong>Product One:</strong></p>\n \n <p>If either part is acceptable, update both parts </p>\n \n <p><strong>Product Two:</strong></p>\n \n <p>If either part is acceptable, and one age is > 55, update both parts</p>\n \n <p>If either part is acceptable, and neither age is > 55, then update\n whichever part needs updating (or both)</p>\n</blockquote>\n\n<p>Follows the next, almost literal, straightforward implementation:</p>\n\n<h2>Straightforward implementation</h2>\n\n<p>So, you could implement this using two <code>Checker</code>s, a <code>Product1Checker</code> and a <code>Product2Checker</code>. </p>\n\n<pre><code>if (this.productName.equals(PRODUCT_ONE))\n{\n new Product1Checker().check(this);\n}\nelse if (this.productName.equals(PRODUCT_TWO))\n{\n new Product2Checker().check(this);\n}\n</code></pre>\n\n<p>Like this:</p>\n\n<pre><code>class Product1Checker \n{\n\n public check (Product product)\n {\n if (product.isAcceptablePartOne || product.isAcceptablePartTwo) \n {\n product.updatePartOne();\n product.updatePartTwo();\n }\n }\n} \n</code></pre>\n\n<h2>Alternative approach</h2>\n\n<p>You could have the <code>Checkers</code> implement a <code>ProductChecker</code> interface. Also, each <code>ProductChecker</code> can have a <code>boolean</code> method indicating if this checker applies to a product. Then you can just add all the checkers to a <code>Set</code>, check if they are applicable, and if so, run them on the product</p>\n\n<pre><code>interface ProductChecker\n{\n boolean check (Product p);\n boolean appliesTo (Product p);\n}\n\nSet&lt;ProductChecker&gt; checkers = new HashSet&lt;ProductChecker&gt;();\ncheckers.add(new Product1Checker());\ncheckers.add(new Product2Checker());\n\nfor (ProductChecker checker: checkers)\n{\n if (checker.appliesTo(this))\n {\n checker.check(this));\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T10:17:33.057", "Id": "212457", "ParentId": "212451", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T09:00:47.960", "Id": "212451", "Score": "0", "Tags": [ "java" ], "Title": "Reducing nested if statements" }
212451
<p>Recently I have solved the inverse matrix in three ways, found that their work efficiency has obvious differences.</p> <p>This is the case:</p> <pre><code>typedef signed char int8; typedef signed short int16; typedef signed int int32; typedef unsigned char uint8; typedef unsigned short uint16; typedef unsigned int uint32; typedef float float32; typedef double float64; enum { MINORS, COFACTORS, ADJUGATE }; template &lt;int32 COLS, int32 ROWS, typename T&gt; class Matrix { puiblic: T elements[COLS * ROWS]; // Matrix() : _columns(COLS), _rows(ROWS), _size(COLS * ROWS) { identity(); } // void set(int32 col, int32 row, T value) { elements[_columns * row + col] = value; } // const T&amp; get(int32 col, int32 row) const { return elements[_columns * row + col]; } // Minors, Cofactors and Adjugate solving the inverse matrix: Matrix&lt;COLS, COLS, T&gt; getConversion(uint32 mode) const { Matrix&lt;COLS, COLS, T&gt; m; Matrix&lt;COLS, COLS, T&gt; temp; for (int32 i = 0; i &lt; COLS; i++) { for (int32 j = 0; j &lt; COLS; j++) { // calculate the matrix of minors. cofactor(temp, j, i, COLS); T det = temp.determinantAid(COLS - 1); // calculate the matrix of cofactors. if (mode &gt; MINORS) det *= ((i + j) % 2 == 0) ? 1 : -1; if (mode &gt;= ADJUGATE) // calculate the matrix of adjugate. m.set(i, j, det); else m.set(j, i, det); } } return m; } // Calculates the inverse of matrix. bool invert() { assert(_columns == _rows); T det = determinant(); if (det == 0) { identity(); return false; } det = 1.0f / det; // find adjoint. Matrix&lt;COLS, COLS, T&gt; adj = getConversion(ADJUGATE); // find inverse using formula "inverse(A) = adj(A)/det(A)". for (int32 i = 0; i &lt; COLS; i++) { for (int32 j = 0; j &lt; COLS; j++) set(i, j, adj.get(i, j) * det); } return true; } // Gaussian elimination solves the inverse matrix: bool invert2(){ assert(_columns == _rows); int32 i, j, k, swap; float32 t; Matrix&lt;COLS, COLS, T&gt; temp; for (i = 0; i &lt; COLS; i++) { for (j = 0; j &lt; COLS; j++) temp.set(j, i, get(j, i)); } identity(); for (i = 0; i &lt; COLS; i++) { // look for largest element in column swap = i; for (j = i + 1; j &lt; COLS; j++) { if (abs(temp.get(i, j)) &gt; abs(temp.get(i, i))) swap = j; } if (swap != i) { // swap rows. for (k = 0; k &lt; COLS; k++) { t = temp.get(k, i); temp.set(k, i, temp.get(k, swap)); temp.set(k, swap, t); t = get(k, i); set(k, i, get(k, swap)); set(k, swap, t); } } if (temp.get(i, i) == 0) // no non-zero pivot. // the matrix is singular, which shouldn't // happen. This means the user gave us a bad matrix. return false; t = temp.get(i, i); for (k = 0; k &lt; COLS; k++) { temp.set(k, i, temp.get(k, i) / t); set(k, i, get(k, i) / t); } for (j = 0; j &lt; COLS; j++) { if (j != i) { t = temp.get(i, j); for (k = 0; k &lt; COLS; k++) { temp.set(k, j, temp.get(k, j) - temp.get(k, i) * t); set(k, j, get(k, j) - get(k, i) * t); } } } } return true; } private: T determinantAid(int32 n) const { switch (n) { case 1: return get(0, 0); case 2: return get(0, 0) * get(1, 1) - get(1, 0) * get(0, 1); default: T det = 0; Matrix&lt;COLS, COLS, T&gt; temp; int32 sign = 1; // iterate for each element of first row. for (int32 i = 0; i &lt; n; i++) { cofactor(temp, 0, i, n); det += sign * get(0, i) * temp.determinantAid(n - 1); // terms are to be added with alternate sign. sign = -sign; } return det; } } void cofactor(Matrix&lt;COLS, ROWS, T&gt;&amp; temp, int32 p, int32 q, int32 n) const { int32 i = 0, j = 0; // looping for each element of the matrix. for (int32 col = 0; col &lt; n; col++) { for (int32 row = 0; row &lt; n; row++) { // copying into temporary matrix only those element // which are not in given row and column. if (col != p &amp;&amp; row != q) { temp.set(j++, i, get(col, row)); // row is filled, so increase row index and // reset col index. if (j == n - 1) { j = 0; i++; } } } } } } Next I created a Maxtrix4x4 class using Minors, Cofactors and Adjugate solutions: class Matrix4x4 { public: float32 m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44; Matrix4x4(float32 m11 = 1.0f, float32 m12 = 0.0f, float32 m13 = 0.0f, float32 m14 = 0.0f, float32 m21 = 0.0f, float32 m22 = 1.0f, float32 m23 = 0.0f, float32 m24 = 0.0f, float32 m31 = 0.0f, float32 m32 = 0.0f, float32 m33 = 1.0f, float32 m34 = 0.0f, float32 m41 = 0.0f, float32 m42 = 0.0f, float32 m43 = 0.0f, float32 m44 = 1.0f) { ......... } bool invert() { float32 a = m33 * m44 - m43 * m34; float32 b = m32 * m44 - m42 * m34; float32 c = m32 * m43 - m42 * m33; float32 d = m31 * m44 - m41 * m34; float32 e = m31 * m43 - m41 * m33; float32 f = m31 * m42 - m41 * m32; float32 g = m22 * a - m23 * b + m24 * c; float32 h = m21 * a - m23 * d + m24 * e; float32 i = m21 * b - m22 * d + m24 * f; float32 j = m21 * c - m22 * e + m23 * f; // calculate the determinant. float32 det = m11 * g - m12 * h + m13 * i - m14 * j; // close to zero, can't invert. if (det == 0) { identity(); return false; } float32 m = m23 * m44 - m43 * m24; float32 n = m22 * m44 - m42 * m24; float32 o = m22 * m43 - m42 * m23; float32 p = m21 * m44 - m41 * m24; float32 q = m21 * m43 - m41 * m23; float32 r = m21 * m42 - m41 * m22; float32 s = m23 * m34 - m33 * m24; float32 t = m22 * m34 - m32 * m24; float32 u = m22 * m33 - m32 * m23; float32 v = m21 * m34 - m31 * m24; float32 w = m21 * m33 - m31 * m23; float32 x = m21 * m32 - m31 * m22; det = 1.0f / det; float32 t11 = g * det; float32 t12 = -h * det; float32 t13 = i * det; float32 t14 = -j * det; float32 t21 = (-m12 * a + m13 * b - m14 * c) * det; float32 t22 = (m11 * a - m13 * d + m14 * e) * det; float32 t23 = (-m11 * b + m12 * d - m14 * f) * det; float32 t24 = (m11 * c - m12 * e + m13 * f) * det; float32 t31 = (m12 * m - m13 * n + m14 * o) * det; float32 t32 = (-m11 * m + m13 * p - m14 * q) * det; float32 t33 = (m11 * n - m12 * p + m14 * r) * det; float32 t34 = (-m11 * o + m12 * q - m13 * r) * det; float32 t41 = (-m12 * s + m13 * t - m14 * u) * det; float32 t42 = (m11 * s - m13 * v + m14 * w) * det; float32 t43 = (-m11 * t + m12 * v - m14 * x) * det; float32 t44 = (m11 * u - m12 * w + m13 * x) * det; m11 = t11; m12 = t21; m13 = t31; m14 = t41; m21 = t12; m22 = t22; m23 = t32; m24 = t42; m31 = t13; m32 = t23; m33 = t33; m34 = t43; m41 = t14; m42 = t24; m43 = t34; m44 = t44; return true; } } </code></pre> <p>Next, I tested the time it took to calculate:</p> <pre><code>#include &lt;cstdio&gt; #include &lt;iostream&gt; #include &lt;windows.h&gt; #include &lt;time.h&gt; float64 timeSpent = 0; LARGE_INTEGER nFreq; LARGE_INTEGER nBeginTime; LARGE_INTEGER nEndTime; Matrix4x4 m4; m4.m11 = 2.1018f; m4.m12 = -1.81754f; m4.m13 = 1.2541f; m4.m14 = 2.442f; m4.m21 = 0.54194f; m4.m22 = 2.75391f; m4.m23 = -0.1167f; m4.m24 = 0.0f; m4.m31 = -5.81652f; m4.m32 = -7.9381f; m4.m33 = 4.2816f; m4.m34 = 23.33819f; m4.m41 = 9.5076f; m4.m42 = 10.9058f; m4.m43 = 2.0f; m4.m44 = 4.8239f; Matrix&lt;4, 4, float32&gt; mat1; Matrix&lt;4, 4, float32&gt; mat2; float32* e1 = mat1.elements; e1[0] = 2.1018f; e1[1] = -1.81754f; e1[2] = 1.2541f; e1[3] = 2.442f; e1[4] = 0.54194f; e1[5] = 2.75391f; e1[6] = -0.1167f; e1[7] = 0.0f; e1[8] = -5.81652f; e1[9] = -7.9381f; e1[10] = 4.2816f; e1[11] = 23.33819f; e1[12] = 9.5076f; e1[13] = 10.9058f; e1[14] = 2; e1[15] = 4.8239f; mat2 = mat1; QueryPerformanceFrequency(&amp;nFreq); QueryPerformanceCounter(&amp;nBeginTime); // start timer for (i = 0; i &lt; 100000; i++) mat1.invert(); QueryPerformanceCounter(&amp;nEndTime); // end timer timeSpent = (float64)(nEndTime.QuadPart - nBeginTime.QuadPart) / (nFreq.QuadPart); printf("time1:%f\n", timeSpent); QueryPerformanceCounter(&amp;nBeginTime); for (i = 0; i &lt; 100000; i++) mat2.invert2(); QueryPerformanceCounter(&amp;nEndTime); timeSpent = (float64)(nEndTime.QuadPart - nBeginTime.QuadPart) / (nFreq.QuadPart); printf("time2:%f\n", timeSpent); QueryPerformanceCounter(&amp;nBeginTime); for (i = 0; i &lt; 100000; i++) m4.invert(); QueryPerformanceCounter(&amp;nEndTime); timeSpent = (float64)(nEndTime.QuadPart - nBeginTime.QuadPart) / (nFreq.QuadPart); printf("time3:%f\n", timeSpent); </code></pre> <p>Output:</p> <pre><code>time1:0.122209 time2:0.014264 time3:0.002685 ........ ........ ........ time1:0.100992 time2:0.014209 time3:0.002736 time1:0.101950 time2:0.014248 time3:0.002731 ....... ....... </code></pre> <p>Obvious difference!</p> <p>What do you think?</p>
[]
[ { "body": "<p>Regarding possible performance differences: yes, they are possible. But I'm also pretty sure you are not measuring it correctly. You need to compile with optimizations turned on, that is e.g. for gcc / clang you'll need to at least add <code>-O3</code> to your compiler flags, also note that figures you get will strongly depend on architecture, used compiler etc. You may want to inspect some benchmark frameworks for C++, e.g. <a href=\"http://quick-bench.com/\" rel=\"nofollow noreferrer\">Quick Bench</a>. </p>\n\n<p>That being said, there are some other things you can improve. Since this is tagged as C++, you should use standard library, e.g. <code>std::array</code> from header <code>array</code> as the storage for your matrix class, you should probably also get familiar with <code>chrono</code> if you insist on measuring time \"by hand\", particularly <code>steady_clock</code> might be of interest to you (this part is a guess, since you have not included actual implementation for the <code>QueryPerformance...</code> functions).<br>\nI'd also recommend making the <code>Matrix</code> class template more container like- define proper constructors, member access functions, iterators (possibly) inside the class. On the other hand, I'd remove the remaining stuff from the class and make those functions free and operating on the matrix class e.g. the <code>invert</code> declaration could look like this:</p>\n\n<pre><code>template&lt;std::size_t Dim, typename T&gt;\nusing SquareMatrix = Matrix&lt;Dim, Dim, T&gt;;\n\ntemplate&lt;std::size_t Dim, typename T&gt;\nSquareMatrix&lt;Dim, T&gt; invert (SquareMatrix&lt;Dim, T&gt; const&amp; mat);\n</code></pre>\n\n<p>Also note that there is a very small number of types on which the algorithms work, this could be manifested using some <code>SFINAE</code> (that is probably a bit more advanced topic, but there is plenty of resources online on how to use that technique). </p>\n\n<p>The <code>Matrix4x4</code> is not needed- this is a very bad implementation of <code>Matrix</code> constructor implementation, should be handled by proper <code>Matrix</code> constructor instead. </p>\n\n<p>Use <code>enum class</code> instead of plain <code>enum</code>, it's type-safe and prohibits implicit conversions from underlying numeric type (this will also force you to write the algorithm choice part properly- the ifs around the underlying values are not pretty). </p>\n\n<p>Lastly, force your compiler to do some work for you: add <code>-Werror -Wall -Wpedantic</code> to your compiler flags, so that your code won't compile if you produce warnings (<code>-Wall</code> is a must to avoid a ton of undefined / unspecified behavior). If you are using MVSC compiler then you'll need <code>/W3</code> instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T10:43:00.480", "Id": "212459", "ParentId": "212455", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T10:07:16.073", "Id": "212455", "Score": "-3", "Tags": [ "c++", "performance", "comparative-review", "matrix" ], "Title": "About the problem of seeking matrix inverse" }
212455
<p>I made a program in <a href="https://en.wikipedia.org/wiki/IDL_(programming_language)" rel="nofollow noreferrer">IDL</a> for performing a minimum distance classification on multispectral satellite data. This is what my main function looks like:</p> <pre><code>function minimum_distance, stack, exercising_data ;variables nbands = get_number_of_bands() nclasses = get_number_of_classes() x_size = (size(stack, /DIMENSIONS))[0] y_size = (size(stack, /DIMENSIONS))[1] result = MAKE_ARRAY(x_size,y_size,/INTEGER) ;calculate class mean for each class class_means = calculate_class_means(exercising_data) ;find closest class mean for each point and create result image i = 0 foreach point, stack[0,*,0], i do begin foreach point, stack[*,i,0], j do begin print, string(i) + "-" + string(j) point = REFORM(stack[j,i,*],7,1) dist_array = [[point],[class_means]] class = (DISTANCE_MEASURE(dist_array))[0:nclasses-1] class = min(class,location) result[j,i] = location end end ;prepare result for display result = result * (255/(nclasses-1)) result = REVERSE(ROTATE(result,2)) return, result end </code></pre> <p>The stack is an array of tif files of Landsat 7 data that I load with the <code>read_tiff</code> function. The exercising data looks like this:</p> <pre><code>;Forst [ $ [39,25,21,29,14,80,12], $ [40,25,20,28,11,79,12], $ [37,24,20,29,14,81,11], $ [43,28,25,34,14,79,12], $ [44,29,29,40,13,79,13], $ [41,27,23,32,14,80,13], $ [0,0,0,0,0,0,0], $ [46,31,27,36,13,79,12] $ ], $ ... (more classes) ;Water [ $ [39,24,19,13,9,92,10], $ [37,22,19,13,9,92,10], $ [38,24,20,13,9,90,10], $ [40,24,22,15,9,89,10], $ [37,22,19,13,10,92,9], $ [38,23,20,13,10,89,9], $ [37,23,18,13,9,90,9], $ [39,25,20,13,9,90,9] $ ] $ </code></pre> <p>The program actually works, but doesn't have a good performance. This is due to the nested <code>foreach</code>-loops within the minimum_distance function. With larger satellite images it takes a very long time to process. I can imagine that you can reach a much better performance using some IDL function that I don't know of. Do you know a way in how I can give this program a better performance and replace the <code>foreach</code>-loops?</p> <p>If you want to take a look at the complete program, <a href="https://textuploader.com/1awtu" rel="nofollow noreferrer">here</a> it is.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T10:18:27.943", "Id": "212458", "Score": "3", "Tags": [ "performance", "iteration", "interactive-data-language" ], "Title": "IDL code for minimum distance calculation" }
212458
<p><a href="https://en.wikipedia.org/wiki/IDL_(programming_language)" rel="nofollow noreferrer">Interactive Data Language</a>, often abbreviated IDL, is a programming language used for data analysis.</p> <p>Don't confuse this IDL with Interface Description Language!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T11:31:21.130", "Id": "212461", "Score": "0", "Tags": null, "Title": null }
212461
For code written in Interactive Data Language (not to be confused with CORBA Interface Description Language, also abbreviated IDL).
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T11:31:21.130", "Id": "212462", "Score": "0", "Tags": null, "Title": null }
212462
<p>here I am taking 3 inputs. 1st input will take test cases and the other two input will take starting and ending range. the program is running fine as expected but the limit of this question for compilation is 1 sec, and my code is taking 5.01 sec.</p> <p>How can I make it more efficient so that I can submit the code?</p> <blockquote> <p>The challenge was to take number of test cases.</p> <p>Each test cases show take 2 input (starting and ending range) Eg: 1 4 (i.e 1,2,3,4)</p> <p>Do the bitwise XOR operation for all of them (i.e 1^2^3^4) </p> <p>Which when you perform will be equal to 4</p> <p>Now just check if it is even or odd and print the same.</p> </blockquote> <p>Here's my code:</p> <pre><code>from sys import stdin, stdout t = stdin.readline() for i in range(int(t)): p = 0 a, b = map(int,stdin.readline().split()) for x in range(a,b+1): p ^= int(x) if p % 2 == 0: stdout.write(str("Even\n")) else: stdout.write(str("Odd\n")) </code></pre> <p>compiling in python 3.6</p> <pre><code>INPUT: 4 1 4 2 6 3 3 2 3 OUTPUT: Even Even Odd Odd </code></pre> <p>Working perfectly with no issue in code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T15:01:09.413", "Id": "410984", "Score": "1", "body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have." } ]
[ { "body": "<p>The logic is straightforward and easy to follow (albeit with an unnecessary conversion of an <code>int</code> to an <code>int</code>):</p>\n\n<pre><code>p = 0\nfor x in range(a,b+1):\n p ^= x\nreturn p % 2\n</code></pre>\n\n<p>However, you could achieve the same more efficiently by noting that we're just counting how many odd numbers are in the range, and reporting whether that count is even or odd. That should suggest a simple O(1) algorithm in place of the O(<em>n</em>) algorithm you're currently using:</p>\n\n<pre><code>def count_odds(lo, hi):\n '''\n Count (modulo 2) how many odd numbers are in inclusive range lo..hi\n &gt;&gt;&gt; count_odds(0, 0)\n 0\n &gt;&gt;&gt; count_odds(0, 1)\n 1\n &gt;&gt;&gt; count_odds(1, 1)\n 1\n &gt;&gt;&gt; count_odds(0, 2)\n 1\n &gt;&gt;&gt; count_odds(1, 2)\n 1\n &gt;&gt;&gt; count_odds(2, 2)\n 0\n &gt;&gt;&gt; count_odds(0, 3)\n 2\n &gt;&gt;&gt; count_odds(1, 3)\n 2\n &gt;&gt;&gt; count_odds(2, 3)\n 1\n &gt;&gt;&gt; count_odds(3, 3)\n 1\n '''\n # if lo and hi are both odd, then we must round up,\n # but if either is even, we must round down\n return (hi + 1 - lo + (lo&amp;1)) // 2\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n</code></pre>\n\n<p>We can then use this function to index the appropriate string result:</p>\n\n<pre><code>if __name__ == '__main__':\n for _ in range(int(input())):\n a,b = map(int, input().split())\n print([\"Even\",\"Odd\"][count_odds(a,b) &amp; 1])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T15:20:50.850", "Id": "410989", "Score": "0", "body": "I lost you after \"don't use p: just p % 2, which\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T16:25:46.870", "Id": "411004", "Score": "0", "body": "@Akshansh, I've completely re-written that paragraph to make it clearer. Is that better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T10:13:34.830", "Id": "411081", "Score": "3", "body": "Since we're taking `%2` or `&1`, only the low 2 bits of `hi` and `lo` matter; if we wanted to make sure this runs fast even with huge inputs (like 1 gigabyte long BigIntegers), we could narrow them before subtracting. But that would complicate the expression and slow down Python for the normal case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T13:06:17.013", "Id": "411107", "Score": "1", "body": "Yes @Peter, I thought of that and decided that clarity was more important for me. :-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T15:08:09.403", "Id": "212469", "ParentId": "212463", "Score": "10" } }, { "body": "<p>Welcome to CR, nice challenge</p>\n\n<p>A few comments about the code</p>\n\n<ul>\n<li><p>Many unnecessary conversion</p>\n\n<p>Python is a duck typed language, if it talks like a duck, walks like a duck... it must be a duck!</p>\n\n<p>This means that</p>\n\n<blockquote>\n<pre><code>p ^= int(x)\n</code></pre>\n</blockquote>\n\n<p>Here <code>x</code> is already an <code>int</code>, same goes for the <code>str</code> conversion later</p></li>\n<li><p>Use <code>_</code> variable names for variable you don't use</p>\n\n<blockquote>\n <p><code>for i in range(int(t)):</code></p>\n</blockquote>\n\n<p>Replace the <code>i</code> with <code>_</code></p></li>\n<li><p>You could return directly</p>\n\n<blockquote>\n<pre><code>if p % 2 == 0:\n return \"Even\"\nelse:\n return \"Odd\"\n</code></pre>\n</blockquote>\n\n<p>Instead, you could do which uses a ternary operator</p>\n\n<pre><code>return \"Even\" if p % 2 == 0 else \"Odd\"\n</code></pre></li>\n<li><p>As for the speedup</p>\n\n<p>I've used <a href=\"https://stackoverflow.com/questions/10670379/find-xor-of-all-numbers-in-a-given-range\">this SO link</a> to inspire me, which does a way better job of explaining this then I could ever do</p>\n\n<p>In short there is a trick to get the XOR'd product of a certain range</p>\n\n<p>Using the method from the link, I get a massive speedup,</p>\n\n<p>For these timings: <code>range(1, 1000)</code></p>\n\n<pre><code>Bitmagic: 0.023904799999999997\nOP: 2.2717274\n</code></pre></li>\n</ul>\n\n<h1>Code</h1>\n\n<pre><code># https://stackoverflow.com/questions/10670379/find-xor-of-all-numbers-in-a-given-range\ndef bit_magic(bound):\n magic = [bound, 1, bound + 1, 0]\n return magic[bound % 4]\n\ndef bitwise_check(lower_bound, upper_bound):\n p = bit_magic(upper_bound) ^ bit_magic(lower_bound - 1)\n return \"Odd\" if p &amp; 1 else \"Even\"\n\ndef main():\n n = int(input(\"Number of testcases: \"))\n for _ in range(n):\n lower_bound, upper_bound = map(int, input().split())\n print(bitwise_check(lower_bound, upper_bound))\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T17:02:23.887", "Id": "411005", "Score": "3", "body": "For the `return` there is also the option `return [\"Even\", \"Odd\"][p]`, but that might be too cryptic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T22:50:40.190", "Id": "411026", "Score": "3", "body": "Is there an objective reason to prefer the ternary to the if/else? I, personally, find the if/else construct more readable than the ternary (which hides the conditional in the middle of the results), and from what I can tell, both ways should result in the same bytecode." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T05:01:22.277", "Id": "411045", "Score": "0", "body": "@R.M. Agreed - I think if you want to shorten that, the more idiomatic way would be to leave off the `else` (given that it's redundant with a `return` in the `if`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T11:38:48.527", "Id": "411094", "Score": "0", "body": "@R.M. Not any objective reason, I find it to be more readable but YMMV" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T11:43:06.380", "Id": "411096", "Score": "0", "body": "@PeterTaylor normally I would advice against, but since the result can be only `1` or `0` not truthy or falsey, I think it's not super cryptic :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T15:28:07.053", "Id": "212470", "ParentId": "212463", "Score": "11" } }, { "body": "<p>If one has a range 1,2,3,4 then only every first bit is interesting for the result; in concreto: whether odd or even. If the number of odd numbers is odd, the result is odd.</p>\n\n<pre><code>def even (lwb, upb):\n n = upb - lwb + 1;\n ones = (n / 2) + (0 if n % 2 == 0 else (upb &amp; 1))\n return ones % 2 == 0\n</code></pre>\n\n<p>Here <code>lwb</code> (lower bound) and <code>upb</code> (upperbound) inclusive give a range of <code>n</code> numbers (odd even odd even ... or even odd even odd ...). <code>ones</code> is the number of odd.</p>\n\n<p>This means that <em>intelligent domain information</em> can quite reduce the problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T13:39:30.440", "Id": "411116", "Score": "2", "body": "When you use `upb & 1`, you may consistently replace all `…% 2` with `… & 1`. This also allows to get rid of the conditional: `ones = (n / 2) + (n & upb & 1)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T14:21:15.960", "Id": "411125", "Score": "0", "body": "@Holger simplifies indeed. However I did not want to make the code too unreadable (needing an explanation). For instance `def odd(lwb, upb) return 1&((n>>1)^(lwb&upb))`. But indeed the odd/even test with modulo 2 is ugly looking." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T16:52:14.270", "Id": "212476", "ParentId": "212463", "Score": "11" } }, { "body": "<p>If you want to make this efficient you should avoid iterating over the range at all.</p>\n\n<p>If you notice that the Xor of four consecutive integers is always even, you can \"ignore\" them in the final Xor and in the end you only care about the bounds modulo 4, and thus only have to read 4 bits of the input.</p>\n\n<p>A one liner giving you the answer can be written as:</p>\n\n<pre><code>def answer(lo, hi):\n return \"Odd\" if (((hi ^ lo) &gt;&gt; 1) ^ hi) &amp; 1 else \"Even\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T10:51:08.713", "Id": "212531", "ParentId": "212463", "Score": "6" } } ]
{ "AcceptedAnswerId": "212531", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T12:03:19.340", "Id": "212463", "Score": "9", "Tags": [ "python", "python-3.x", "programming-challenge", "time-limit-exceeded" ], "Title": "Compute binary XOR of all integers in a range, mod 2" }
212463
<p>I'm making an online shopping store or e-commerce and I use an express session for many things. </p> <p>Example: Shopping Cart, Authentication user*</p> <p>I store the data chart list in the database based on the <code>sessionID</code> so when a user visits the website, the user does not need to log in for add to cart. </p> <p>As well as login, to check the user has logged in or not, I have checked the <code>sessionID</code> that is in the user and checked it on the database whether or not the <code>sessionID</code> is in the database.</p> <p>When logging in with Google or Facebook, I use the passport for authentication and when I am successful I store the <code>sessionID</code> to the database.</p> <p>I am using React SPA, Express.js and MySQL.</p> <p><strong>My database</strong></p> <p><strong>Table Session</strong></p> <p><a href="https://i.stack.imgur.com/pa7xO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pa7xO.png" alt="Table Session"></a></p> <p><strong>Table Session Browser</strong></p> <p><a href="https://i.stack.imgur.com/5Ur3X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Ur3X.png" alt="Table Session Browser"></a></p> <p><strong>Table User</strong></p> <p><a href="https://i.stack.imgur.com/xWT3J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xWT3J.png" alt="Table User"></a></p> <p><strong>Table User Session</strong></p> <p><a href="https://i.stack.imgur.com/VpCX4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VpCX4.png" alt="Table user session"></a></p> <p><strong>Table Cart</strong></p> <p><a href="https://i.stack.imgur.com/TiE0m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TiE0m.png" alt="Table Cart"></a></p> <p>Is what I'm doing correct? And what about the passport? Because as far as I know the passport uses the Headers Authorization token.</p> <p>Example add to cart:</p> <pre><code>export const addToCart = (req,res) =&gt;{ let ip_address = req.headers['x-forwarded-for'] || req.connection.remoteAddress; let ua = UAparser(req.headers['user-agent']); if (ip_address.substr(0, 7) == "::ffff:") { ip_address = ip_address.substr(7) } let querySelectSession = ` SELECT ss.id,ss.ip_address from session as ss LEFT JOIN session_browser as sb on ss.id = sb.session_id LEFT JOIN session_os as so on ss.id = sb.session_id LEFT JOIN session_engine as se on ss.id = se.session_id LEFT JOIN session_device as sd on ss.id = se.session_id where ss.ip_address = '${ip_address}' and ss.id = '${req.sessionID}' and sb.name = '${ua.browser.name}' and sb.version = '${ua.browser.version}' and so.name = '${ua.os.name}' and so.version = '${ua.os.version}' and se.name = '${ua.engine.name}' and se.version = '${ua.engine.version}' ${ua.device.model ? ` and sd.model='${ua.device.model}'` : ''} ${ua.device.type ? ` and sd.type='${ua.device.type}'` : ''} ${ua.device.vendor ? ` and sd.vendor='${ua.device.vendor}'` : ''} group by ss.id,ss.ip_address`; let queryCheckCart = `select crt.id from carts as crt where crt.session_id = '${req.sessionID}'`; let queryCheckCartList = `select ci.product_id,ci.product_variant_id,ci.product_attribute_id from cart_items as ci where cart_id = (select crt.id from carts as crt where crt.session_id = '${req.sessionID}') and ci.product_id = ${req.body.product_id} and ci.product_variant_id = ${req.body.product_variant_id} and ci.product_attribute_id = ${req.body.product_attribute_id}`; let queryInsertSession = `INSERT INTO session (id,ip_address) values ('${req.sessionID}','${ip_address}')`; let queryAddToCart = `INSERT INTO carts (session_id,active) values ('${req.sessionID}',1)`; let queryAddCartList = `INSERT INTO cart_items (product_id,product_variant_id,product_attribute_id,cart_id,quantity) SELECT ${req.body.product_id},${req.body.product_variant_id},${req.body.product_attribute_id},(SELECT crt.id from carts as crt where crt.session_id = '${req.sessionID}'),1 where (select pa.stock from product_attribute as pa where pa.id = ${req.body.product_attribute_id}) &gt;= 1 `; let queryInsertAll = `${queryAddToCart}; ${queryAddCartList};`; let queryUpdateCartList = `UPDATE cart_items as ci set ci.quantity = ci.quantity+1 where ci.cart_id = (select crt.id from carts as crt where crt.session_id = '${req.sessionID}') and ci.product_id = ${req.body.product_id} and ci.product_variant_id = ${req.body.product_variant_id} and ci.product_attribute_id = ${req.body.product_attribute_id} and (select pa.stock from product_attribute as pa where pa.id = ${req.body.product_attribute_id}) &gt;= ci.quantity+1 `; let queryFindCartList =`select ci.id as cart_items_id, p.name as product_name, p.slug as product_slug, p.description, p.regular_price, c.name as category_name, c.slug, pv.type, pd.discount_percentage, pd.discount_value, i.link,i.caption,i.alt,pa.size,pa.stock,crt.active as cart_status,ci.quantity from products as p left join product_category as pc on p.id = pc.product_id left join categories as c on pc.category_id = c.id left join product_variant as pv on p.id = pv.product_id left join product_discount as pd on pd.id = (SELECT pd1.id from product_discount as pd1 where p.id = pd1.id and now() between pd1.valid_from and pd1.valid_until) left join product_image as pi on pi.id = (SELECT pi1.id from product_image as pi1 where pi1.product_id = p.id order by pi1.product_id asc limit 1) left join images as i on pi.image_id = i.id left join product_attribute as pa on p.id = pa.product_id and pv.id = pa.product_variant_id left join cart_items as ci on pv.id = ci.product_variant_id and p.id = ci.product_id and pa.id = ci.product_attribute_id left join carts as crt on ci.cart_id = (SELECT crt1.id from carts as crt1 where crt1.session_id = '${req.sessionID}' ) where crt.session_id = '${req.sessionID}' and ci.quantity &lt;= pa.stock `; let queryChecking = `${querySelectSession};${queryCheckCart}; ${queryCheckCartList}; ${queryFindCartList};`; db.query(queryChecking,(error,result)=&gt;{ if(error) return res.status(400).json(error); if(result[0].length &gt; 0 &amp;&amp; result[1].length &gt; 0 &amp;&amp; result[2].length === 0 &amp;&amp; result[3].length &lt; 15){ db.query(queryAddCartList,(error,result)=&gt;{ if (error) return res.status(400).json(error); if (result) { db.query(queryFindCartList, (error, result) =&gt; { if (error) return res.status(400).json(error); if (result.length &gt; 0) { let payload = { session_id: req.sessionID, ip_address: ip_address } let dataToken = jwt.sign(payload, keys.jwt.secretOrPrivateKey, { expiresIn: keys.jwt.expiresIn }); res.cookie("hammerstout_ss", dataToken, { sameSite: true }); let token_cart = { result }; let notification = { error: false, message: "ADDED TO YOUR CART.", notification: true } let token_c = jwt.sign(token_cart, keys.jwt.secretOrPrivateKey, { expiresIn: keys.jwt.expiresIn }); return res.status(200).json({ cart_list: result, status: 'OK', notification: notification, token_c}); } }) } }) } else if (result[0].length &gt; 0 &amp;&amp; result[1].length === 0 &amp;&amp; result[2].length === 0 &amp;&amp; result[3].length &lt; 15){ db.query(queryInsertAll,(error,result)=&gt;{ if (error) return res.status(400).json(error); if (result[0].affectedRows &gt; 0 &amp;&amp; result[1].affectedRows &gt; 0){ db.query(queryFindCartList, (error, result) =&gt; { if (error) return res.status(400).json(error); if (result.length &gt; 0) { let payload = { session_id: req.sessionID, ip_address: ip_address } let dataToken = jwt.sign(payload, keys.jwt.secretOrPrivateKey, { expiresIn: keys.jwt.expiresIn }); res.cookie("hammerstout_ss", dataToken, { sameSite: true }); let token_cart = { result }; let notification = { error: false, message: "ADDED TO YOUR CART.", notification: true } let token_c = jwt.sign(token_cart, keys.jwt.secretOrPrivateKey, { expiresIn: keys.jwt.expiresIn }); return res.status(200).json({ cart_list: result, status: 'OK', notification: notification, token_c}); } }) } else if (result[0].affectedRows === 0){ let notification = { error: true, message: "ERROR CART", notification: true } return res.status(400).json({ notification: notification }); } else if (result[1].affectedRows === 0){ let notification = { error: true, message: "IS OUT OF STOCK !", notification: true } return res.status(400).json({ notification: notification}); } }) } else if (result[0].length &gt; 0 &amp;&amp; result[1].length &gt; 0 &amp;&amp; result[2].length &gt; 0 ){ db.query(queryUpdateCartList,(error,result)=&gt;{ if (error) return res.status(400).json(error); if (result.affectedRows &gt; 0){ db.query(queryFindCartList, (error, result) =&gt; { if (error) return res.status(400).json(error); if (result.length &gt; 0) { let payload = { session_id: req.sessionID, ip_address: ip_address } let dataToken = jwt.sign(payload, keys.jwt.secretOrPrivateKey, { expiresIn: keys.jwt.expiresIn }); res.cookie("hammerstout_ss", dataToken, { sameSite: true }); let token_cart = { result }; let notification = { error: false, message: "ADDED TO YOUR CART.", notification: true } let token_c = jwt.sign(token_cart, keys.jwt.secretOrPrivateKey, { expiresIn: keys.jwt.expiresIn }); return res.status(200).json({ cart_list: result, status: 'OK', notification: notification, token_c}); } }) } else if (result.affectedRows === 0) { let notification = { error: true, message: "IS OUT OF STOCK !", notification: true } return res.status(400).json({ notification: notification }); } }) } else if (result[0].length &gt; 0 &amp;&amp; result[1].length &gt; 0 &amp;&amp; result[3].length &gt;= 15 ){ let notification = { error: true, message: "Already the maximum limit", notification: true } return res.status(400).json({ notification: notification }); } else{ return res.status(400).json(result); } }) } </code></pre>
[]
[ { "body": "<p>Thanks for your first submission for review.</p>\n\n<hr>\n\n<p>First and foremost, the thing that really jumps out at me is that this function is doing WAY too many different things. You likely should be considering different Express middleware functions to do things like:</p>\n\n<ul>\n<li>decorate IP address determination and decoration onto <code>req</code></li>\n<li>user agent parsing and decoration onto <code>req</code></li>\n<li>session ID determination, database update, and decoration onto <code>req</code></li>\n</ul>\n\n<p>...etc.</p>\n\n<hr>\n\n<p>Do you do any validation on <code>req.body</code> at all outside of this function? You are taking a potential dangerous path in there is no input validation here.</p>\n\n<hr>\n\n<p>The code is VERY hard to read. It is not indented well (particularly around SQL queries), has no comments, and has inconsistent use of vertical whitespace to separate logical sections.</p>\n\n<hr>\n\n<p>You have many more nested if-else conditions than are needed. You should always that about inverting conditions to de-nest things, and should use <code>return</code> appropriately to de-nest. Code with this many branches is going to be very fragile to maintain and extremely difficult to test all those code paths.</p>\n\n<p>You have some case where you are doing this well like</p>\n\n<blockquote>\n<pre><code>db.query(queryChecking,(error,result)=&gt;{\n if(error) return res.status(400).json(error);\n if(result[0].length &gt; 0 &amp;&amp; result[1].length &gt; 0 &amp;&amp; result[2].length === 0 &amp;&amp; result[3].length &lt; 15){\n</code></pre>\n</blockquote>\n\n<p>Here you exit early on error condition and let the rest of the code proceed without being in an else condition.</p>\n\n<p>However in most places in code you have this sort of pattern</p>\n\n<pre><code>if (...) {\n ...\n return;\n} else if (...) {\n ...\n return;\n} else if (...) {\n ...\n return;\n}\n</code></pre>\n\n<p>This should be</p>\n\n<pre><code>if (...) {\n ...\n return;\n}\nif (...) {\n ...\n return;\n}\nif (...) {\n ...\n return;\n}\n</code></pre>\n\n<p>There is no need for most of your else conditions if you are making a return in from the previous conditional statement.</p>\n\n<hr>\n\n<p>Many of your <code>let</code> declarations could and should be <code>const</code> when the variables are not intended to ever be reassigned.</p>\n\n<hr>\n\n<p>Besides these code issues noted, I am struggling to understand what you are trying to achieve here.</p>\n\n<p>What does a cart have to do with a session or a login at all?</p>\n\n<p>Why tie something that perhaps should persist across sessions to a given session?</p>\n\n<p>How do you handle updating carts around events that should regenerate session id's like logins/logouts?</p>\n\n<p>How do you handle session expiry?</p>\n\n<p>Why is Session Browser \"normalized\" into it's own table when it seems there would be 1:1 relationship with session?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T09:04:38.603", "Id": "412043", "Score": "0", "body": "How do you handle updating carts around events that should regenerate session id's like logins/logouts? I send cookies to the client and when the cookie is successfully retrieved and update the sessionID on the cart. Is this correct?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T17:31:10.913", "Id": "212642", "ParentId": "212471", "Score": "1" } } ]
{ "AcceptedAnswerId": "212642", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T15:28:08.813", "Id": "212471", "Score": "1", "Tags": [ "javascript", "mysql", "node.js", "express.js" ], "Title": "Authentication using express-session" }
212471
<p>I'm a newbie in servlet API. I have a test task to create a very simple web app with one home page and an authorization form. The requirement is to use filter somewhere in my app.<br/><br/> Given that it's a super simple app, I implemented basic login and registration functions right in my filter (it was a much simpler way for me to do it).<br/><br/> Here is the question: can I do this at all according to the best practices? Or should I only leave the cookie check in the filter and move all other functions to separate servlets? Is it necessary?</p> <p>The filter itself:</p> <pre><code>@WebFilter("/") public class Filter implements javax.servlet.Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) request; final HttpServletResponse resp = (HttpServletResponse) response; @SuppressWarnings("unchecked") final AtomicReference&lt;UserDAO&gt; dao = (AtomicReference&lt;UserDAO&gt;) req.getServletContext().getAttribute("dao"); final String username = req.getParameter("username"); final String password = req.getParameter("password"); final String action = req.getParameter("action"); final String remember = req.getParameter("remember"); //Just in case final String path = req.getRequestURI().substring(req.getContextPath().length()); if (path.startsWith("/resources/")) { filterChain.doFilter(request, response); // Goes to default servlet. } final Cookie[] cookies = req.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (dao.get().checkUserById(cookie.getName()) &amp;&amp; !cookie.getValue().isEmpty()) { req.setAttribute("username", dao.get().getUsernameById(cookie.getName())); req.getRequestDispatcher("/WEB-INF/view/home.jsp").forward(req, resp); } } } if ((username != null) &amp;&amp; (password != null) &amp;&amp; (action != null)) { req.setAttribute("username", username); if (action.equals("registration")) { if (!dao.get().checkUserByUsername(username)) { final String id = Integer.toString(dao.get().getSize() + 1); final User user = new User(id, username, password); dao.get().add(user); if (remember != null &amp;&amp; remember.equals("on")) { Cookie cookie = getRememberMeCookie(id, username, password); resp.addCookie(cookie); } req.getRequestDispatcher("/WEB-INF/view/home.jsp").forward(req, resp); } else { req.getRequestDispatcher("/WEB-INF/view/login-form.jsp?registration").forward(req, resp); } } else if (action.equals("login")) { if (dao.get().checkUserByUsernameAndPassword(username, password)) { String id = dao.get().getIdByUsername(username); if (remember != null &amp;&amp; remember.equals("on")) { Cookie cookie = getRememberMeCookie(id, username, password); resp.addCookie(cookie); } req.getRequestDispatcher("/WEB-INF/view/home.jsp").forward(req, resp); } else { req.getRequestDispatcher("/WEB-INF/view/login-form.jsp?login").forward(req, resp); } } } else { req.getRequestDispatcher("/WEB-INF/view/login-form.jsp").forward(req, resp); } } @Override public void destroy() { } private String md5Hash(String username, String password) throws NoSuchAlgorithmException { String entryData = username + "md5Cookie" + password; MessageDigest m = MessageDigest.getInstance("MD5"); byte[] data = entryData.getBytes(); m.update(data,0,data.length); BigInteger i = new BigInteger(1,m.digest()); return String.format("%1$032X", i); } private Cookie getRememberMeCookie(String id, String username, String password) { String md5CookieValue = null; try { md5CookieValue = md5Hash(username, password); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } final Cookie cookie = new Cookie(id, md5CookieValue); cookie.setMaxAge(60 * 60 * 24 * 15); return cookie; } } </code></pre> <p>I think almost all code after line 47 can be moved to separate servlets, just need a confirmation. <br/><br/> P.S. Logic is awful, I know. I'm newbie after all :)</p>
[]
[ { "body": "<p>Quickfire opinions:</p>\n\n<ul>\n<li>Don't use MD5 for anything. MD5 is cryptographically broken. Especially do not put passwords through it.</li>\n<li>Don't use passwords to generate an authentication token. Use a <code>SecureRandom</code> in conjunction with the claimed ID. Keep a server-side copy of the salt and check the authentication token on every request.</li>\n<li>Only require the password once and try to purge it from memory as soon as possible. This implies removing it from the <code>req</code></li>\n<li><p>Use \"guard clauses\" to reduce the level of nesting in your methods and to return early. This allows you to reduce the amount of context you need to keep in your head when reading a given piece of code. Note that since java7 switch-case statements can also operate on Strings.<br>\nThis simplifies the checks for content:</p>\n\n<pre><code>if (username == null || password == null || action == null) {\n req.getRequestDispatcher(\"/WEB-INF/view/login-form.jsp\").forward(req, resp);\n return;\n}\nreq.setAttribute(\"username\", username);\nswitch (action) {\n case \"registration\":\n if (dao.get().checkUserByUsername(username)) {\n req.getRequestDispatcher(\"/WEB-INF/view/login-form.jsp?registration\").forward(req, resp);\n return;\n }\n // [...]\n</code></pre></li>\n<li><p>Extract the technicalities of generating an AuthenticationToken into a separate class. Usually that class would either be static or injected through some kind of dependency injection mechanism.\nIt can also be used to provide facilities for checking a given token.</p></li>\n<li>A <code>Filter</code> would make sense to <strong>check</strong> for authentication. To authenticate a request or to create a new user is something more suited to a Servlet. </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T08:43:48.140", "Id": "411063", "Score": "0", "body": "Thank you for such an answer!\nNever expected to get such a full explanation.\nRegarding the last point:\nSo I need to leave cookie check in the filter and move\neverything regarding authentication and registration to separate servlets, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T09:13:26.330", "Id": "411073", "Score": "0", "body": "Yes. A Filter changes a request, a servlet handles it. Login and registration are actions, authorization is a change" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T09:09:09.067", "Id": "411259", "Score": "0", "body": "One more stupid question :)\nWhy do we need `return;` statement in the code you provided?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T10:19:27.460", "Id": "411264", "Score": "0", "body": "And what do you think about thread-safety? Is it more or less enough for such kind of an app to declare variables final in filter and servlets and be done with it?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T10:41:52.910", "Id": "411269", "Score": "0", "body": "The return statement is necessary to allow removing the explicit `else`. If there was no return statement, the code after the closing brace of the if-block would need to be put into an else block to do the same thing. IIRC all application servers out there handle thread safety of Request and Response correctly. Local variables can not have any problems with thread-safety, that's just not how they work. As such the code you have is perfectly threadsafe already" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T18:30:15.740", "Id": "212479", "ParentId": "212475", "Score": "2" } } ]
{ "AcceptedAnswerId": "212479", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T15:59:45.303", "Id": "212475", "Score": "2", "Tags": [ "java", "beginner", "authentication", "session", "servlets" ], "Title": "Implementation of login and registration functions in servlet filter" }
212475
<p>In order to get a hang of the ECS paradigm of game making, I decided to try my hand at making a clone of Tetris. I am using the <code>specs</code> crate for Rust in order to facilitate this.</p> <p>The game is on a non-standard 10x10 grid, played in the terminal (although the rendering function is omitted because it's 100 lines long and not really what I'm interested in).</p> <p>Without further ado, here are the files. First, <code>main.rs</code>, containing all the setup and the core game loop.</p> <pre><code>extern crate rand; use std::time::{SystemTime, Duration}; extern crate specs; use specs::{World, DispatcherBuilder}; extern crate termion; use termion::{async_stdin, raw::IntoRawMode}; use std::io::{Read, stdout}; mod components; use components::{Cell, Fixed, Tetromino, Next, Center, Score, IsGameOver, ReadyForNext}; mod systems; use systems::{GameStart, MoveDown, MoveRight, MoveLeft, Rotate, ClearRow, Render, ShouldFix, Fix, GameEnd, NewTetro}; fn main() { let mut stdin = async_stdin().bytes(); let _stdout = stdout().into_raw_mode().unwrap(); let mut world = World::new(); world.register::&lt;Cell&gt;(); world.register::&lt;Fixed&gt;(); world.register::&lt;Tetromino&gt;(); world.register::&lt;Next&gt;(); world.register::&lt;Center&gt;(); world.add_resource(IsGameOver(false)); world.add_resource(ReadyForNext(true)); world.add_resource(Score(0)); let mut start = DispatcherBuilder::new() .with(GameStart, "starter", &amp;[]) .build(); let mut progress = DispatcherBuilder::new() .with(ShouldFix, "fixer", &amp;[]) .with(Fix, "fix", &amp;["fixer"]) .with(GameEnd, "ender", &amp;["fix"]) .with(NewTetro, "new", &amp;["ender"]) .with(MoveDown, "move_down", &amp;["new"]) .with(ClearRow, "clear_row", &amp;["move_down"]) .with(Render, "render", &amp;["clear_row"]) .build(); let mut move_left = DispatcherBuilder::new() .with(MoveLeft, "move_left", &amp;[]) .with(Render, "render", &amp;["move_left"]) .build(); let mut move_right = DispatcherBuilder::new() .with(MoveRight, "move_right", &amp;[]) .with(Render, "render", &amp;["move_right"]) .build(); let mut rotate = DispatcherBuilder::new() .with(Rotate, "rotate", &amp;[]) .with(Render, "render", &amp;["rotate"]) .build(); start.dispatch(&amp;mut world.res); world.maintain(); let mut last_update = SystemTime::now(); while !world.read_resource::&lt;IsGameOver&gt;().0 { if let Some(Ok(k)) = stdin.next() { match k { 65 =&gt; { rotate.dispatch(&amp;mut world.res); world.maintain(); }, 66 =&gt; { progress.dispatch(&amp;mut world.res); world.maintain(); last_update = SystemTime::now(); }, 67 =&gt; { move_right.dispatch(&amp;mut world.res); world.maintain(); }, 68 =&gt; { move_left.dispatch(&amp;mut world.res); world.maintain(); }, 13 | 3 =&gt; break, _ =&gt; {} } } if let Ok(d) = SystemTime::now().duration_since(last_update) { if d &gt; Duration::from_millis(1000) { progress.dispatch(&amp;mut world.res); world.maintain(); last_update = SystemTime::now(); } } } } </code></pre> <p>Next is the file <code>components.rs</code>, containing all the component definitions.</p> <pre><code>use specs::{Component, VecStorage, NullStorage}; #[derive(Default)] pub struct IsGameOver(pub bool); #[derive(Default)] pub struct Score(pub u32); #[derive(Default)] pub struct ReadyForNext(pub bool); // A single active cell in the tetris game. // Empty cells are not stored. #[derive(Debug)] pub struct Cell { pub x: i8, pub y: i8, } impl Component for Cell { type Storage = VecStorage&lt;Self&gt;; } // Flag for cells which have landed and stuck #[derive(Default)] pub struct Fixed; impl Component for Fixed { type Storage = NullStorage&lt;Self&gt;; } // Flag for cells which are part of a falling tetromino #[derive(Default)] pub struct Tetromino; impl Component for Tetromino { type Storage = NullStorage&lt;Self&gt;; } // The rotational center cell of a tetromino // A tetromino doesn't always rotate about the center // of any given cell, which is what the offset // is for. And there are four offset coordinates to // make sure that rotating a tetromino four times // (twice for T and I blocks, and once for O block) // takes it back to where it started #[derive(Default)] pub struct Center { pub rot_offset: [(i8, i8); 4], pub offset_index: usize, } impl Component for Center { type Storage = VecStorage&lt;Self&gt;; } // Flag for cells which are part of the next tetromino #[derive(Default)] pub struct Next; impl Component for Next { type Storage = NullStorage&lt;Self&gt;; } </code></pre> <p>And finally, the <code>systems.rs</code> file, containing all the systems.</p> <pre><code>use rand::Rng; use specs::{System, ReadStorage, WriteStorage, Join, Entities, Write as WriteResource, Read as ReadResource}; use super::components::*; use termion::{color, cursor, clear, style}; // Starts the game with one tetromino at the // top and one tetromino as next. pub struct GameStart; impl&lt;'a&gt; System&lt;'a&gt; for GameStart { type SystemData = (WriteStorage&lt;'a, Cell&gt;, WriteStorage&lt;'a, Tetromino&gt;, WriteStorage&lt;'a, Next&gt;, WriteStorage&lt;'a, Center&gt;, Entities&lt;'a&gt;); fn run(&amp;mut self, (mut cells, mut tetros, mut nexts, mut centers, ents): Self::SystemData) { let mut rand = rand::thread_rng(); let r: usize = rand.gen_range(0, 7); for i in 0..4 { let ent = ents.create(); nexts.insert(ent, Next {}) .expect("Couldn't make new 'next' tetromino"); cells.insert(ent, Cell { x: NEW_COORDS[r][i].0, y: NEW_COORDS[r][i].1 }) .expect("Couldn't make new 'next' tetromino"); if i == 0 { centers.insert(ent, Center { rot_offset: ROT_OFFSET[r], offset_index: 0 }) .expect("Couldn't make new 'next' tetromino"); } } let r: usize = rand.gen_range(0, 7); for i in 0..4 { let ent = ents.create(); tetros.insert(ent, Tetromino {}) .expect("Couldn't make new 'next' tetromino"); cells.insert(ent, Cell { x: NEW_COORDS[r][i].0 - 10, y: NEW_COORDS[r][i].1 + 2}) .expect("Couldn't make new 'next' tetromino"); if i == 0 { centers.insert(ent, Center { rot_offset: ROT_OFFSET[r], offset_index: 0 }) .expect("Couldn't make new 'next' tetromino"); } } } } // Moves the tetromino down one unit, // if there is space pub struct MoveDown; impl&lt;'a&gt; System&lt;'a&gt; for MoveDown { type SystemData = (WriteStorage&lt;'a, Cell&gt;, ReadStorage&lt;'a, Tetromino&gt;, ReadResource&lt;'a, ReadyForNext&gt;, ReadResource&lt;'a, IsGameOver&gt;); fn run(&amp;mut self, (mut cells, tetros, ready_for_next, game_over): Self::SystemData) { if game_over.0 | ready_for_next.0 { return; } for (cell, _tetro) in (&amp;mut cells, &amp;tetros).join() { cell.y = cell.y-1; } } } // Moves a tetromino right one unit, // if there is room pub struct MoveRight; impl&lt;'a&gt; System&lt;'a&gt; for MoveRight { type SystemData = (WriteStorage&lt;'a, Cell&gt;, ReadStorage&lt;'a, Tetromino&gt;, ReadStorage&lt;'a, Fixed&gt;, ReadResource&lt;'a, IsGameOver&gt;); fn run(&amp;mut self, (mut cells, tetros, fixeds, game_over): Self::SystemData) { if game_over.0 { return; } let mut tetro_coords = Vec::new(); for (cell, _tetro) in (&amp;cells, &amp;tetros).join() { if cell.x == 9 { return; } tetro_coords.push((cell.x+1, cell.y)); } for (cell, _fixed) in (&amp;cells, &amp;fixeds).join() { if tetro_coords.contains(&amp;(cell.x, cell.y)) { return; } } for (cell, _tetro) in (&amp;mut cells, &amp;tetros).join() { cell.x = cell.x + 1; } } } // Moves a tetromino left one unit, // if there is room pub struct MoveLeft; impl&lt;'a&gt; System&lt;'a&gt; for MoveLeft { type SystemData = (WriteStorage&lt;'a, Cell&gt;, ReadStorage&lt;'a, Tetromino&gt;, ReadStorage&lt;'a, Fixed&gt;, ReadResource&lt;'a, IsGameOver&gt;); fn run(&amp;mut self, (mut cells, tetros, fixeds, game_over): Self::SystemData) { if game_over.0 { return; } let mut tetro_coords = Vec::new(); for (cell, _tetro) in (&amp;cells, &amp;tetros).join() { if cell.x == 0 { return; } tetro_coords.push((cell.x-1, cell.y)); } for (cell, _fixed) in (&amp;cells, &amp;fixeds).join() { if tetro_coords.contains(&amp;(cell.x, cell.y)) { return; } } for (cell, _tetro) in (&amp;mut cells, &amp;tetros).join() { cell.x = cell.x - 1; } } } // Rotates a tetromino ninety degrees, // if there is room pub struct Rotate; impl&lt;'a&gt; System&lt;'a&gt; for Rotate { type SystemData = (WriteStorage&lt;'a, Cell&gt;, ReadStorage&lt;'a, Tetromino&gt;, ReadStorage&lt;'a, Fixed&gt;, WriteStorage&lt;'a, Center&gt;, ReadResource&lt;'a, IsGameOver&gt;); fn run(&amp;mut self, (mut cells, tetros, fixeds, mut centers, game_over): Self::SystemData) { if game_over.0 { return; } let mut center_coord: (i8, i8) = (0, 0); let mut rot_offset: (i8, i8) = (0, 0); for (cell, _tetro, center) in (&amp;cells, &amp;tetros, &amp;centers).join() { center_coord = (cell.x, cell.y); rot_offset = center.rot_offset[center.offset_index]; } let mut tetro_coords = Vec::new(); for (cell, _tetro) in (&amp;cells, &amp;tetros).join() { tetro_coords.push((center_coord.0 + center_coord.1 - cell.y + rot_offset.0, center_coord.1 + cell.x - center_coord.0 + rot_offset.1)); if let Some(&amp;(x, y)) = tetro_coords.last() { if (x &lt; 0) | (x &gt;= 10) | (y &lt; 0) { return; } } } for (cell, _fixed) in (&amp;cells, &amp;fixeds).join() { if tetro_coords.contains(&amp;(cell.x, cell.y)) { return; } } for (cell, _tetro) in (&amp;mut cells, &amp;tetros).join() { let new_x = center_coord.0 + center_coord.1 - cell.y + rot_offset.0; cell.y = center_coord.1 + cell.x - center_coord.0 + rot_offset.1; cell.x = new_x; } for (_tetro, center) in (&amp;tetros, &amp;mut centers).join() { center.offset_index += 1; if center.offset_index &gt;= 4 { center.offset_index -= 4; } } } } // Checks if the current tetromino should be fixed pub struct ShouldFix; impl&lt;'a&gt; System&lt;'a&gt; for ShouldFix { type SystemData = (ReadStorage&lt;'a, Cell&gt;, ReadStorage&lt;'a, Tetromino&gt;, ReadStorage&lt;'a, Fixed&gt;, WriteResource&lt;'a, ReadyForNext&gt;); fn run(&amp;mut self, (cells, tetros, fixeds, mut ready_for_next): Self::SystemData) { let mut tetro_coords = Vec::new(); let mut should_fix = false; for (cell, _tetro) in (&amp;cells, &amp;tetros).join() { if cell.y == 0 { should_fix = true; } tetro_coords.push((cell.x, cell.y - 1)); } for (cell, _fixed) in (&amp;cells, &amp;fixeds).join() { if tetro_coords.contains(&amp;(cell.x, cell.y)) { should_fix = true; } } ready_for_next.0 = should_fix; } } // Fixes the next tetromino if ShouldFix figured out it ought to pub struct Fix; impl&lt;'a&gt; System&lt;'a&gt; for Fix { type SystemData = (WriteStorage&lt;'a, Cell&gt;, WriteStorage&lt;'a, Tetromino&gt;, WriteStorage&lt;'a, Center&gt;, WriteStorage&lt;'a, Fixed&gt;, Entities&lt;'a&gt;, ReadResource&lt;'a, ReadyForNext&gt;); fn run(&amp;mut self, (cells, mut tetros, mut centers, mut fixeds, ents, ready_for_next): Self::SystemData) { if !ready_for_next.0 { return; } for _ in (&amp;cells, &amp;ents, &amp;tetros, centers.drain()).join() {} for (_cell, ent, _tetro) in (&amp;cells, &amp;ents, tetros.drain()).join() { fixeds.insert(ent, Fixed {}) .expect("Couldn't fix tetromino"); } } } // Checks if the game ought to end pub struct GameEnd; impl&lt;'a&gt; System&lt;'a&gt; for GameEnd { type SystemData = (ReadStorage&lt;'a, Cell&gt;, ReadStorage&lt;'a, Fixed&gt;, ReadStorage&lt;'a, Next&gt;, ReadResource&lt;'a, ReadyForNext&gt;, WriteResource&lt;'a, IsGameOver&gt;); fn run(&amp;mut self, (cells, fixeds, nexts, ready_for_next, mut is_game_over): Self::SystemData) { if !ready_for_next.0 { return; } let mut fixed_coords = Vec::new(); for (cell, _fixed) in (&amp;cells, &amp;fixeds).join() { fixed_coords.push((cell.x, cell.y)); } for (cell, _next) in (&amp;cells, &amp;nexts).join() { if fixed_coords.contains(&amp;(cell.x - 10, cell.y + 1)) { is_game_over.0 = true; } } } } // Puts the "next" tetromino into play, // if there is need and room, and makes a new "next" pub struct NewTetro; impl&lt;'a&gt; System&lt;'a&gt; for NewTetro { type SystemData = (WriteStorage&lt;'a, Cell&gt;, WriteStorage&lt;'a, Tetromino&gt;, WriteStorage&lt;'a, Next&gt;, WriteStorage&lt;'a, Center&gt;, Entities&lt;'a&gt;, ReadResource&lt;'a, ReadyForNext&gt;, ReadResource&lt;'a, IsGameOver&gt;); fn run(&amp;mut self, (mut cells, mut tetros, mut nexts, mut centers, ents, ready_for_next, is_game_over): Self::SystemData) { if !ready_for_next.0 | is_game_over.0 { return; } for (cell, ent, _next) in (&amp;mut cells, &amp;ents, nexts.drain()).join() { cell.x -= 10; cell.y += 1; tetros.insert(ent, Tetromino {}) .expect("Couldn't start next tetromino"); } let mut rand = rand::thread_rng(); let r: usize = rand.gen_range(0, 7); for i in 0..4 { let ent = ents.create(); nexts.insert(ent, Next {}) .expect("Couldn't make new 'next' tetromino"); cells.insert(ent, Cell { x: NEW_COORDS[r][i].0, y: NEW_COORDS[r][i].1 }) .expect("Couldn't make new 'next' tetromino"); if i == 0 { centers.insert(ent, Center { rot_offset: ROT_OFFSET[r], offset_index: 0 }) .expect("Couldn't make new 'next' tetromino"); } } } } const NEW_COORDS: [[(i8, i8); 4];7] = [[(15, 8), (14, 8), (13, 8), (15, 7)], // J [(13, 8), (14, 8), (15, 8), (13, 7)], // L [(14, 8), (13, 8), (15, 8), (16, 8)], // I [(14, 7), (13, 7), (15, 7), (14, 8)], // T [(14, 7), (13, 7), (14, 8), (15, 8)], // Z [(14, 8), (13, 8), (14, 7), (15, 7)], // S [(14, 8), (15, 8), (15, 7), (14, 7)]];// O const ROT_OFFSET: [[(i8, i8); 4]; 7] = [[(-1, 0), (0, -1), (1, 0), (0, 1)], [(0, -1), (1, 0), (0, 1), (-1, 0)], [(0, 0), (1, 0), (-1, 1), (0, -1)], [(0, 0); 4], [(1, 1), (-1, 0), (0, 0), (0, -1)], [(0, 0), (0, -1), (1, 1), (-1, 0)], [(0, -1), (1, 0), (0, 1), (-1, 0)]]; pub struct ClearRow; impl&lt;'a&gt; System&lt;'a&gt; for ClearRow { type SystemData = (WriteStorage&lt;'a, Cell&gt;, ReadStorage&lt;'a, Fixed&gt;, Entities&lt;'a&gt;, WriteResource&lt;'a, Score&gt;); fn run(&amp;mut self, (mut cells, fixeds, ents, mut score): Self::SystemData) { let mut cleared_rows: u32 = 0; let mut filled_rows = [0 as u8; 10]; for(cell, _fixed) in (&amp;cells, &amp;fixeds).join() { if cell.y &lt; 10 { filled_rows[cell.y as usize] += 1; } } // (*) for i in (0..10).filter(|i| filled_rows[*i as usize] == 10).rev() { let mut ents_to_delete = Vec::new(); cleared_rows += 1; for (cell, _fixed, ent) in (&amp;mut cells, &amp;fixeds, &amp;ents).join() { if cell.y as usize == i { ents_to_delete.push(ent); } else if cell.y as usize &gt; i { cell.y -= 1; } } for ent in ents_to_delete { cells.remove(ent); ents.delete(ent) .expect("Couldn't delete row"); } } score.0 += cleared_rows*(cleared_rows + 1)*50; } } // Prints all the cells to the standard output (terminal) pub struct Render; impl&lt;'a&gt; System&lt;'a&gt; for Render { type SystemData = (ReadStorage&lt;'a, Cell&gt;, ReadStorage&lt;'a, Tetromino&gt;, ReadStorage&lt;'a, Fixed&gt;, ReadStorage&lt;'a, Next&gt;, ReadResource&lt;'a, IsGameOver&gt;, ReadResource&lt;'a, Score&gt;); fn run(&amp;mut self, (cells, tetros, fixeds, nexts, is_game_over, score): Self::SystemData) { // Omitted in this post. } } </code></pre> <p>Any kind of feedback would be good to have, but I have a few specific things I'm worrying about:</p> <ul> <li>There is a loop in the <code>run()</code> method of <code>ClearRow</code> annotated with a <code>(*)</code> comment. Here I had a comment from past me saying this was "easy" to do with a single <code>for</code> loop rather than a nested loop. But apparently a comment was too small a space to contain any hints to future me as to how this was supposed to be achieved. Is this feasible, or was past me wrong?</li> <li>The <code>progress</code> dispatch, whose task is to progress the game by one frame, is a bit too big and chaotic for my taste. It does many things, possibly in the wrong order (not that I have noticed any bugs), and juggles two separate flags as it does so, both of which basically turns entire functions on or off. But i tried refactoring it, and that basically just ended in me calling the same several dispatches one after the other each time instead. So is it acceptable?</li> <li>Is the code "Rust-y"?</li> <li>I should probably have more files, shouldn't I?</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T17:39:54.027", "Id": "212477", "Score": "5", "Tags": [ "rust", "tetris" ], "Title": "Tetris clone in Rust using specs" }
212477
<p>I'm a bit of a novice in terms of coding. I have to print to the console any tweets from a file that mentions a specific word like "Uber". This image below is what I have done so far. It prints how many times uber is mentioned in a line. But I need it to print the actual tweets themselves. </p> <pre><code> else if (choice == 4) { // 4th option on the menu to print tweets mentioning the word "Uber": string temp; ifstream infile; // Read in. infile.open("sampleTweets.csv"); // File name in folder. if (infile.good()) { while (!infile.eof()) { getline(infile,temp); if (temp.find("Uber") &lt;= temp.length()) { cout &lt;&lt; "Found Uber in the line" &lt;&lt; endl; } } } </code></pre> <p><a href="https://i.stack.imgur.com/zskLQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zskLQ.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T00:13:05.970", "Id": "411031", "Score": "1", "body": "Welcome to code-review. Unfortunately, your question is accumultaing close-votes, because (here on code-review) we only provide commentary on working code with a well-defined purpose and context; we can't help with implementing code to solve a particular problem. You might want to take a look at the [help center](https://codereview.stackexchange.com/help/on-topic) to get a better idea of how you can get the most out of the site." } ]
[ { "body": "<h2><a href=\"https://en.cppreference.com/w/cpp/string/basic_string/find\" rel=\"nofollow noreferrer\">std::string::find</a></h2>\n\n<p>In your code you have <code>temp.find(\"Uber\") &lt;= temp.length()</code>. <code>std::string::find</code> will return <code>std::string::npos</code> if the substring is not found.\nSo change that piece of code to</p>\n\n<pre><code>if(temp.find(\"Uber\") != std::string::npos)\n{\n // do stuff\n}\n</code></pre>\n\n<h2>Print line</h2>\n\n<p>To print the actual line, just put it into the <code>cout</code> statement.</p>\n\n<pre><code>cout &lt;&lt; \"Found Uber in the line \\\"\" &lt;&lt; temp &lt;&lt; \"\\\"\" &lt;&lt; endl;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T03:08:14.377", "Id": "411038", "Score": "0", "body": "To the ones who downvoted: can you also comment on what the problem with my solution is?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-05T15:14:26.560", "Id": "411800", "Score": "0", "body": "You answered an off-topic question." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T00:08:10.163", "Id": "212498", "ParentId": "212481", "Score": "-1" } } ]
{ "AcceptedAnswerId": "212498", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T19:33:34.590", "Id": "212481", "Score": "-3", "Tags": [ "c++" ], "Title": "Assessment help, application that interrogates tweets" }
212481
<p>I wrote this as an aid to count money that is in a cash box. are there any flaws in the code or any improvements I can make. </p> <pre><code>from decimal import Decimal def moneyfmt(value, places=2, curr='', sep=',', dp='.', pos='', neg='-', trailneg=''): """Convert Decimal to a money formatted string. places: required number of places after the decimal point curr: optional currency symbol before the sign (may be blank) sep: optional grouping separator (comma, period, space, or blank) dp: decimal point indicator (comma or period) only specify as blank when places is zero pos: optional sign for positive numbers: '+', space or blank neg: optional sign for negative numbers: '-', '(', space or blank trailneg:optional trailing minus indicator: '-', ')', space or blank https://docs.python.org/3/library/decimal.html#recipes """ q = Decimal(10) ** -places # 2 places --&gt; '0.01' sign, digits, exp = value.quantize(q).as_tuple() result = [] digits = list(map(str, digits)) build, next = result.append, digits.pop if sign: build(trailneg) for i in range(places): build(next() if digits else '0') if places: build(dp) if not digits: build('0') i = 0 while digits: build(next()) i += 1 if i == 3 and digits: i = 0 build(sep) build(curr) build(neg if sign else pos) return ''.join(reversed(result)) money = {'nickels' : Decimal(0), 'dimes' : Decimal(0), 'quarters': Decimal(0), 'ones': Decimal(0), 'twos': Decimal(0), 'fives': Decimal(0), 'tens' : Decimal(0), 'twenties' : Decimal(0), 'fifties': Decimal(0), 'one hundreds' : Decimal(0)} def display_values(): d = Decimal(money['nickels'] * Decimal(0.05)) print(money['nickels'], 'nickles = ', (moneyfmt(d, curr='$'))) d = Decimal((money['dimes'] * Decimal(0.10))) print(money['dimes'], 'dimes = ', (moneyfmt(d, curr='$'))) d = Decimal((money['quarters'] * Decimal(0.25))) print(money['quarters'], 'quarters = ', (moneyfmt(d, curr='$'))) d = Decimal((money['ones'] * Decimal(1))) print(money['ones'], 'ones = ', (moneyfmt(d, curr='$'))) d = Decimal((money['twos'] * Decimal(2))) print(money['twos'], 'two dollar coin(s)= ', (moneyfmt(d, curr='$'))) d = Decimal((money['fives'] * Decimal(5))) print(money['fives'], 'fives(s)= ', (moneyfmt(d, curr='$'))) d = Decimal((money['tens'] * Decimal(10))) print(money['tens'], 'ten(s)= ', (moneyfmt(d, curr='$'))) d = Decimal((money['twenties'] * Decimal(20))) print(money['twenties'], 'twenty dollar bill(s) = ', (moneyfmt(d, curr='$'))) d = Decimal((money['fifties'] * Decimal(50))) print(money['fifties'], 'fifty dollar bill(s) = ', (moneyfmt(d, curr='$'))) d = Decimal((money['one hundreds'] * Decimal(100))) print(money['one hundreds'], 'one hundred dollar bill(s) = ', (moneyfmt(d, curr='$')),'\n') cashbox_sum() def cashbox_sum(): nickels = money['nickels'] * Decimal(0.05) dimes = money['dimes'] * Decimal(0.10) quarters = money['quarters'] * Decimal(0.25) ones = money['ones'] * Decimal(1.00) twos = money['twos'] * Decimal(2.00) fives = money['fives'] * Decimal(5.00) tens = money['tens'] * Decimal(10.00) twenties = money['twenties'] * Decimal(20.00) fifties = money['fifties'] * Decimal(50.00) one_hundreds = money['one hundreds'] * Decimal(100.00) print('Cash box total: ', nickels.quantize(Decimal('0.00')) + dimes.quantize(Decimal('0.00')) + quarters.quantize(Decimal('0.00')) + ones.quantize(Decimal('0.00')) + twos.quantize(Decimal('0.00')) + fives.quantize(Decimal('0.00')) + tens.quantize(Decimal('0.00')) + twenties.quantize(Decimal('0.00')) + fifties.quantize(Decimal('0.00')) + one_hundreds.quantize(Decimal('0.00')),'\n') def assign_all_values(): input_nickles() input_dimes() input_quarters() input_ones() input_twos() input_fives() input_tens() input_twenties() input_fifties() input_one_hundreds() while True: entry = input("do you need to change a value. enter yes or no. ").lower() if entry == "yes": change_value() if entry == "no": input("press enter to exit") break else: print(entry, "is not a valid entry") def input_nickles(): while True: try: entry = int(input('how many nickels are in your cash box? ')) except ValueError: print("\nyou must enter a whole number. e.x. 1, 2, 3... do not enter letters or characters such as $\n") else: money['nickels'] = Decimal(entry) display_values() break def input_dimes(): while True: try: entry = int(input('how many dimes are in your cash box? ')) except ValueError: print("\nyou must enter a whole number. e.x. 1, 2, 3... do not enter letters or characters such as $\n") else: money['dimes'] = Decimal(entry) display_values() break def input_quarters(): while True: try: entry = int(input('how many quarters are in your cash box? ')) except ValueError: print("\nyou must enter a whole number. e.x. 1, 2, 3... do not enter letters or characters such as $\n") else: money['quarters'] = Decimal(entry) display_values() break def input_ones(): while True: try: entry = int(input('how many ones are in your cash box? ')) except ValueError: print("\nyou must enter a whole number. e.x. 1, 2, 3... do not enter letters or characters such as $\n") else: money['ones'] = Decimal(entry) display_values() break def input_twos(): while True: try: entry = int(input('how many two dollar coins are in your cash box? ')) except ValueError: print("\nyou must enter a whole number. e.x. 1, 2, 3... do not enter letters or characters such as $\n") else: money['twos'] = Decimal(entry) display_values() break def input_fives(): while True: try: entry = int(input('how many five dollar bills are in your cash box? ')) except ValueError: print("\nyou must enter a whole number. e.x. 1, 2, 3... do not enter letters or characters such as $\n") else: money['fives'] = Decimal(entry) display_values() break def input_tens(): while True: try: entry = int(input('how many ten dollar bills are in your cash box? ')) except ValueError: print("\nyou must enter a whole number. e.x. 1, 2, 3... do not enter letters or characters such as $\n") else: money['tens'] = Decimal(entry) display_values() break def input_twenties(): while True: try: entry = int(input('how many twenty dollar bills are in your cash box? ')) except ValueError: print("\nyou must enter a whole number. e.x. 1, 2, 3... do not enter letters or characters such as $\n") else: money['twenties'] = Decimal(entry) display_values() break def input_fifties(): while True: try: entry = int(input('how many fifty dollar bills are in your cash box? ')) except ValueError: print("\nyou must enter a whole number. e.x. 1, 2, 3... do not enter letters or characters such as $\n") else: money['fifties'] = Decimal(entry) display_values() break def input_one_hundreds(): while True: try: entry = int(input('how many one hundred dollar bills are in your cash box? ')) except ValueError: print("\nyou must enter a whole number. e.x. 1, 2, 3... do not enter letters or characters such as $\n") else: money['one hundreds'] = Decimal(entry) display_values() break def change_value(): while True: try: entry = int(input('\nwhat value would you like to change? please enter a corrosponding number\n\n1. Nickle\n2. Dime \n3. Quarter \n4. One \n5. Two \n6. Five \n7. Ten \n8. Twenty \n9. Fifty \n10. One Hundred\n')) except ValueError: print(str('that is not a valid option')) else: if entry == 1: input_nickles() if entry == 2: input_dimes() if entry == 3: input_quarters() if entry == 4: input_ones() if entry == 5: input_twos() if entry == 6: input_fives() if entry == 7: input_tens() if entry == 8: input_twenties() if entry == 9: input_fifties() if entry == 10: input_one_hundreds() entry = (input("would you like to change another value. enter yes or no")).lower() if entry == 'yes': print("yyy") pass elif entry == 'no': input('press enter to exit') exit() else: print(entry, 'is not a valid entry') assign_all_values() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T21:04:05.083", "Id": "411020", "Score": "0", "body": "Welcome to Code Review! Are you aware there's an awful lot of code repetition going on in your program?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T21:05:54.813", "Id": "411021", "Score": "0", "body": "yes, I was feeling like I could have made this less repetitive, but I wasn't exactly sure how." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T11:47:29.077", "Id": "411097", "Score": "0", "body": "Thank You. I am teaching myself how to program, Im often am unsure if something I've done is good or not. Python 3.x. I will change that." } ]
[ { "body": "<p>I think above the repetition, this is the most \"urgent\" thing to change :</p>\n\n<p><code>build, next = result.append, digits.pop</code> </p>\n\n<p>It is very counter-intuitive. Being explicit with <code>result.append</code> is much clearer and easy to understand that using <code>build</code>. I searched for a little while for a <code>build</code> and <code>next</code> function in your code without finding them, only to realize this hack.</p>\n\n<p>In the method <code>display_values</code>, there's a lot of repetition that could easily be avoided. It would make a lot of sense to have a dictionary that maps <code>Nickel</code> to the value <code>0.05</code>. This way, it would be easy to do :</p>\n\n<pre><code>def display_values():\n\n money_values = {'nickels' : 0.05, ...}\n\n for m, amount in money.items():\n d = Decimal(amount * Decimal(money_values[m]))\n print(amount, 'nickles = ', (moneyfmt(d, curr='$')))\n\n cashbox_sum()\n</code></pre>\n\n<p>Doing this would also simplify <code>cashbox_sum</code> :</p>\n\n<pre><code>def cashbox_sum():\n\n total = Decimal(0)\n for m, amount in money.items():\n total += (amount * money_values[m]).quantize(Decimal('0.00'))\n\n print('Cash box total: ', total)\n</code></pre>\n\n<p><em>I've never used the <code>Decimal</code> class, but maybe you can actually quantize only at the end?</em></p>\n\n<p>It is also possible to simplify your inputs : </p>\n\n<pre><code>def input_cashbox():\n\n for m in money.keys():\n while True:\n try:\n entry = int(input('how many ', m, ' are in your cash box? '))\n except ValueError:\n print(\"\\nyou must enter a whole number. e.x. 1, 2, 3... do not enter letters or characters such as $\\n\") \n else:\n money[m] = Decimal(entry)\n display_values()\n break\n</code></pre>\n\n<p>This would require an effort to refactor <code>change_value</code> but I think you should be able to figure it out with the rest of this review.</p>\n\n<p>I didn't test all of this, but I'm sure it would reduce the code duplication a lot.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T02:20:04.667", "Id": "411232", "Score": "1", "body": "Thank you, I have put that into my code. it has brought it from 249 lines to 122." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T21:17:33.777", "Id": "212488", "ParentId": "212484", "Score": "4" } } ]
{ "AcceptedAnswerId": "212488", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T20:37:48.630", "Id": "212484", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Cashbox count program" }
212484
<p><a href="https://leetcode.com/problems/merge-two-sorted-lists/" rel="nofollow noreferrer">https://leetcode.com/problems/merge-two-sorted-lists/</a></p> <p>Merge two sorted linked lists and return it as a new list. <br> The new list should be made by splicing together the nodes of the first two lists.</p> <p>Example:</p> <p>Input: 1->2->4, 1->3->4<br> Output: 1->1->2->3->4->4</p> <pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting; namespace SortingQuestions { [TestClass] public class Merge2SortedLists { [TestMethod] public void TwoListsMerge() { ListNode l1 = new ListNode(1); l1.next = new ListNode(2); l1.next.next = new ListNode(4); ListNode l2 = new ListNode(1); l2.next = new ListNode(3); l2.next.next = new ListNode(4); var res = MergeTwoLists(l1, l2); Assert.AreEqual(1, res.val); Assert.AreEqual(1, res.next.val); Assert.AreEqual(2, res.next.next.val); Assert.AreEqual(3, res.next.next.next.val); Assert.AreEqual(4, res.next.next.next.next.val); Assert.AreEqual(4, res.next.next.next.next.next.val); } [TestMethod] public void OneEmptyList() { ListNode l1 = new ListNode(1); l1.next = new ListNode(2); l1.next.next = new ListNode(4); ListNode l2 = null; var res = MergeTwoLists(l1, l2); Assert.AreEqual(1, res.val); Assert.AreEqual(2, res.next.val); Assert.AreEqual(4, res.next.next.val); } public ListNode MergeTwoLists(ListNode l1, ListNode l2) { ListNode result = new ListNode(0); if (l1 == null &amp;&amp; l2 == null) { return null; } ListNode currRes = result; while (l1 != null &amp;&amp; l2 != null) { if (l1.val &lt; l2.val) { currRes.next = l1; l1 = l1.next; currRes = currRes.next; } else { currRes.next = l2; l2 = l2.next; currRes = currRes.next; } } if (l1 != null) { currRes.next = l1; //concat all the rest } else { currRes.next = l2; } return result.next; // we don't pass the first value } } public class ListNode { public int val; public ListNode next; public ListNode(int x) { val = x; } } } </code></pre> <p>if you could please review this code from testing point of view, in an interview. what edge cases would you expected to be tested here. please remember this is about 30 minutes. also please comment on style.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:13:28.057", "Id": "411148", "Score": "0", "body": "Are these questions you ask really interview-questions or are you doing them just for practice? What feedback did you get in your interview?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T20:13:05.040", "Id": "411205", "Score": "0", "body": "It is my friend's interview. My code is ok. He was asked to explain what he wrote just a few test cases. And told them it was a time issues. The interview we asked if knows what are unit tests and smoke tests. And why he didn't check all the edge cases. I told him that this code is great and the interviewer was wierd" } ]
[ { "body": "<p>Style wise, the assignment <code>currRes = currRes.next;</code> happens no matter what, so lift it out of <code>if-else</code> clause:</p>\n\n<pre><code> if (l1.val &lt; l2.val)\n {\n currRes.next = l1;\n l1 = l1.next;\n }\n else\n {\n currRes.next = l2;\n l2 = l2.next;\n } \n currRes = currRes.next;\n</code></pre>\n\n<p>Correctness wise, the condition <code>if (l1.val &lt; l2.val)</code> loses the stability: if the elements compare equal, the one from <code>l2</code> is merged first. Consider <code>if (l1.val &lt;= l2.val)</code> (or even <code>if (l2.val &lt; l2.val)</code>) instead. It is not required by the problem statement, and it doesn't matter for <code>int</code>s. In real life however the stability is of utmost importance, and as an interviewer I'd definitely mark it.</p>\n\n<p>On the bright side, a dummy head for the merged list is a right way to go. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T22:43:09.457", "Id": "212493", "ParentId": "212485", "Score": "4" } }, { "body": "<p>This condition is unnecessary, and can be safely deleted:</p>\n\n<blockquote>\n<pre><code>if (l1 == null &amp;&amp; l2 == null)\n{\n return null;\n}\n</code></pre>\n</blockquote>\n\n<p>The problem description says, with <strong><em>emphasis</em></strong> mine:</p>\n\n<blockquote>\n <p>Merge two sorted linked lists and return it as a <strong><em>new</em></strong> list.</p>\n</blockquote>\n\n<p>The solution doesn't really do that, it reuses and even modifies the nodes in the input lists. The solution is accepted by the judge anyway, so I think it's a bug in the description. Just for the record.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T11:27:48.693", "Id": "213181", "ParentId": "212485", "Score": "0" } } ]
{ "AcceptedAnswerId": "212493", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T21:04:41.953", "Id": "212485", "Score": "0", "Tags": [ "c#", "programming-challenge", "linked-list", "interview-questions" ], "Title": "Leetcode: Merging 2 sorted lists" }
212485
<p>I have a simple brute-force search function:</p> <pre><code>function run_query(search_data::Vector{Float64}, query::Vector{Float64}, search_f::Function)::Tuple{Float64, Int} current_best = Inf loc = -1 q_len = length(query) for d_i in 1:(length(data) - q_len) dist = search_f(data[d_i:d_i+q_len-1], query) if dist &lt; current_best current_best = dist loc = d_i end end return current_best, loc end </code></pre> <p>I have an alternative version of the function which also returns the maximum distance found while searching to data:</p> <pre><code>function run_query_max(search_data::Vector{Float64}, query::Vector{Float64}, search_f::Function)::Tuple{Float64, Int, Float64} current_best = Inf loc = -1 q_len = length(query) max_dist = 0. for d_i in 1:(length(data) - q_len) dist = search_f(data[d_i:d_i+q_len-1], query) if dist &gt; max_dist max_dist = dist end if dist &lt; current_best current_best = dist loc = d_i end end return current_best, loc, max_dist end </code></pre> <p>This can be tested as follows:</p> <pre><code>function simple_dist(data::Vector{Float64}, query::Vector{Float64})::Float64 return sum((data .- query) .^ 2) end data = [0., 0., 1., 2., 3., 1.1, 3., 3., 1., 0., 0., 1., 0., 0., 1., 4.5, 2., 1., 0., 0.] query = [1., 2., 3., 1.] val, idx = run_query(data, query, simple_dist) @assert (idx == 3) @assert isapprox(val, 0.01, atol=0.001) val, idx, max_dist = run_query_max(data, query, simple_dist) @assert (idx == 3) @assert isapprox(val, 0.01, atol=0.001) @assert isapprox(max_dist, 21.25, atol=0.001) </code></pre> <p>This pattern of:</p> <ol> <li>Basic search function</li> <li>Add keeping track of maximum distance in search function</li> </ol> <p>Occurs in multiple places in my code. What is a reasonable way to refactor it out?</p>
[]
[ { "body": "<p>I think this depends a lot on your motivation for separating these into two methods.</p>\n\n<p>One simple option I would consider first is to just have 1 version of each of these functions to avoid the duplication in the first place. \nThe caller can just ignore the <code>max_dist</code> value if they don't need it.</p>\n\n<p>If performance is an issue and <code>max_dist</code>calculation could be a bottleneck, you could add a Boolean argument to the single function to indicate if <code>max_dist</code> should be calculated or not.</p>\n\n<p>If the logic for <code>max_dist</code> is complex enough to hurt the readability of the basic search, I think you may be better off going with the duplication instead of doing something more complex. It could be done, but not in a way I would consider reasonable in most cases.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T14:54:26.460", "Id": "411137", "Score": "0", "body": "Yeah, I'm also considering I might need to do benchmarking to guide whether I should worry about this or not." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T14:43:50.613", "Id": "212550", "ParentId": "212486", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T21:06:14.037", "Id": "212486", "Score": "2", "Tags": [ "julia" ], "Title": "Add optional distance range to function" }
212486
<p>The following code clears 11 columns that contain lists that are used for data validation on another worksheet. This list is constantly changing due to records being added/removed from the source data. Basically I'm checking every value in a column, and if it meets all of my criteria I'm adding it to my data validation column (after making sure it doesn't already exist there).</p> <p>Once I've populated my 11 columns, I sort each one alphabetically. <strong>This is the portion of my code that I don't like</strong>. While it doesn't explicitly <code>select</code> anything, I can see on my worksheet the last column that was sorted because it is selected.</p> <p>What I'm wondering is if there's a better way to dynamically generate this list alphabetically without having to use <code>.Sort</code> - possibly populating an array and then sorting it alphabetically? I've never sorted an array in VBA, so I'm not sure <strong>1. If it's even more efficient</strong> and <strong>2. What is the best method to sort an array, if that's the approach I should take here?</strong></p> <p>Code:</p> <pre><code>Option Explicit Sub PopulateAllDataValidationLists() Dim sht As Worksheet, sht2 As Worksheet Dim i As Long, listcol As Long Set sht = Worksheets("Sheet 1") Set sht2 = Worksheets("Data Validation") Application.ScreenUpdating = False sht2.Range("A2:K500").ClearContents For i = 1 To 11 listcol = sht.Rows("1:1").Find(What:=sht2.Cells(1, i).Value, LookAt:=xlWhole).Column For j = 2 To sht.Cells(sht.Rows.Count, listcol).End(xlUp).Row If IsError(Application.Match(sht.Cells(j, listcol).Value, sht2.Range(ColumnLetter(i) &amp; ":" &amp; ColumnLetter(i)), 0)) And _ sht.Cells(j, listcol).Value &lt;&gt; "" And _ sht.Cells(j, listcol).Value &lt;&gt; "UNK" And _ sht.Cells(j, listcol).Value &lt;&gt; "xxx" And _ sht.Cells(j, listcol).Value &lt;&gt; "yyy" And _ sht.Cells(j, listcol).Value &lt;&gt; "zzz" And _ sht.Cells(j, listcol).Value &lt;&gt; "yxz" And _ sht.Cells(j, listcol).Value &lt;&gt; "zyx" And _ Len(sht.Cells(j, listcol).Value) &lt;= 3 Then sht2.Cells(sht2.Cells(sht2.Rows.Count, i).End(xlUp).Row + 1, i).Value = sht.Cells(j, listcol).Value End If Next j Next i 'Sort all alphabetically For i = 1 To 11 Worksheets("Data Validation").Sort.SortFields.Clear Worksheets("Data Validation").Sort.SortFields.Add Key:=Range(ColumnLetter(i) &amp; "2"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal With Worksheets("Data Validation").Sort .SetRange Range(ColumnLetter(i) &amp; "2:" &amp; ColumnLetter(i) &amp; sht2.Cells(sht2.Rows.Count, i).End(xlUp).Row) .Header = xlNo .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With Next i Application.ScreenUpdating = True End Sub Function ColumnLetter(colnum As Long) As String ColumnLetter = Split(Cells(1, colnum).Address, "$")(1) End Function </code></pre> <p>An example of data in a column:</p> <p><a href="https://i.stack.imgur.com/nGbxX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nGbxX.png" alt="img1"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T01:13:05.133", "Id": "411033", "Score": "0", "body": "Can you provide any sample data from the sheets?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T09:09:55.967", "Id": "411072", "Score": "0", "body": "Funnily enough, I've been working on a data structure that achieves precisely this. Annoyingly it's still a work in progress, but the basic concept is that I encapsulate an `ArrayList` and raise events whenever the order or content change. You might be able to make use of the [working branch](https://github.com/Greedquest/VBA-Toolbox/tree/synchro-list-v3?files=1) though. Message me on chat if you'd like some more details, the whole thing will hopefully go up on CR fairly soon" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:18:29.727", "Id": "411149", "Score": "0", "body": "@PeterT I added a small example of what data in a column would look like." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:28:14.533", "Id": "411169", "Score": "0", "body": "@Greedo Interesting - I'll take a look at this. Thanks." } ]
[ { "body": "<p>I would refactor your code and add <code>Worksheets(\"Data Validation\").Range(\"A1\").Select</code> to the end to clear the selection. </p>\n\n<h2>Refactored Code</h2>\n\n<p>Changes:</p>\n\n<ul>\n<li><code>ColumnLetter()</code>: Removed</li>\n<li>sht2: Replaced using a <code>With</code> block.</li>\n<li><code>For j</code>: Changed to <code>For item</code>. <code>item.Value</code> is much easier to distinguish than <code>sht.Cells(j, listcol).Value</code></li>\n<li><code>.Range(\"A1\").Select</code>: Added to clear the dreaded selected column</li>\n<li>Cell reference fully qualified for the Sort ranges (I am surprised that the code would run without <code>Worksheets(\"Data Validation\")</code> being the ActiveSheet.</li>\n<li><code>sht2.Range(\"A2:K500\").ClearContents</code>: Replaced made dynamic using <code>sht2.Range(\"A1:K1\").CurrentRegion.Offset(1).ClearContents</code></li>\n</ul>\n\n<hr>\n\n<pre><code>Sub PopulateAllDataValidationLists()\n Dim sht As Worksheet\n Dim i As Long, listcol As Long\n With Worksheets(\"Data Validation\")\n Application.ScreenUpdating = False\n\n .Range(\"A1:K1\").CurrentRegion.Offset(1).ClearContents\n Dim columnName As String\n Dim InvalidValues As Variant\n\n InvalidValues = Array(\"UNK\", \"xxx\", \"yyy\", \"zzz\", \"yxz\", \"zyx\")\n\n Dim rColumn As Range, item As Range\n For i = 1 To 11\n columnName = .Cells(1, i).Value\n With Worksheets(\"Sheet 1\")\n listcol = .Rows(\"1:1\").Find(What:=columnName, LookAt:=xlWhole).Column\n Set rColumn = Range(.Cells(1, listcol), .Cells(.Rows.Count, listcol).End(xlUp))\n End With\n\n For Each item In rColumn\n If item.Value &lt;&gt; \"\" Then\n If IsError(Application.Match(item.Value, .Columns(i), 0)) And _\n IsError(Application.Match(item.Value, InvalidValues, 0)) And _\n Len(item.Value) &lt;= 3 Then\n .Cells(.Cells(.Rows.Count, i).End(xlUp).Row + 1, i).Value = item\n End If\n End If\n Next\n\n .Sort.SortFields.Clear\n .Sort.SortFields.Add Key:=.Cells(2, i), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal\n Dim target As Range\n Set target = Range(.Cells(2, i), .Cells(.Rows.Count, i).End(xlUp))\n\n With .Sort\n .SetRange target\n .Header = xlNo\n .MatchCase = False\n .Orientation = xlTopToBottom\n .SortMethod = xlPinYin\n .Apply\n End With\n Next i\n .Range(\"A1\").Select\n End With\n\n Application.ScreenUpdating = True\n\nEnd Sub\n</code></pre>\n\n<h2>Other Method</h2>\n\n<p>There are many ways that you can sort the data: </p>\n\n<ul>\n<li>System.Collection.ArrayList : <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist?view=netframework-4.7.2\" rel=\"nofollow noreferrer\">ArrayList Class (System.Collections) | Microsoft Docs</a>, <a href=\"http://www.snb-vba.eu/VBA_Arraylist_en.html\" rel=\"nofollow noreferrer\">VBA for smarties: ArrayList</a></li>\n<li>System.Collections.SortedList: <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist?view=netframework-4.7.2\" rel=\"nofollow noreferrer\">SortedList Class (System.Collections) | Microsoft Docs</a>, <a href=\"http://www.snb-vba.eu/VBA_Sortedlist_en.html\" rel=\"nofollow noreferrer\">VBA voor smarties: SortedList</a>, <a href=\"https://www.robvanderwoude.com/vbstech_data_sortedlist.php\" rel=\"nofollow noreferrer\">VBScript Scripting Techniques: SortedLists - Rob van der Woude</a></li>\n<li>Bubble Sort: <a href=\"https://bettersolutions.com/vba/arrays/sorting-bubble-sort.htm\" rel=\"nofollow noreferrer\">VBA Arrays - Bubble Sort - BetterSolutions.com</a></li>\n<li>Quick Sort: <a href=\"https://bettersolutions.com/vba/arrays/sorting-quick-sort.htm\" rel=\"nofollow noreferrer\">VBA Arrays - Quick Sort - BetterSolutions.com</a></li>\n</ul>\n\n<p>Here is an example of how you can use an <code>ADODB.Recordset</code> to create a table in memory to sort and potentially filter the data.</p>\n\n<h2>RSSort: Class</h2>\n\n<pre><code>Option Explicit\nPublic FieldName As String\nPrivate Const adVarChar = 200\nPrivate Const adOpenKeyset = 1\nPrivate Const adUseClient = 3\nPrivate Const adLockPessimistic = 2\nPrivate rs As Object\n\nPrivate Sub Class_Initialize()\n FieldName = \"Values\"\n Set rs = CreateObject(\"ADODB.Recordset\")\n\n With rs\n .Fields.Append FieldName, adVarChar, 255\n .CursorType = adOpenKeyset\n .CursorLocation = adUseClient\n .LockType = adLockPessimistic\n .Open\n End With\nEnd Sub\n\nPublic Sub AddNew(ByVal item As Variant)\n rs.AddNew FieldName, item\nEnd Sub\n\nPublic Property Get Filter() As String\n Filter = rs.Filter\nEnd Property\n\nPublic Property Let Filter(ByVal sFilter As String)\n rs.Filter = sFilter\nEnd Property\n\nPublic Sub Sort(Optional SortAscending As Boolean = True)\n rs.Sort = FieldName &amp; IIf(SortAscending, \" ASC\", \" DESC\")\nEnd Sub\n\nPublic Function ToArray() As Variant\n Dim data As Variant, results As Variant\n If rs.RecordCount = 0 Then\n ReDim results(1 To 1, 1 To 1)\n ToArray = results\n Exit Function\n End If\n rs.MoveFirst\n data = rs.GetRows(rs.RecordCount)\n ReDim results(1 To UBound(data, 2) + 1, 1 To 1)\n\n Dim r As Long\n\n For r = 1 To UBound(data, 2)\n results(r + 1, 1) = data(0, r)\n Next\n\n ToArray = results\nEnd Function\n</code></pre>\n\n<h2>Demo Code</h2>\n\n<pre><code>Sub RSSorterPopulateAllDataValidationLists()\n Application.ScreenUpdating = False\n\n Dim data As Variant\n Dim c As Long\n\n With Worksheets(\"Data Validation\")\n .Range(\"A1:K1\").CurrentRegion.Offset(1).ClearContents\n For c = 1 To 11\n data = getValidationValues(.Columns(c), \"\", \"UNK\", \"xxx\", \"yyy\", \"zzz\", \"yxz\", \"zyx\")\n .Cells(2, c).Resize(UBound(data)).Value = data\n Next\n End With\nEnd Sub\n\nFunction getValidationValues(MatchColumn As Range, ParamArray InvalidValues() As Variant) As Variant()\n Dim sorter As New RSSorter\n Dim col As Range\n Dim ColumnHeader As String\n ColumnHeader = MatchColumn.Cells(1, 1).Value\n Dim vExcluded As Variant\n vExcluded = InvalidValues\n\n With Worksheets(\"Sheet 1\")\n Dim item As Range\n Set col = .Rows(\"1:1\").Find(What:=ColumnHeader, LookAt:=xlWhole)\n If Not col Is Nothing Then\n For Each item In Range(col.Cells(2, 1), .Cells(.Rows.Count, col.Column).End(xlUp))\n If item.Value &lt;&gt; \"\" Then\n If IsError(Application.Match(item.Value, MatchColumn, 0)) And _\n IsError(Application.Match(item.Value, vExcluded, 0)) And _\n Len(item.Value) &lt;= 3 Then\n sorter.AddNew item\n End If\n End If\n Next\n End If\n End With\n sorter.Sort\n getValidationValues = sorter.ToArray\nEnd Function\n</code></pre>\n\n<h2>Edit</h2>\n\n<ul>\n<li><code>sht</code>replaced with <code>With Worksheets(\"Sheet 1\")</code></li>\n<li>Constants (adOpenKeyset, adUseClient, adLockPessimistic) added to completely convert from early binding to late binding.</li>\n<li>The ADODB library <code>\"Microsoft ActiveX Data Objects x.x Library\"</code> removed from original workbook</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:32:31.237", "Id": "411171", "Score": "0", "body": "This is great! Is there a library that I need to use for RSSorter? Getting user-defined type not defined." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:35:16.267", "Id": "411173", "Score": "0", "body": "Although I will say that the refactored code works nicely (except it was missing a `Set` line for `sht` which I easily added). Additionally, I had to get rid of `Range(\"A1\").Select` since that sheet is hidden and not active when sorting - but it looks to run faster!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T18:45:41.230", "Id": "411192", "Score": "0", "body": "@dwirony Thanks for accepting my answer. I resolved the issues(see edits). Late night" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T19:14:32.783", "Id": "411197", "Score": "0", "body": "Haha no worries - I was tired when this original script, I should've created an array and checked against it instead of all those `And`s... sloppy by me." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T07:51:22.223", "Id": "212520", "ParentId": "212489", "Score": "1" } } ]
{ "AcceptedAnswerId": "212520", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T21:39:56.120", "Id": "212489", "Score": "1", "Tags": [ "vba", "excel" ], "Title": "Generating a data validation list and sorting it alphabetically" }
212489
<p>Rarely is the <em>exact</em> value of a <code>double</code> needed to be printed and only its leading significant digits, after rounding, are needed.</p> <p>It is a curiosity to see the exact value of a <code>double</code> as all finite <code>double</code> are exact. (Even if the math used on them generates mathematical approximation.)</p> <p>An <em>exact</em> decimal output can be used to evaluate rounded outputs. <a href="https://codereview.stackexchange.com/q/212415/29485">Example</a></p> <hr /> <p>Below I seek a general review of <code>print_double()</code> and its support functions with emphasis on portability, assuming <code>FLT_RADIX == 2</code>, though not necessarily <a href="https://en.wikipedia.org/wiki/Double-precision_floating-point_format" rel="nofollow noreferrer">binary64</a>.</p> <p>Efficiency is a lesser concern.</p> <pre><code>/* * print_double.c * chux 2019 */ #include &lt;assert.h&gt; #include &lt;float.h&gt; #include &lt;math.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; _Static_assert(FLT_RADIX == 2, &quot;TBD code for non-binary FP&quot;); // Max whole number decimal digits in a `double`. #define AD_I (DBL_MAX_10_EXP + 1) // Max fractional decimal digits in a `double`. #define AD_F (DBL_MANT_DIG - DBL_MIN_EXP) /* * Managed array of decimal digits * Code first uses the middle of the array and works its way out to the ends * Most significant digits in highest indexed elements. */ typedef struct { unsigned char digit[AD_F + AD_I]; size_t flength; size_t ilength; } ad; /* * Initialize 2 digits: 0.0 */ static void ad_zero(ad *a) { a-&gt;ilength = 1; a-&gt;flength = 1; a-&gt;digit[AD_F] = 0; a-&gt;digit[AD_F-1] = 0; } /* * a = a*FLT_RADIX + carry */ static int ad_mul(ad *a, unsigned carry) { size_t msd = AD_F + a-&gt;ilength; size_t lsd = AD_F; for (size_t i = lsd; i &lt; msd; i++) { carry += (unsigned char) (a-&gt;digit[i] * FLT_RADIX); a-&gt;digit[i] = (unsigned char) (carry % 10); carry /= 10; } if (carry) { //printf(&quot;xx %zu\n&quot;, a-&gt;ilength); a-&gt;digit[AD_F + a-&gt;ilength++] = (unsigned char) carry; assert(carry / 10 == 0); } return 0; } /* * Divide by FLT_RADIX, a /= FLT_RADIX */ static void ad_div(ad *a) { size_t msd = AD_F + a-&gt;ilength; size_t lsd = AD_F - a-&gt;flength; unsigned carry = 0; for (size_t i = msd; i &gt; lsd;) { i--; carry = carry * 10u + a-&gt;digit[i]; a-&gt;digit[i] = (unsigned char) (carry / FLT_RADIX); carry %= FLT_RADIX; } if (a-&gt;ilength &gt; 1 &amp;&amp; a-&gt;digit[msd - 1] == 0) { a-&gt;ilength--; } if (carry) { carry = carry * 10u; a-&gt;flength++; a-&gt;digit[AD_F - a-&gt;flength] = (unsigned char) (carry / FLT_RADIX); carry %= FLT_RADIX; assert(carry == 0); } } /* * Print ad */ static void ad_print(const ad *a) { size_t msd = AD_F + a-&gt;ilength; size_t lsd = AD_F - a-&gt;flength; for (size_t i = msd; i &gt; lsd;) { printf(&quot;%d&quot;, a-&gt;digit[--i]); if (i == AD_F) { putchar('.'); } } } /* * Print the exact value of double */ void print_double(double d) { if (!isfinite(d)) { printf(&quot;%f&quot;, d); return; } if (signbit(d)) { d = -d; putchar('-'); } // Array to hold all the digits. ad a; ad_zero(&amp;a); int expo; d = frexp(d, &amp;expo); while (d &gt; 0) { expo--; double ipart; d = modf(d, &amp;ipart) * FLT_RADIX; ad_mul(&amp;a, (unsigned char) ipart); } expo++; while (expo &gt; 0) { expo--; ad_mul(&amp;a, 0); } if (expo &lt; 0) { while (expo &lt; 0) { expo++; ad_div(&amp;a); } } ad_print(&amp;a); } </code></pre> <p>Sample usage</p> <pre><code>#include &lt;float.h&gt; #include &lt;stdio.h&gt; // Usually I'd put this in a .h file. void print_double(double d); void print_double_wrap(double d) { // Print via printf() printf(&quot;% -*.*e '&quot;, DBL_DECIMAL_DIG + 8, DBL_DECIMAL_DIG - 1, d); print_double(d); puts(&quot;'&quot;); } int main(void) { print_double_wrap(0.0 / 0.0); print_double_wrap(1.0 / 0.0); print_double_wrap(-1.0 / 0.0); print_double_wrap(0); print_double_wrap(-0.0); print_double_wrap(1); print_double_wrap(123); print_double_wrap(1234); print_double_wrap(1e10); print_double_wrap(-1e20); print_double_wrap(1e30); print_double_wrap(1e300); print_double_wrap(123.5); print_double_wrap(0.01); print_double_wrap(DBL_MAX); print_double_wrap(DBL_MIN); print_double_wrap(-DBL_TRUE_MIN); } </code></pre> <p>Output</p> <pre><code>-nan '-nan' inf 'inf' -inf '-inf' 0.0000000000000000e+00 '0.0' -0.0000000000000000e+00 '-0.0' 1.0000000000000000e+00 '1.0' 1.2300000000000000e+02 '123.0' 1.2340000000000000e+03 '1234.0' 1.0000000000000000e+10 '10000000000.0' -1.0000000000000000e+20 '-100000000000000000000.0' 1.0000000000000000e+30 '1000000000000000019884624838656.0' 1.0000000000000001e+300 '1000000000000000052504760255204420248704468581108159154915854115511802457988908195786371375080447864043704443832883878176942523235360430575644792184786706982848387200926575803737830233794788090059368953234970799945081119038967640880074652742780142494579258788820056842838115669472196386865459400540160.0' 1.2350000000000000e+02 '123.5' 1.0000000000000000e-02 '0.01000000000000000020816681711721685132943093776702880859375' 1.7976931348623157e+308 '179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0' 2.2250738585072014e-308 '0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002225073858507201383090232717332404064219215980462331830553327416887204434813918195854283159012511020564067339731035811005152434161553460108856012385377718821130777993532002330479610147442583636071921565046942503734208375250806650616658158948720491179968591639648500635908770118304874799780887753749949451580451605050915399856582470818645113537935804992115981085766051992433352114352390148795699609591288891602992641511063466313393663477586513029371762047325631781485664350872122828637642044846811407613911477062801689853244110024161447421618567166150540154285084716752901903161322778896729707373123334086988983175067838846926092773977972858659654941091369095406136467568702398678315290680984617210924625396728515625' -4.9406564584124654e-324 '-0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004940656458412465441765687928682213723650598026143247644255856825006755072702087518652998363616359923797965646954457177309266567103559397963987747960107818781263007131903114045278458171678489821036887186360569987307230500063874091535649843873124733972731696151400317153853980741262385655911710266585566867681870395603106249319452715914924553293054565444011274801297099995419319894090804165633245247571478690147267801593552386115501348035264934720193790268107107491703332226844753335720832431936092382893458368060106011506169809753078342277318329247904982524730776375927247874656084778203734469699533647017972677717585125660551199131504891101451037862738167250955837389733598993664809941164205702637090279242767544565229087538682506419718265533447265625' </code></pre> <p>Edit: Added output for <code>FLT_MAX, FLT_MIN, -FLT_TRUE_MIN</code> for reference.</p> <pre><code> 3.4028234663852886e+38 '340282346638528859811704183484516925440.0' 1.1754943508222875e-38 '0.000000000000000000000000000000000000011754943508222875079687365372222456778186655567720875215087517062784172594547271728515625' -1.4012984643248171e-45 '-0.00000000000000000000000000000000000000000000140129846432481707092372958328991613128026194187651577175706828388979108268586060148663818836212158203125' </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T07:26:32.907", "Id": "526608", "Score": "1", "body": "One would imagine that `FLT_RADIX == 10` should be easy to support, too..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T13:20:24.453", "Id": "526624", "Score": "0", "body": "@TobySpeight True, but hard to test. IIRC, the latest platform with `FLT_RADIX == 10` is over 15 years ago. C23 may introduce a new set of FP: decimal types, distinct from `float, double`, etc." } ]
[ { "body": "<p>An interesting curiosity, as you say. Because 10 is an exact multiple of 2, all binary fractions have an exact, non-repeating decimal representation (but not <em>vice versa</em>). That means we're guaranteed to terminate.</p>\n\n<p>The code compiles cleanly with an aggressive set of warnings enabled, and Valgrind is completely happy with the test program. But I expect you already know that.</p>\n\n<hr>\n\n<p>There's very little I would change, but I did notice a redundancy here:</p>\n\n<blockquote>\n<pre><code> if (expo &lt; 0) {\n while (expo &lt; 0) {\n expo++;\n ad_div(&amp;a);\n }\n }\n</code></pre>\n</blockquote>\n\n<p>The outer <code>if</code> is pointless (and a good compiler will ignore it), so it's just useless clutter.</p>\n\n<hr>\n\n<p>On the style side, I'd move the mutation of <code>i</code> from the body of these <code>for</code> loops into the loop-control part (inside the <code>( )</code>), so that the control variable is constant within the body of each iteration:</p>\n\n<blockquote>\n<pre><code> for (size_t i = msd; i &gt; lsd;) {\n i--;\n //...\n }\n</code></pre>\n</blockquote>\n\n\n\n<blockquote>\n<pre><code> for (size_t i = msd; i &gt; lsd;) {\n printf(\"%d\", a-&gt;digit[--i]);\n //...\n }\n</code></pre>\n</blockquote>\n\n<p>to become, respectively:</p>\n\n<pre><code> for (size_t i = msd; i-- &gt; lsd;) {\n //...\n }\n</code></pre>\n\n\n\n<pre><code> for (size_t i = msd; i-- &gt; lsd;) {\n printf(\"%d\", a-&gt;digit[i]);\n //...\n }\n</code></pre>\n\n<p>That makes no difference to the functionality, but is less surprising and makes it easier to reason about the code. (If you want to be cute, you can write those operators together without a space, aka the <a href=\"//stackoverflow.com/q/1642028\">infamous \"goes to\" operator</a>, <code>--&gt;</code>.)</p>\n\n<hr>\n\n<p>One line that might need more comments is this one:</p>\n\n<blockquote>\n<pre><code>// Max fractional decimal digits in a `double`.\n#define AD_F (DBL_MANT_DIG - DBL_MIN_EXP)\n</code></pre>\n</blockquote>\n\n<p>As we all know, <code>DBL_MANT_DIG</code> and <code>DBL_MIN_EXP</code> are defined in terms of <code>FLT_RADIX</code>, so it looks like an error to use these to infer the number of decimal digits required. A small amount of mathematical reasoning shows that each added bit requires one more decimal digit for the representation; I recommend that you summarise that in the comment to show that it's not a mistake.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T13:57:31.350", "Id": "411403", "Score": "0", "body": "Yes `if (expo < 0) {\n while (expo < 0) {` simplification good idea. Code came from former code that had a `if (expo < 0) { putchar('.'); /* or other do something interesting here */\n while (expo < 0) {`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T14:04:53.133", "Id": "411405", "Score": "0", "body": "Second style idea: Solitary `i--` comes from a noted tendency to reduce use of post-fix notation in line (as in suggested `i-- > lsd`). It seems the newer crop of coders tend to have trouble with the latter. But I did miss the fine _goto operator_ opportunity. Could have coded it that way just to encourage feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T14:06:42.037", "Id": "411406", "Score": "0", "body": "Last bit about commenting `#define AD_F` is spot on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T14:09:15.410", "Id": "411407", "Score": "0", "body": "As I said, it's a style/opinion point about `i--` in the body - my preference is not to modify within the body unless it's natural for the step to be part-way through (and then consider commenting it). But I'm open to other opinions on that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T14:15:28.077", "Id": "411408", "Score": "0", "body": "The other common reason for `for (i = msd; i > lsd;) {\n i--;` vs. `for (i = msd; i-- > lsd;) {` is when `i` defined and used outside the loop and the decrement must not be taken on loop exit." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T13:49:44.883", "Id": "212690", "ParentId": "212490", "Score": "4" } } ]
{ "AcceptedAnswerId": "212690", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T21:42:30.577", "Id": "212490", "Score": "11", "Tags": [ "c", "floating-point", "c11" ], "Title": "Function to print a double - exactly" }
212490
<p>I was given this problem during an interview. And I solved it using Python. Would like to get feedback to see how I can improve my interview response. </p> <blockquote> <p><strong>Busiest Time in The Mall</strong></p> <p>The Westfield Mall management is trying to figure out what the busiest moment at the mall was last year. You’re given data extracted from the mall’s door detectors. Each data point is represented as an integer array whose size is 3. The values at indices 0, 1 and 2 are the timestamp, the count of visitors, and whether the visitors entered or exited the mall (0 for exit and 1 for entrance), respectively. Here’s an example of a data point: [ 1440084737, 4, 0 ].</p> <p>Note that time is given in a Unix format called Epoch, which is a nonnegative integer holding the number of seconds that have elapsed since 00:00:00 UTC, Thursday, 1 January 1970.</p> <p>Given an array, data, of data points, write a function findBusiestPeriod that returns the time at which the mall reached its busiest moment last year. The return value is the timestamp, e.g. 1480640292. Note that if there is more than one period with the same visitor peak, return the earliest one.</p> <p>Assume that the array data is sorted in an ascending order by the timestamp.</p> </blockquote> <pre><code>""" input: data = [ [1487799425, 14, 1], [1487799425, 4, 0], [1487799425, 2, 0], [1487800378, 10, 1], [1487801478, 18, 0], [1487801478, 18, 1], [1487901013, 1, 0], [1487901211, 7, 1], [1487901211, 7, 0] ] output: 1487800378 # since the increase in the number of people # in the mall is the """ def find_busiest_period(data): people = 0 max_time = 0 max_people = 0 for i in range(len(data)): if data[i][2] == 1: people += data[i][1] else: people -= data[i][1] if (i &lt; len(data)-1 and data[i][0] == data[i+1][0]): continue if people &gt; max_people: max_people = people max_time = data[i][0] return max_time data = [ [1487799425, 14, 1], [1487799425, 4, 0], [1487799425, 2, 0], [1487800378, 10, 1], [1487801478, 18, 0], [1487801478, 18, 1], [1487901013, 1, 0], [1487901211, 7, 1], [1487901211, 7, 0] ] test = find_busiest_period(data) print(test) </code></pre>
[]
[ { "body": "<h1>Algorithm</h1>\n<p>I don't understand the purpose of comparing the timestamp of the next datum here:</p>\n<blockquote>\n<pre><code>if (i &lt; len(data)-1 and data[i][0] == data[i+1][0]):\n continue\n</code></pre>\n</blockquote>\n<p>The two events happened during the same second, but it's reasonable to assume that they are ordered, and therefore we should consider the total within that single second, unless the problem statement says otherwise.</p>\n<p>Without that constraint, we have no need for the index <code>i</code>, and can consider just the members of the input data; we can give the elements meaningful names:</p>\n<pre><code> for time,quantity,direction in data:\n</code></pre>\n<p>Now, we know we won't find a new maximum when people are exiting (assuming we're not given negative numbers of people), so we can move the test into the <code>+=</code> branch:</p>\n<pre><code> if direction == 1:\n # Some people entered\n people += quantity\n # Have we reached a new maximum?\n if people &gt; max_people:\n max_time, max_people = time, people\n elif direction == 0:\n # Some people left\n people -= quantity\n else:\n raise ValueError(direction)\n</code></pre>\n<h1>General review</h1>\n<ul>\n<li><p>PEP8 recommends four spaces per indent level.</p>\n</li>\n<li><p>This doc-comment is both incomplete and incorrect:</p>\n<blockquote>\n<pre><code>&quot;&quot;&quot;\noutput: 1487800378 # since the increase in the number of people\n # in the mall is the\n&quot;&quot;&quot;\n</code></pre>\n</blockquote>\n</li>\n<li><p>The doc-comment is in the wrong place (it should be just within the function body).</p>\n</li>\n<li><p>We should use a <code>main</code> guard.</p>\n</li>\n<li><p>Consider using <code>doctest</code> to provide more test cases.</p>\n</li>\n</ul>\n<hr />\n<h1>Improved code</h1>\n<pre><code>def find_busiest_period(data):\n &quot;&quot;&quot;\n Find the timestamp when the greatest number of people\n are in the building.\n\n &gt;&gt;&gt; find_busiest_period([]) is None\n True\n\n &gt;&gt;&gt; find_busiest_period([ [0, 0, 2] ])\n Traceback (most recent call last):\n ...\n ValueError: 2\n\n &gt;&gt;&gt; find_busiest_period([ [0, -5, 0] ])\n Traceback (most recent call last):\n ...\n ValueError: -5\n\n &gt;&gt;&gt; find_busiest_period([ [0, 5, 1], [2, 5, 1], [3, 5, 0] ])\n 2\n\n &gt;&gt;&gt; find_busiest_period([ [1487799425, 14, 1], \\\n [1487799425, 4, 0], \\\n [1487799425, 2, 0], \\\n [1487800378, 10, 1], \\\n [1487801478, 18, 0], \\\n [1487801478, 18, 1], \\\n [1487901013, 1, 0], \\\n [1487901211, 7, 1], \\\n [1487901211, 7, 0] ])\n 1487901211\n &quot;&quot;&quot; \n people = 0 \n max_time = None\n max_people = 0\n\n for time,quantity,direction in data:\n if quantity &lt; 0:\n raise ValueError(quantity)\n if direction == 1:\n # Some people entered\n people += quantity\n # Have we reached a new maximum?\n if people &gt; max_people:\n max_time, max_people = time, people\n elif direction == 0:\n # Some people left\n people -= quantity\n else:\n raise ValueError(direction)\n\n return max_time \n\n\nif __name__ == &quot;__main__&quot;:\n import doctest\n doctest.testmod()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T11:08:13.750", "Id": "212533", "ParentId": "212491", "Score": "2" } }, { "body": "<p>Toby has covered many excellent points in his review. I won't repeat them here. What I will do is cover composition of the algorithm. You are trying to do everything in one function. It is often better to break the algorithm down into steps, and chain the individual pieces together.</p>\n\n<p>You start off with a stream (list) of raw data, containing the time, quantity of people, and direction they are moving. You can create a \"generator expression\" which can turn the quantity of people and direction they are moving into a incremental change in the total number of people.</p>\n\n<pre><code>deltas = ((time, quantity if enter else -quantity) for time, quantity, enter in data)\n</code></pre>\n\n<p>The above generator expression will take each row of data from the list, calling the individual pieces <code>time</code>, <code>quantity</code> and the <code>enter</code> flag respectively. It then converts <code>quantity</code> and <code>enter</code> flag into a positive quantity, for people entering, or a negative quantity, for people leaving. It produces a stream of tuples containing the time and the change in the number of people. Ie, <code>print(list(deltas))</code> would produce:</p>\n\n<pre><code>[(1487799425, 14), (1487799425, -4), (1487799425, -2), (1487800378, 10), (1487801478, -18), (1487801478, 18), (1487901013, -1), (1487901211, 7), (1487901211, -7)]\n</code></pre>\n\n<p>We can feed this stream into another generator which accumulates the change in number of people. This time, I'll use a generator function, since <code>population</code> is a state quantity that needs to persist from sample to sample:</p>\n\n<pre><code>def population_over_time(deltas):\n population = 0\n for time, delta in deltas:\n population += delta\n yield time, population\n</code></pre>\n\n<p>This would turn the list of times and deltas into a list of times and populations. Ie) <code>print(list(population_over_time(deltas)))</code> would produce:</p>\n\n<pre><code>[(1487799425, 14), (1487799425, 10), (1487799425, 8), (1487800378, 18), (1487801478, 0), (1487801478, 18), (1487901013, 17), (1487901211, 24), (1487901211, 17)]\n</code></pre>\n\n<p>From this stream of tuples, the <a href=\"https://docs.python.org/3/library/functions.html#max\" rel=\"nofollow noreferrer\"><code>max()</code></a> function can easily return the first tuple corresponding to the maximum population. We'll need to use <a href=\"https://docs.python.org/3/library/operator.html#operator.itemgetter\" rel=\"nofollow noreferrer\"><code>operator.itemgetter(1)</code></a> to extract the population value from the tuple to use as the key:</p>\n\n<pre><code>peak = max(population_over_time(deltas), key=operator.itemgetter(1))\n</code></pre>\n\n<p>This will assign <code>(1487901211, 24)</code> to <code>peak</code>. Since we just want the time of the maximum population, we can <code>return peak[0]</code>.</p>\n\n<p>Putting the pieces together, and reorganizing a bit, we can get:</p>\n\n<pre><code>from operator import itemgetter\n\ndef population_deltas(data):\n return ((time, quantity if enter else -quantity) for time, quantity, enter in data)\n\ndef population_over_time(data):\n population = 0\n for time, delta in population_deltas(data):\n population += delta\n yield time, population\n\ndef find_busiest_period(data):\n return max(population_over_time(data), key=itemgetter(1))[0]\n</code></pre>\n\n<p>In addition to the busiest period, you also have a function to produce the population over time, if you wanted to graph that information. Instead of writing many functions to process the data from start to finish, you have tiny pieces of code which can be assembled as needed to produce the desired product, and could be combined in different fashions as needed to produce other data.</p>\n\n<p>An important aspect of the above approach which bears mentioning: no lists are being created. The <code>population_deltas</code> and <code>population_over_time</code> are generators, which produce one value at a time. The <code>max()</code> function asks <code>population_over_time()</code> for a value, which in turns asks <code>population_deltas()</code> for a value, which retrieves an item from <code>data</code>. Then, <code>max()</code> asks for the next value, and keeps the largest. Then it asks for another value and keeps the largest, and so on. Memory requirement: <span class=\"math-container\">\\$O(1)\\$</span>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T04:58:19.057", "Id": "212603", "ParentId": "212491", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T22:29:38.770", "Id": "212491", "Score": "2", "Tags": [ "python", "interview-questions" ], "Title": "Given entrance and exit logs, find the population maximum" }
212491
<p>I would like to receive feedback on my coding interview for the following problem:</p> <blockquote> <h3>Bracket Match</h3> <p>A string of brackets is considered correctly matched if every opening bracket in the string can be paired up with a later closing bracket, and vice versa. For instance, “(())()” is correctly matched, whereas “)(“ and “((” aren’t. For instance, “((” could become correctly matched by adding two closing brackets at the end, so you’d return 2.</p> <p>Given a string that consists of brackets, write a function bracketMatch that takes a bracket string as an input and returns the minimum number of brackets you’d need to add to the input in order to make it correctly matched.</p> <p>Explain the correctness of your code, and analyze its time and space complexities.</p> <blockquote> <p>Examples:</p> <p>input: text = “(()” output: 1</p> <p>input: text = “(())” output: 0</p> <p>input: text = “())(” output: 2 Constraints:</p> <p>[time limit] 5000ms</p> <p>[input] string text</p> <p>1 ≤ text.length ≤ 5000 [output] integer</p> </blockquote> </blockquote> <pre><code>def bracket_match(text): diffCounter = 0 answer = 0 length = len(text) for i in range(length): if text[i] == '(': diffCounter += 1 elif text[i] == ')': diffCounter -= 1 if diffCounter &lt; 0: diffCounter += 1 answer +=1 return answer + diffCounter text1=")))(" print(bracket_match(text1)) </code></pre>
[]
[ { "body": "<p>Doesn't look like you've done this:</p>\n\n<blockquote>\n <p>Explain the correctness of your code, and analyze its time and space complexities.</p>\n</blockquote>\n\n<hr>\n\n<p>This is an anti-pattern:</p>\n\n<pre><code> length = len(text)\n\n for i in range(length):\n # code using only `text[i]`, but never using `i`\n</code></pre>\n\n<p>You are computing the length of <code>text</code>, then using a <code>for</code> loop of over the <code>range(length)</code>, assigning the index to <code>i</code>, but then never using <code>i</code> for anything other than fetching the character <code>text[i]</code>.</p>\n\n<p>Far, far better is looping over the letters of <code>text</code>:</p>\n\n<pre><code> for ch in text:\n # use `ch` here.\n</code></pre>\n\n<hr>\n\n<p>Efficiency:</p>\n\n<pre><code> if text[i] == '(':\n # ...\n elif text[i] == ')':\n diffCounter -= 1\n if diffCounter &lt; 0:\n diffCounter += 1\n # ...\n</code></pre>\n\n<p>Will <code>diffCounter</code> ever be negative, without first subtracting 1 from it? No? Perhaps the next test belongs in the <code>elif</code> clause:</p>\n\n<pre><code> if text[i] == '(':\n # ...\n elif text[i] == ')':\n diffCounter -= 1\n if diffCounter &lt; 0:\n diffCounter += 1\n # ...\n</code></pre>\n\n<p>But that is still subtracting 1 and then (possibly) immediately adding 1 again. Better: check for the underflow condition first.</p>\n\n<pre><code> if text[i] == '(':\n # ...\n elif text[i] == ')':\n if diffCounter &gt; 0:\n diffCounter -= 1\n else:\n # ...\n</code></pre>\n\n<hr>\n\n<p>While the <code>diffCounter</code> is an understandable variable name (barely), the variable named <code>answer</code> is completely mysterious. Answer to what? Why is it incremented when there is an underflow? Why is it added to <code>diffCounter</code> at the end. Not a comment in sight, and the code is anything but self documenting.</p>\n\n<hr>\n\n<p>Follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> coding standards, and use <code>pylint</code> or other style checker. For instance, variables should not be <code>camelCase</code>, and <code>answer +=1</code> needs an extra space.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T01:21:03.280", "Id": "412349", "Score": "0", "body": "Just for the fun of it, I've refactored your suggestions, and renamed some variables into [this repl](https://repl.it/@holroy/BracketMatcher)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T05:58:48.873", "Id": "412353", "Score": "0", "body": "@holroy I disagree with your space complexity. While it is true the input string has N characters, you are only using 2 extra scalar state variables, so I'd say the space complexity is \\$O(1)\\$." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T23:36:58.903", "Id": "212496", "ParentId": "212492", "Score": "3" } }, { "body": "<p>From my experience in job interviews that question usually takes you to implements a solution with one type of data-structure.</p>\n\n<p>A good implementation will be using a stack that load each '(' bracket and unloads each ')' bracket. In that way you can iterate over the text and if you encounter ') bracket beforehand you add to the result.</p>\n\n<p>In Python you can use list type object as a Stack, <a href=\"https://docs.python.org/3.6/tutorial/datastructures.html\" rel=\"nofollow noreferrer\">reference</a>.</p>\n\n<p>Implementation example using stack in python3:</p>\n\n<pre><code>def bracket_match(text):\n pairs = {'(': ')'} # Using dictionary for O1 get\n sk = []\n res = 0\n for c in text:\n if c in pairs:\n sk.append(pairs[c])\n elif sk and c == sk[-1]:\n sk.pop()\n else:\n res += 1\n return res + len(sk)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T16:25:20.110", "Id": "412338", "Score": "0", "body": "Forgot to return the len of the stack obviously, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T01:06:20.880", "Id": "412348", "Score": "0", "body": "I like the stack approach, but how does it handle tests starting with ending brackets? Or have a surplus of ending brackets? Are those conditions properly handled by the `res += 1` option?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T08:10:33.110", "Id": "412357", "Score": "2", "body": "a big -1 from me. 1) This is a code review. you should review the code of the OP and not present your solutions of the problem. If you have your implemented a solution and want to know what this community thinks about your solution then post your solution as question and it will be reviewed.2) it makes no sens to use a stack if an integer variable is sufficient, 3)your code isn't good and the OP should not try to copy it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T08:52:58.997", "Id": "412358", "Score": "3", "body": "apparently you copied most part of your code from [here](https://www.hackerrank.com/challenges/ctci-balanced-brackets/forum/comments/216703). But the original code handles different types of brackets and this makes it necessary to use a stack. In the OP there is only one kind of brackets is used and a stack makes no sense. Also the usage of the dictionary 'pair' makes sense in the original source but no sense in your code. It does not make sense to present code here that was written by other people that you apparently do not completely understand ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T08:54:41.650", "Id": "412359", "Score": "3", "body": "... and I think it is very impolite to use code of other people without citing the source." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T10:22:12.350", "Id": "412373", "Score": "0", "body": "1) He asked this question within the context of job interview, so I've wrote the comment _\"..From my experience in job interviews that question usually takes you to implements a solution with one type of data-structure...\"_ \n2) It make sense if your looking for a known data-structure solution\n3) About copying the code, please this question is the most famous question in CS job interviews and this solution appears in most learning books and also in hackerrank." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T00:56:36.520", "Id": "514110", "Score": "1", "body": "@hodisr, Your suggestion to start with a stack is a good one, but if you can get rid of the stack and reduce the space complexity (without sacrificing the time complexity), you should at least make that suggestion to your interviewer during your coding interview and ask if they would prefer that solution (to which, they'll probably say 'yes'). And no, those problems you saw on leetcode and hackerrank may all look identical to this one, but they're not completely identical. And if you want to do well during your technical coding interviews, you need to be able to pick up on those differences." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T10:36:42.890", "Id": "212530", "ParentId": "212492", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T22:41:09.897", "Id": "212492", "Score": "2", "Tags": [ "python", "interview-questions", "balanced-delimiters" ], "Title": "Bracket matcher in Python" }
212492
<p>I was given this question during an interview. It is similar to two sum problems and I would like to ask for feedback for my solution. </p> <blockquote> <p>Merging 2 Packages</p> <p>Given a package with a weight limit limit and an array arr of item weights, implement a function getIndicesOfItemWeights that finds two items whose sum of weights equals the weight limit limit. Your function should return a pair [i, j] of the indices of the item weights, ordered such that i > j. If such a pair doesn’t exist, return an empty array.</p> <p>Example:</p> <p>input: arr = [4, 6, 10, 15, 16], lim = 21</p> <p>output: [3, 1] # since these are the indices of the # weights 6 and 15 whose sum equals to 21 Constraints:</p> <p>[time limit] 5000ms</p> <p>[input] array.integer arr</p> <p>0 ≤ arr.length ≤ 100 [input] integer limit</p> <p>[output] array.integer</p> </blockquote> <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>function getIndicesOfItemWeights(arr, limit) { let weights = {}; let result = [] for ( let i = 0; i &lt; arr.length; i++){ let compliment = limit - arr[i]; if (typeof weights[compliment]!= "undefinded"){ if (i &gt; (weights[compliment])){ result.push(weights[compliment], i); //return [i, weights[compliment]]; } else { return [weights[compliment] , i]; } } else { weights[arr[i]] = i; // put new weight into weight obj } } return []; } let arr = [4, 6, 10, 15, 16]; let limit = 21; console.log(getIndicesOfItemWeights(arr, limit)) // output: [3, 1] # since these are the indices of the // weights 6 and 15 whose sum equals to 21</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T00:08:49.123", "Id": "411030", "Score": "2", "body": "Your code logs `[undefined, 0]` - should it actually log `[3, 1]`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T04:08:06.280", "Id": "411041", "Score": "0", "body": "Is the array of weights sorted?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T16:59:40.487", "Id": "412410", "Score": "1", "body": "As Sam Onela pointed out, the code doesn't work as intended, returning `[undefined, 0]` instead of `[3, 1]`. The commented out `return` statement looks suspicious, so is the typo \"undefinded\" (instead of `undefined`)" } ]
[ { "body": "<p>there are many ways to aproach this, somehow i find your solution alittle bit difficult to read but i like the idea of using <code>compliment = limit - arr[i];</code></p>\n\n<p>a simpler way would be either using nested <code>for</code> loops :</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 getIndicesOfItemWeights = (arr, limit) =&gt; {\n let result = [];\n\n for (let i = 0; i &lt; arr.length; i++) {\n if (result[0] &amp;&amp; result[1]) break; // break out of the loop if the result is full.\n\n for (let j = i; j &lt; arr.length; j++) {\n if (arr[i] + arr[j] === limit) { // if the sum of two elements is eqaul to the limit.\n result.push(i, j); // push the indices to the result array. \n break; // break out of the second loop\n }\n }\n }\n\n return result.sort((a, b) =&gt; b - a);\n}\n\nconst arr = [4, 6, 10, 15, 16];\nconst limit = 21;\n\nconst x = getIndicesOfItemWeights(arr, limit);\nconsole.log(x)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>or take the shortcut of using the <code>compliment = limit - arr[i];</code></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const arr = [4, 6, 10, 15, 16];\nconst limit = 21;\n\nconst getIndicesOfItemWeights = (arr, limit) =&gt; {\n let result = [];\n\n arr.forEach(e =&gt; {\n const a = arr.find(x =&gt; x === limit - e);\n if (a &amp;&amp; result.length === 0) { // if the element is found and the array is empty, push the indices to the result array\n result.push(arr.indexOf(e), arr.indexOf(a));\n return;\n }\n })\n\n return result.sort((a, b) =&gt; b - a);\n}\n\nconst x = getIndicesOfItemWeights(arr, limit);\nconsole.log(x)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T15:43:03.323", "Id": "212556", "ParentId": "212494", "Score": "1" } }, { "body": "<p>this is my updated solution after the code review:</p>\n\n<pre><code>let getIndicesOfItemWeights = function(arr, limit) {\n let map = new Map()\n let indices = []\n for(let i = 0; i &lt; arr.length; i++){\n let difference = limit-arr[i]\n if(map.has(difference)){\n indices.push(i, map.get(difference))\n return indices\n } else {\n map.set(arr[i], i)\n }\n }\n return indices\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T21:26:25.903", "Id": "212584", "ParentId": "212494", "Score": "0" } } ]
{ "AcceptedAnswerId": "212584", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T22:45:11.557", "Id": "212494", "Score": "-1", "Tags": [ "javascript", "interview-questions", "ecmascript-6", "k-sum" ], "Title": "Two-sum solution in JavaScript" }
212494
<p>I have a simple task that I can't find an elegant solution to. Say I have two arrays and I want to find which one is shorter and create variables for both their lengths (specifying them as long and short). Here's an inelegant way to do it:</p> <pre><code>l1 = len(arr1) l2 = len(arr2) if l1 &lt; l2: short_arr = arr1 long_arr = arr2 lshort = l1 llong = l2 else: short_arr = arr2 long_arr = arr1 lshort = l2 llong = l1 </code></pre> <p>What's a better way to do it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T06:04:48.283", "Id": "411052", "Score": "2", "body": "Sometimes simple and straightforward is really the way to go." } ]
[ { "body": "<p>There is nothing inelegant about your code. You are computing the length of each array exactly once, have one test, and assign variables in each of the two paths of the branch. It is clean, fast, and efficient.</p>\n\n<p>You could make it shorter by combining the assignments into structured assignment statement:</p>\n\n<pre><code>l1, l2 = len(arr1), len(arr2)\n\nif l1 &lt; l2:\n short_arr, long_arr = arr1, arr2\n lshort, llong = l1, l2\nelse:\n short_arr, long_arr = arr2, arr1\n lshort, llong = l2, l1\n</code></pre>\n\n<p>but it is debatable whether that is clearer.</p>\n\n<hr>\n\n<p>I can’t claim this is more elegant, but it is significantly shorter:</p>\n\n<pre><code>short_arr, long_arr = (arr1, arr2) if len(arr1) &lt; len(arr2) else (arr2, arr1)\nlshort, llong = len(short_arr), len(long_arr)\n</code></pre>\n\n<p>And the absolutely wrong way to do it would be:</p>\n\n<pre><code>((lshort, short_arr), (llong, long_arr)) = sorted([(len(arr1), arr1), (len(arr2), arr2)])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T01:54:47.660", "Id": "212502", "ParentId": "212501", "Score": "2" } }, { "body": "<p>You want shorter? I don't think these improve anything, but they're fewer lines of code.</p>\n\n<pre><code>l1, l2 = len(arr1), len(arr2)\n\nif l1 &lt; l2:\n arr1, l1, arr2, l2 = arr2, l2, arr1, l1\n\n short_arr, lshort, long_arr, llong = arr2, l2, arr1, l1\n</code></pre>\n\n<p>or maybe</p>\n\n<pre><code>if len(arr1) &lt; len(arr2):\n arr1, arr2 = arr2, arr1\n\nshort_arr, lshort, long_arr, llong = arr2, len(arr2), arr1, len(arr1)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if len(arr1) &lt; len(arr2):\n arr1, arr2 = arr2, arr1\n\nshort_arr = arr2\nlong_arr = arr1\nlshort = len(arr2)\nllong = len(arr1)\n</code></pre>\n\n<p>Admittedly, this doesn't leave the lists how they were at first.</p>\n\n<p>Personally, if I had to choose between my hacks, AJNeufeld's permutations, or your code, I'd go with your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T06:04:17.310", "Id": "212514", "ParentId": "212501", "Score": "1" } }, { "body": "<p>If you want to sort variables, you can use <code>sorted</code> with tuple unpacking:</p>\n\n<pre><code>short_arr, long_arr = sorted([arr1, arr2], key=len)\nlshort, llong = len(short_arr), len(long_arr)\n</code></pre>\n\n<p>This does call <code>len</code> twice on each array, but I think that trade-off is fine since it is <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> for lists anyways.</p>\n\n<p>You could avoid it, but that would make it a lot harder to read, IMO:</p>\n\n<pre><code>(lshort, short_arr), (llong, long_arr) = sorted([(len(arr1), arr1), (len(arr2), arr2)])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T08:27:26.963", "Id": "212522", "ParentId": "212501", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T01:41:36.833", "Id": "212501", "Score": "1", "Tags": [ "python" ], "Title": "Python set variables to shorter list and list length" }
212501
<p>For a programming challenge I was doing, I needed to traverse a list of lists, and while writing the standard 2D traversal function, I thought why not generalise it, so I did. Here's my best effort:</p> <h3>My Code</h3> <pre><code>def rTraverse(lst, f = lambda x: x): #Traverse a list and any of its (non self referential) sublists recursively. for item in lst: if isinstance(item, list): if "..." in str(item): #Skip self-referential lists. continue traverse(item, f) #Traverse the sublist. else: f(item) </code></pre>
[]
[ { "body": "<p>Well, one failure case that I didn't consider is that sublists that contain strings with \"...\" inside them break the function. Furthermore, converting a list to a string is an expensive operation. After consulting with people outside SE, I was able to refine the algorithm further:</p>\n\n<h3>Refactored Version</h3>\n\n<pre class=\"lang-py prettyprint-override\"><code>\"\"\"\n* A faster version of `rTraverse()` that uses a set instead of a stack to store a list's ancestry. \n\n* Searching a set is O(1) in the average case, while searching a list is O(n) in the average case, so `rTraverse2()` would run faster.\n* Params:\n * `lst`: the list to be traversed.\n * `f`: the function to be applied to the list items.\n * `seen`: a set that stores the ancestry of the current sublist. (would be used for checking if a sublist is self referential).\n* Return:\n * None: The list is modified in place.\n* Caveats:\n * The function no longer traverses in order.\n* Credits:\n * The main insight(s) for the algorithm comes from \"raylu\" on the [programming discord](https://discord.gg/010z0Kw1A9ql5c1Qe)\n\"\"\"\ndef rTraverse2(lst, f, seen=None):\n seen = set() if seen is None else seen #Initialise the set.\n toRecurse = [] #The list of sublists to be recursed on.\n for idx in range(len(lst)):\n if isinstance(lst[idx], list):\n if id(lst[idx]) not in seen: #Traverse only non self referential sublists.\n toRecurse.append(lst[idx]) #Add the sublist to the list of sublists to be recursed upon.\n else:\n lst[idx] = f(lst[idx])\n seen.update(id(x) for x in toRecurse)\n for item in toRecurse: #Traverse all sublists in `toRecurse`.\n rTraverse2(item, f, seen)\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T03:09:29.830", "Id": "411039", "Score": "1", "body": "`seen=[]` in the argument list is a bad idea. That list is created once (at compile time) and is shared amongst all invocations of the function. This means you can’t have two threads calling the function at once. It also means if `f` raises an exception, then `rTraverse()` could be exited without draining `seen` back to an empty list, so the next time `rTraverse()` is called, it could misbehave!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T09:04:21.250", "Id": "411070", "Score": "0", "body": "There's actually another version that uses a set instead and doesn't do , place `seen` in the argument list. I'll update the answer with the current versions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T02:59:12.433", "Id": "212506", "ParentId": "212503", "Score": "0" } }, { "body": "<p>The way you keep track of lists which you are currently exploring is a bit inefficient. You basically have a stack which contains the first argument of the function for each recursive call. This exact information is also stored on the execution stack of the Python interpreter, so it's duplicated.</p>\n\n<p>A more efficient way would be to <strong>abandon recursion</strong> and use a cycle instead, since you are already using a stack. That way, you will also save some more space by not duplicating the constant (non-changing) arguments <code>f</code> and <code>seen</code> on the execution stack.</p>\n\n<p>Another, even more significant way to improve efficiency is by observing that the check <code>if lst[idx] not in seen</code> <strong>takes linear time</strong>, although this <strong>can be done in constant time</strong>.</p>\n\n<p><strong>1. <em>Removing recursion</em></strong></p>\n\n<p>We can start with the existing stack of lists and extend it as necessary. Since we are basically doing a dept-first search, upon descent to the deeper level we need to remember the list which we are currently iterating over, as well as the position within that list (so we can later return and continue where we left off). This can be done for example by having two lists, one containing the lists and the other one containing the positions. Or we can have just one list containing 2-tuples of the form <code>(list, position)</code>.</p>\n\n<p><strong>2. <em>Faster cyclic reference detection</em></strong></p>\n\n<p>Instead of searching through the stack, item by item, we can use a <code>set</code> as you suggested in a comment. This will allow us to detect cyclic references in constant time and the whole issue will be settled.</p>\n\n<p>An even better approach would be to combine the position-tracking with fast membership checking: we could have a list of lists (the stack), and a dictionary mapping each list to our position within that list. Then a list will be used as a key in the dictionary if and only if it is in the stack. Note that adding, updating and deleting items in a hashed dictionary are all essentially constant time operations, and so is checking whether a key is present. So we achieve constant time cycle detection, much like we would with a <code>set</code>, but in a more elegant way.</p>\n\n<p>One \"problem\" here may be that if we have the same list in the stack twice, with two different positions, which position do we put in the dictionary? Or can we somehow put both of them there? The answer is, we don't care, because this will never happen. Since we don't want to visit the same list twice on our path down the tree, the stack will never contain the same list twice. Now the only problem is that <strong>Python doesn't allow us to use <code>list</code> objects as keys in <code>dict</code></strong>.</p>\n\n<p><strong>3. <em>Using lists as keys in a dictionary</em></strong></p>\n\n<p>Since <code>list</code> is not a hashable type, it cannot be used as a key in <code>dict</code> (which is a hashed dictionary). However, the solution is quite simple: we use <code>id(lst)</code> instead of the <code>lst</code> itself as the key. We can do this, since we only care about identity, not equality. As a side note, this is another case in which your program behaves incorrectly. It compares lists with the items in <code>seen</code> based on equality, not identity: <code>if lst[idx] not in seen: …</code>. Consider following code:</p>\n\n<pre><code>&gt;&gt;&gt; a = []\n&gt;&gt;&gt; a.append(a)\n&gt;&gt;&gt; b = [a]\n&gt;&gt;&gt; a == b\nTrue\n&gt;&gt;&gt; id(a) == id(b)\nFalse\n&gt;&gt;&gt; a in [b]\nTrue\n</code></pre>\n\n<p>What should happen if you call <code>rTraverse(b)</code>? I suppose you would want to traverse both <code>a</code> and <code>b</code>.</p>\n\n<p><br/></p>\n\n<hr>\n\n<h3>Refactored code</h3>\n\n<p>The code contains a (very basic) implementation of a custom data structure which facilitates the above-proposed approach. This data structure is then employed in the modified <code>traverse</code> function.</p>\n\n<pre><code>class CustomStack(list):\n \"\"\"\n Our custom data structure to facilitate position-tracking\n and provide constant time membership checking for cycle detection.\n\n This data structure serves as the stack, hence inherits from `list`.\n It has an `item_pos` attribute which serves as the dictionary.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__((item for item, pos in args), **kwargs)\n self.item_pos = {id(item): pos for item, pos in args}\n\n def append(self, item, pos):\n if item not in self:\n super().append(item)\n self.item_pos[id(item)] = pos\n\n def pop(self):\n del self.item_pos[id(self.top)]\n return super().pop()\n\n def __contains__(self, item):\n return id(item) in self.item_pos\n\n def __getitem__(self, idx):\n item = super().__getitem__(idx)\n pos = self.item_pos[id(item)]\n return item, pos\n\n @property\n def top(self):\n return super().__getitem__(-1)\n\n def setpos(self, pos):\n \"\"\"\n This functions allows us to update the saved position within the list\n which is being currently explored (= is last in the stack).\n \"\"\"\n self.item_pos[id(self.top)] = pos\n\n\ndef traverse(lst, f = lambda x: x):\n\n stk = CustomStack((lst, 0)) # initial position in the list is 0\n\n while stk:\n curr_list, curr_pos = stk[-1] # don't pop the top of the stack yet\n\n for idx in range(curr_pos, len(curr_list)): # continue from the saved position\n\n item = curr_list[idx]\n\n if isinstance(item, list) and item not in stk:\n stk.setpos(idx+1) # update the current position to restore it later\n stk.append(item, 0) # push the new list onto the stack\n break # we are going depth-first into the new, deeper list\n else:\n curr_list[idx] = f(item)\n\n else:\n # we did not break out of the `for` loop. that means we're done\n # with this list and we are returning to the previous level.\n stk.pop()\n​\n</code></pre>\n\n<hr>\n\n<h3>Recursive version</h3>\n\n<p>Since the code got a bit too long for such a simple task, we can try going back to using recursion, and use a <code>set</code> as you proposed. Similarly to the case with a dictionary, we have to use <code>id(lst)</code> instead of <code>lst</code>, because items in a <code>set</code> are hashed. Considering AJNeufeld's remarks on thread and exception safety, we can use a dummy default value for the <code>seen</code> parameter, and if we see that <code>seen</code> has this dummy value (as opposed to a \"real\" value, eg. a <code>set</code> instance), then we create a <code>set</code> instance as a local variable on the function's stack frame. Upon recursively calling the function, we pass a reference to this local variable, therefore no thread safety or exception safety issues ensue.</p>\n\n<pre><code>def traverse_simple(lst, f=lambda x: x, seen=None):\n\n if seen is None:\n seen = set()\n\n seen.add(id(lst))\n\n for i, item in enumerate(lst):\n\n if isinstance(item, list) and id(item) not in seen:\n traverse_simple(item, f, seen)\n else:\n lst[i] = f(item)\n\n seen.remove(id(lst))\n​\n</code></pre>\n\n<p>By using <code>id(lst)</code>, we are able to not only use a set and therefore detect cyclic references in constant time; we are also able to compare lists by identity instead of equality. This means the function does not fail on inputs on which your original function does fail, such as this:</p>\n\n<pre><code>&gt;&gt;&gt; a = []\n&gt;&gt;&gt; b = [a]\n&gt;&gt;&gt; a.append(b)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T20:27:49.253", "Id": "212716", "ParentId": "212503", "Score": "1" } } ]
{ "AcceptedAnswerId": "212716", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T02:11:44.380", "Id": "212503", "Score": "1", "Tags": [ "python", "performance", "algorithm", "array", "recursion" ], "Title": "Recursive Transversal (Python)" }
212503
<p>I've written a function to sort an array that interweaves an arrays values in the way of if you had two separate arrays [1,2,3,4,5] on one side and [6,7,8,9,0] on the other and it becomes [1, 6, 2, 7, 3, 8, 4, 9, 5, 0].</p> <p>The code works, but I'm wondering how it can be cleaned up and be more performant without the need for three additional arrays and to see if it can be done on the cards array itself.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let data = [1,2,3,4,5,6,7,8,9,0]; const interweave = data =&gt; { const _data = []; const l = data.slice(0, data.length / 2); const r = data.slice(data.length / 2, data.length); if (l.length === r.length) { for (let i = 0; i &lt; l.length; i++) { _data.push(l[i], r[i]); } } return _data; } interweave(data);</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T04:01:20.990", "Id": "411040", "Score": "0", "body": "I wouldn't call this deck _shuffled_. It all depends on your definition of shuffling." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T04:09:00.823", "Id": "411042", "Score": "0", "body": "@vnp, updated the wording" } ]
[ { "body": "<p>One approach would be to utilize <code>.splice()</code> instead of <code>.slice()</code> and <code>.shift()</code>. </p>\n\n<p>If the input array is expected to be mutated <code>const copy = [...arr]</code> can be removed and the array methods can be called on input <code>arr</code> : <code>data</code></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let data = [1,2,3,4,5,6,7,8,9,0];\n\nconst interweave = arr =&gt; {\n const copy = [...arr]; // copy input\n const r = copy.splice(Math.ceil(copy.length / 2)); // splice half of input\n for (let i = 1; r.length; i += 2) // set `i` to `1` increment by `2`\n copy.splice(i, 0, r.shift()); // use `.splice()` and `.shift()`\n return copy; // return `copy`\n}\n\nconsole.log(interweave(data));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T05:38:24.267", "Id": "212512", "ParentId": "212504", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T02:44:01.687", "Id": "212504", "Score": "0", "Tags": [ "javascript" ], "Title": "Interweaving an array's values" }
212504
<p>I've been tasked with writing a windows form application that offers some options to modify the drawing of shapes within another window. I have very little experience with event-driven programming and I'd like to improve my skill.</p> <pre><code>using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using GDIDrawer; namespace ICA3 { public enum ShapeType { Square, Circle }; public partial class master : Form { const int _HEIGHT = 600; const int _WIDTH = 800; const int _SIZE = 50; Color DEFAULT_COLOR = Color.Red; Color CURRENT_COLOR; CDrawer dr = new CDrawer(_WIDTH, _HEIGHT); shapeform sf = new shapeform(); public master() { InitializeComponent(); } private void master_btn_start_Click(object sender, EventArgs e) { CURRENT_COLOR = DEFAULT_COLOR; master_timer.Start(); } private void master_btn_stop_Click(object sender, EventArgs e) { master_timer.Stop(); } private void master_btn_color_Click(object sender, EventArgs e) { using (ColorDialog cd = new ColorDialog()) { if (cd.ShowDialog() == DialogResult.OK) { CURRENT_COLOR = cd.Color; } } } private void master_btn_shape_Click(object sender, EventArgs e) { sf.ShowDialog(); } private void master_timer_Tick(object sender, EventArgs e) { Point pt = new Point(); //borders if (sf._BORDER) { if (sf.shape == ShapeType.Circle) { if (dr.GetLastMouseLeftClick(out pt)) { dr.AddCenteredEllipse(pt, _SIZE, _SIZE, CURRENT_COLOR, 1, Color.White); } } else if (sf.shape == ShapeType.Square) { if (dr.GetLastMouseLeftClick(out pt)) { dr.AddCenteredRectangle(pt, _SIZE, _SIZE, CURRENT_COLOR, 1, Color.White); } } } //no borders else { if (sf.shape == ShapeType.Circle) { if (dr.GetLastMouseLeftClick(out pt)) { dr.AddCenteredEllipse(pt, _SIZE, _SIZE, CURRENT_COLOR); } } else if (sf.shape == ShapeType.Square) { if (dr.GetLastMouseLeftClick(out pt)) { dr.AddCenteredRectangle(pt, _SIZE, _SIZE, CURRENT_COLOR); } } } } } } </code></pre> <pre><code>using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ICA3 { public partial class shapeform : Form { ShapeType _SHAPE; public bool _BORDER = false; public ShapeType shape { get { return _SHAPE; } } public bool BorderChecked { get { return shapeform_cb_border.Checked; } } public shapeform() { InitializeComponent(); } private void shapeform_btn_ok_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; } private void shapeform_btn_cancel_Click(object sender, EventArgs e) { this.Close(); } private void shapeform_cb_border_CheckedChanged(object sender, EventArgs e) { _BORDER = shapeform_cb_border.Checked; } private void shapeform_rb_circle_CheckedChanged(object sender, EventArgs e) { _SHAPE = ShapeType.Circle; } private void shapeform_rb_square_CheckedChanged(object sender, EventArgs e) { _SHAPE = ShapeType.Square; } } } </code></pre> <p>I'm trying to learn the best practices in C# and Windows forms, so tips are much appreciated.</p>
[]
[ { "body": "<p><strong>Code Review submission:</strong> It's very helpful for reviewers to be able to execute your code, so that they can observe it \"in action\" (and, in my case, test out possible revisions). Before I could build this code, I had to</p>\n\n<ul>\n<li><p>Create a project with the classes described (which was easy, of course)</p></li>\n<li><p>Reverse-engineer the forms with the controls hinted at by your handler functions (which was a pain)</p></li>\n<li><p>Google for the library you used (<code>GDIDrawer</code>), and include it in the project too. If this had been any harder, I wouldn't have bothered, and you wouldn't have gotten a review.</p></li>\n</ul>\n\n<p>Obviously not getting my feedback specifically isn't the end of the world, but presumably feedback is what you're here for, so try to make it easy on us.</p>\n\n<hr/>\n\n<p><strong>Capitalization:</strong> Naming your classes with <code>PascalCase</code> (instead of <code>camelCase</code> or <code>alllowercase</code>) doesn't make them <em>inherently</em> easier to read... It makes them easier to read because that is the convention recommended by Microsoft and used by the majority of C# programmers. </p>\n\n<hr/>\n\n<p><strong>Separate files for enums:</strong> In my opinion, if multiple classes use an enum to communicate, that enum doesn't \"belong\" to either class, and merits its own file. There's no penalty for having a file that's only 6 lines long.</p>\n\n<hr/>\n\n<p><strong>Autoproperties:</strong> this C# feature may not be obvious, but it can be very useful to both shorten your code and better manage your objects' state. The following code defines a property called Shape that is publicly visible but only privately modifiable:</p>\n\n<pre><code>public ShapeType Shape { get; private set; }\n</code></pre>\n\n<hr/>\n\n<p><strong>Selection Feedback:</strong> This is a feature recommendation more than a code issue, but I found it very helpful to display the current state of the program. Next to <code>master_btn_shape</code> I placed a label. Whenever the shape dialog closed, I set that label to indicate the selection (for example \"Circle, no border\" or \"Square, border\")</p>\n\n<p>I did the same thing to indicate whether the program was currently \"Stopped\" or \"Waiting for clicks\".</p>\n\n<p>Next to the color button, I placed a small panel. Whenever the active color changed, I changed the background color of the panel.</p>\n\n<p>Speaking of the active color, I replaced <code>CURRENT_COLOR</code> with a property as follows. This saves the trouble of remembering to change the \"indicator panel\" manually from anywhere the current color can be changed.</p>\n\n<pre><code>private Color _currentColor;\nprivate Color CurrentColor // Not a constant, so no SCREAMING_SNAKE_CASE\n{\n get =&gt; _currentColor; // Could as easily be \"get { return currentColor; }\"\n set\n {\n _currentColor = value;\n master_pnl_currentColor.BackColor = value;\n }\n}\n</code></pre>\n\n<hr/>\n\n<p><strong>Initialization:</strong> I was puzzled at first that my shapes were being drawn in red when I had specified green. It wasn't until after I'd written the above code that I realized the active color is reset every time the start button is pressed. I recommend placing that sort of default initialization in the constructor.</p>\n\n<hr/>\n\n<p><strong>Respect \"cancel\":</strong> If I open the shape picker, change my selection, and then cancel out? My selection is changed anyway. Why even create a cancel button?</p>\n\n<hr/>\n\n<p><strong>Deep <code>if</code> nesting:</strong> The code in <code>master_timer_Tick</code> is a bit hairy. This is largely unavoidable given the structure of the overall program (and the library being used), but one way to reduce it would be with an \"early bail out\" if there is no click location:</p>\n\n<pre><code>private void master_timer_Tick(object sender, EventArgs e)\n{\n if (!dr.GetLastMouseLeftClick(out var lastClickLocation))\n return; // nothing to do here\n\n // method continues with only 2 layers of \"if\" nesting ...\n}\n</code></pre>\n\n<hr/>\n\n<p><strong>Object orientation:</strong> This suggestion is a larger overhaul, but you might find it useful as an exercise. One of the principles of OOP is abstraction: \"I have this thing that knows how to behave, so that I don't have to deal with the details\". Along those lines, you could create shapes that know how to draw themselves, so that the <code>Tick</code> handler is simply</p>\n\n<pre><code>private void master_timer_Tick(object sender, EventArgs e)\n{\n sf.CurrentShape.Draw(dr);\n}\n</code></pre>\n\n<p>This requires you to have defined an interface:</p>\n\n<pre><code>public interface IShapeDrawer\n{\n void Draw(CDrawer drawer);\n}\n</code></pre>\n\n<p>And you'll probably want a base class to handle the common click location detection:</p>\n\n<pre><code>public class ShapeDrawer : IShapeDrawer\n{\n public Draw(CDrawer drawer)\n {\n if (!drawer.GetLastMouseLeftClick(out var lastClickLocation))\n return;\n\n DrawAt(drawer, lastClickLocation);\n }\n protected abstract void DrawAt(CDrawer drawer, Point location);\n}\n</code></pre>\n\n<p>With child classes <code>BorderedCircleDrawer</code>, <code>NonBorderedSquareDrawer</code>, and so on. Each of those must implement <code>DrawAt</code>, making the appropriate call to <code>drawer</code>.</p>\n\n<p>In order to make this work, the shape picker form will need to know what the current ShapeDrawer is. One way to keep track of that might be in the properties:</p>\n\n<pre><code>public partial class ShapeForm\n{\n public IShapeDrawer ShapeDrawer { get; private set; }\n\n private void shapeform_btn_ok_Click(object sender, EventArgs e)\n {\n select case (_shape)\n {\n case (ShapeType.Circle):\n ShapeDrawer = _hasBorder \n ? new BorderedCircleDrawer()\n : new NonBorderedCircleDrawer();\n case (ShapeType.Sqaure)\n ShapeDrawer = _hasBorder \n ? new BorderedSquareDrawer()\n : new NonBorderedSquareDrawer();\n }\n }\n}\n</code></pre>\n\n<p>You'll notice that technically, the same if-nesting that we moved out of the <code>Tick</code> handler has been moved into this <code>Click</code> handler... It's up to you to decide where that complexity is best managed. I would argue it belongs in the ShapeForm (which I might rename to <code>ShapePicker</code> or <code>ShapeDialog</code>), because that's where the complexity of the related controls (check box and radio buttons) already lives.</p>\n\n<hr/>\n\n<p><strong>Further improvements:</strong> It might be nice if the ShapeDialog behaved more like the ColorDialog. For example, in how it uses <code>DialogResult</code>. It's almost always a good idea to match the behavior of existing objects in the standard libraries, because if you ever share your code, folks who know how to use those objects will have a head start to using yours. (This ties into the \"Respect 'cancel'\" point above)</p>\n\n<p>I don't love the <code>IShapeDrawer</code> interface I invented, in part because you have to pass around references to the <code>CDrawer</code>. You might peek into the GDIDrawer library itself, and see if you can tap into its <code>CEllipse</code> and <code>CRectangle</code> objects directly (instead of making your own <code>ShapeDrawer</code> objects. If you don't have to make different calls to the different <code>AddCenteredFoo</code> functions directly, you may be able to clean up the code even more.</p>\n\n<p>If you go that route, you might even try to reproduce the behavior of drawing shapes on the screen without using GDIDrawer at all - you might find it easier than you think.</p>\n\n<p>Even further along those lines, it might be neat to make the mouse behave more like a \"paintbrush\": Have a shape \"follow\" the mouse cursor around, and leave a copy behind whenever the mouse clicks.</p>\n\n<hr/>\n\n<p>For other reviewers: You may find <a href=\"https://gist.github.com/benj2240/69e3a5fd3fc2933751ef82ee87e38d18\" rel=\"nofollow noreferrer\">this more complete version of the code</a> helpful. It includes the necessary Windows Forms designer files to make a functioning GUI (although I'm sure it's nowhere near as pretty as OP's). I have also included <em>some</em> of the changes I suggested in my review - mostly around the instant feedback for the state of the application. I have not included the <code>GDIDrawer</code> project, but it is <a href=\"https://github.com/NAIT-CNT/GDIDrawer\" rel=\"nofollow noreferrer\">publicly available on Github</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T23:55:05.747", "Id": "411222", "Score": "1", "body": "Before I analyze the things you've said, I'd like to apologize for not including the right files for building the program. This is my first post here on Code Review so I will take these points into consideration next time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T00:20:29.477", "Id": "411223", "Score": "0", "body": "As far as naming UI components, is there a practice I should follow? This is my first multi-form program and I can already see how confusing the variable names can be without a proper convention." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T16:24:41.070", "Id": "411314", "Score": "0", "body": "Concerning the content of your future posts: Much appreciated, and I look forward to them! On the whole, this was a fun review. Concerning component names: I don't have very strong opinions. The fact that you bothered to name them at all (instead of leaving them as button1, button2, etc) is already helpful. There is more good discussion around control names on [this SO question](https://stackoverflow.com/questions/1246546/best-practices-for-c-sharp-gui-naming-conventions)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T22:59:55.347", "Id": "212590", "ParentId": "212508", "Score": "3" } } ]
{ "AcceptedAnswerId": "212590", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T03:04:45.843", "Id": "212508", "Score": "4", "Tags": [ "c#", "event-handling", "winforms" ], "Title": "Drawing shapes in a GDI window" }
212508
<p>I'm working on AI tic-tac-toe that computer make a move and I wanted to know that I correctly implemented the minimax algorithm. Please someone check my code to identify a problem or any kind of bug. Any help would be greatly appreciated.</p> <p>I wanted to know that my code is correctly running the minimax algorithm according to this image.</p> <p><a href="https://i.stack.imgur.com/98HtW.png" rel="nofollow noreferrer">test-cases-for-tic-tac-toe</a></p> <pre><code>from math import inf as infinity def winner(game, turn): win_game = [ [game[0][0], game[0][1], game[0][2]], [game[1][0], game[1][1], game[1][2]], [game[2][0], game[2][1], game[2][2]], [game[0][0], game[1][0], game[2][0]], [game[0][1], game[1][1], game[2][1]], [game[0][2], game[1][2], game[2][2]], [game[0][0], game[1][1], game[2][2]], [game[2][0], game[1][1], game[0][2]], ] if [turn, turn, turn] in win_game: return True else: return False def draw(game): """ Check whether the board is full """ counter = 0 for i in range(3): for j in range(3): if game[i][j] == "X" or game[i][j] == "O": counter+=1 return counter == 9 def game_over(game, turn): return winner(game, turn) or draw(game) def available_moves(game): cell = [] for i in range(3): for j in range(3): if not(game[i][j] == "X" or game[i][j] == "O"): cell.append([i, j]) return cell def minimax(game, turn): if winner(game, "X"): return 1 elif winner(game, "O"): return -1 elif draw(game): return 0 moves = available_moves(game) print(moves) if turn == "X": value = -infinity for move in moves: tmp = game[:][:] tmp[move[0]][move[1]] = "X" value = max(value, minimax(game, "O")) tmp[move[0]][move[1]] = None x, y = move[0], move[1] else: value = infinity for move in moves: tmp = game[:][:] tmp[move[0]][move[1]] = "O" value = min(value, minimax(game, "X")) tmp[move[0]][move[1]] = None x, y = move[0], move[1] return value if __name__ == '__main__': game = [ ["O", None, None], ["O", "X", "X"], [None, "O", "X"]] print(minimax(game, "X")) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T15:22:44.217", "Id": "411140", "Score": "0", "body": "Hi, sadly we only review working code. I encourage you to check the Help Center to see what kind of questions you may ask here :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:33:24.103", "Id": "411150", "Score": "0", "body": "I have rolled-back your question to the original. On Code Review, you cannot change your question once it has been answered, as doing so can invalidate any answers which have already been given. Code Review is also not for assistance locating and fixing bugs in code; it is for reviewing working code. A review may discover an previously unknown bug, but the code must be working to the best of your knowledge prior to posting it." } ]
[ { "body": "<p><code>tmp = game[:][:]</code> is not doing what you think it is doing. <code>game[:]</code> returns a slice of all the rows of <code>game</code> (so a list of columns). To that, you apply the slice operator <code>[:]</code>, which takes the slice of the row list (of columns), and returns a row list (of columns). In short, <code>game[:]</code> is the same as <code>game[:][:]</code>, which is the same as <code>game[:][:][:][:][:]</code>.</p>\n\n<p>In particular, <code>tmp</code> is list which contains references to the <strong>same</strong> column lists as <code>game</code>, so <code>tmp[row][col]</code> accesses exactly the same entry as <code>game[row][col]</code>. You have not created a temporary copy of <code>game</code>; you have created a copy of references to the same column list objects.</p>\n\n<p>As such, you can remove <code>tmp</code>, and just set <code>game[row][col]</code> directly, and set it back to <code>None</code> like you are doing via <code>tmp</code>.</p>\n\n<hr>\n\n<p>The code <code>x, y = move[0], move[1]</code> seems to be useless, since <code>x</code> and <code>y</code> are never used.</p>\n\n<hr>\n\n<p>The <code>minimax()</code> function returns the best possible outcome for that player, but doesn’t return the move that corresponds to that outcome. “You have a guaranteed winning move, but I’m not going to tell you what it is.”</p>\n\n<p>You might want to return the move that corresponds to that outcome.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T13:04:49.743", "Id": "411106", "Score": "0", "body": "But i have one problem now when I tested more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T13:12:44.600", "Id": "411108", "Score": "0", "body": "I update my quesiton. Please check my code @AJNeufeld" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T06:43:31.837", "Id": "212515", "ParentId": "212510", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T05:13:27.463", "Id": "212510", "Score": "0", "Tags": [ "python", "algorithm", "ai" ], "Title": "Could someone check the Minimax Algorithm correctly implemented?" }
212510
<p>I am exporting a List of virtual servers to a CSV file. The users submits filters and the applications generates FilterDTOs containing a map of the attribute and the corresponding value. The idea was to 'undock' the filter and the simple DTOs that contained all the variables from the export, so the export does not need to know the concrete filter (actually he knows but only to let the FilterDTOs be generated). All values in the map are <code>Optional&lt;String&gt;</code>. Here is the exporter, the <code>getFileEnding</code> and <code>getMediaType</code> are given by the interface to dynamically handle the return of a byte[] in a REST-controller (I need the file ending to parse the file and the media type for setting the HTTP headers). I would appreciate any critic and tips </p> <pre><code>public class FilteredCsvExporter implements Exporter { private ExportFilter filter; public FilteredCsvLbExporter(ExportFilter filter) { this.filter = filter; } @Override public void exportData() throws IOException, DocumentException { List&lt;VirtualServerFilterDTO&gt; servers = PoolRepository.getInstance().getVirtualServerFilterDTOs(filter); PrintWriter pw = new PrintWriter(new File(getBaseTempDir() + "/filteredExport.csv")); writeDataToFile(pw, new StringBuilder(), servers); } private void writeDataToFile(PrintWriter printWriter, StringBuilder builder, List&lt;VirtualServerFilterDTO&gt; servers) { generateHeadline(builder, servers); servers = servers.stream().filter(i -&gt; i.getAttributes().get("Pool").isPresent() != false).collect(Collectors.toList()); servers.forEach(server -&gt; { addMapToCsv(builder, server.getAttributes()); if (server.getAssignedPool().get().getAttributes().size() &lt;= 0) { return; } addMapToCsv(builder, server.getAssignedPool().get().getAttributes()); server.getAssignedPool().get().getMembers().forEach(member -&gt; { addMapToCsv(builder, member.getAttributes()); }); builder.append("\n"); }); builder.append("\n"); builder.append("\n"); builder.append("Pools that are not assigned to any virtual server"); builder.append("\n"); appendPoolsWithoutServerHeader(builder, servers); builder.append("\n"); getPoolsWithoutServer().forEach(pool -&gt; { addMapToCsv(builder, pool.getAttributes()); builder.append("\n"); }); printWriter.write(builder.toString()); printWriter.close(); System.out.println("Done"); getPoolsWithoutServer(); } private void appendPoolsWithoutServerHeader(StringBuilder builder, List&lt;VirtualServerFilterDTO&gt; servers) { servers.get(0).getAssignedPool().get().getAttributes().forEach((k, v) -&gt; { builder.append(k); builder.append(","); }); } private void addMapToCsv(StringBuilder builder, Map&lt;String, Optional&lt;String&gt;&gt; map) { for (Map.Entry&lt;String, Optional&lt;String&gt;&gt; entry : map.entrySet()) { if (entry.getValue().orElse("-").contains(",")) { builder.append(escapeStringForCSV(entry.getValue())); builder.append(","); } else { builder.append(entry.getValue().orElse("-")); builder.append(","); } } } private List&lt;PoolFilterDto&gt; getPoolsWithoutServer() { List&lt;VirtualServerFilterDTO&gt; servers = PoolRepository.getInstance().getVirtualServerFilterDTOs(filter); List&lt;PoolFilterDto&gt; pools = new ArrayList&lt;&gt;(); List&lt;PoolDTO&gt; poolDTOS = PoolRepository.getInstance().getPools().getPools(); List&lt;PoolDTO&gt; temp = new ArrayList&lt;&gt;(); for (int i = 0; i &lt; servers.size(); i++) { for (int j = 0; j &lt; poolDTOS.size(); j++) { VirtualServerFilterDTO server = servers.get(i); PoolDTO pool = poolDTOS.get(j); if (server.getAssignedPool().isPresent()) { if (server.getAssignedPool().get().getAttributes().size() &gt; 0) { if (server.getAssignedPool().get().getAttributes().get("Full path").get().equalsIgnoreCase(pool.getFullPath())) { temp.add(pool); } } } } } poolDTOS.removeAll(temp); poolDTOS.forEach(p -&gt; { pools.add(new PoolFilterDto(p, filter)); }); return pools; } private String escapeStringForCSV(Optional&lt;String&gt; value) { if (!value.isPresent()) { return "-"; } return "\"" + value.get() + "\""; } private void generateHeadline(StringBuilder builder, List&lt;VirtualServerFilterDTO&gt; servers) { servers.get(0).getAttributes().forEach((k, v) -&gt; { builder.append(k); builder.append(","); }); servers.get(0).getAssignedPool().get().getAttributes().forEach((k, v) -&gt; { builder.append(k); builder.append(","); }); int size = servers.stream().mapToInt(m -&gt; m.getAssignedPool().get().getMembers().size()).max().getAsInt(); Map&lt;String, Optional&lt;String&gt;&gt; map = servers.get(0).getAssignedPool().get().getMembers().get(0).getAttributes(); for (int i = 0; i &lt; size; i++) { for (Map.Entry&lt;String, Optional&lt;String&gt;&gt; entry : map.entrySet()) { builder.append(entry.getKey()); builder.append(","); } } builder.append("\n"); } @Override public File getBaseTempDir() { return new File(System.getProperty("java.io.tmpdir")); } @Override public String getFileEnding() { return ".csv"; } @Override public String getMediaType() { return "text/csv"; } } </code></pre>
[]
[ { "body": "<h2>(Re)use libraries</h2>\n<p>My main feedback would be that you should not create CSV yourself, but rather use OpenCSV or SuperCSV or another well supported CSV library.\nIf you really want to implement it yourself, make sure it follow the standard: <a href=\"https://www.rfc-editor.org/rfc/rfc4180\" rel=\"nofollow noreferrer\">RFC-4180</a>, so you have proper quoting and escaping.</p>\n<h2>When writing files, check the encoding</h2>\n<p>You currently use the default character encoding. While this can be correct, oft-times it is better to explicitly choose your own character encoding, for example UTF-8.</p>\n<h2>Prefer a logging framework for logging instead of <code>System.out</code></h2>\n<p>I saw:</p>\n<pre><code> System.out.println(&quot;Done&quot;);\n</code></pre>\n<p>See here: <a href=\"https://stackoverflow.com/a/8601972/461499\">https://stackoverflow.com/a/8601972/461499</a></p>\n<blockquote>\n<p>System.out.println is an IO-operation and therefor is time consuming.\nThe Problem with using it in your code is, that your program will wait\nuntil the println has finished. This may not be a problem with small\nsites but as soon as you get load or many iterations, you'll feel the\npain.</p>\n<p>The better approach is to use a logging framework. They use a message\nqueue and write only if no other output is going on.</p>\n</blockquote>\n<h2>Readability of streams</h2>\n<p>This is a taste-thing, but I prefer to write streams formatted like this:</p>\n<pre><code>servers = servers.stream()\n .filter(i -&gt; i.getAttributes().get(&quot;Pool&quot;).isPresent() != false)\n .collect(Collectors.toList());\n</code></pre>\n<p>Also, you can simplify the filter (true != false -&gt; true):</p>\n<pre><code>servers = servers.stream()\n .filter(i -&gt; i.getAttributes().get(&quot;Pool&quot;).isPresent())\n .collect(Collectors.toList());\n</code></pre>\n<p>The other thing in streams is something I try to stick to: don't let the stream modify it's outside state.\nYou use some <code>forEach()</code> that do modify the <code>builder</code>. I'd use a plain enhanced for-loop, I find it easier to read and easier to understand.</p>\n<h2>Don't close when you did not open</h2>\n<p><code>writeDataToFile</code> closes a stream that it did not open. This makes it harder to understand, and increases the probability that something goes wrong.</p>\n<p>I think the <code>exportData()</code> that creates the <code>PrintWriter</code> should also close it, and catch the appropriate exceptions. Maybe rethow them as needed as different exception. If you use try-with-resources it automatically closes the <code>AutoClosable</code>.</p>\n<pre><code>...\n try(PrintWriter pw = new PrintWriter(new File(getBaseTempDir() + &quot;/filteredExport.csv&quot;)))\n {\n ...\n } catch (...) { }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T14:17:25.380", "Id": "411123", "Score": "0", "body": "Hi, thanks for your feedback. I cannot use a third-party library, that's why I needed to do it on my own. Otherwise I would have used apache commons." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T14:22:02.877", "Id": "411126", "Score": "1", "body": "You're welcome. But please make sure you implement the RFC correctly, that saves a lot of headache for other developers ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T14:33:21.263", "Id": "411130", "Score": "0", "body": "Thanks. No comments on the codestyle itself?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T14:43:42.497", "Id": "411131", "Score": "1", "body": "Just my 2 cents; I care a bit about formatting so the code is easier to read, but that is mainly a taste thing." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T12:42:15.883", "Id": "212537", "ParentId": "212516", "Score": "1" } } ]
{ "AcceptedAnswerId": "212537", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T06:54:41.447", "Id": "212516", "Score": "1", "Tags": [ "java" ], "Title": "Java exporting filtered objects to CSV" }
212516
<p>I have to:</p> <p>1) Apply the Observer-Observable pattern to the original code.</p> <p>2) starting from the original code, I have to suppose that the modification of the array fields (slot machine numbers) should be done in parallel by 3 NumberGenerator threads instead of just one.</p> <p>My output seems to work fine but I'm wondering if my implemention is good enough or if am I doing something wrong. Could you tell me if my code is good or not?</p> <p><strong>ORIGINAL CODE:</strong></p> <pre><code>import java.util.*; public class SlotMachineApp { private static final int N = 3; public static void main(String[] args) { Numbers numeri = new Numbers(N); (new NumberGenerator(numeri)).start(); } } class NumberGenerator extends Thread { private Numbers nums; public NumberGenerator(Numbers numeri) { nums = numeri; } public void run() { Random r = new Random(); for (int i = 1; i &lt; 25; i++) { int index = r.nextInt(nums.getNum()); nums.set(index, r.nextInt(5)); nums.print(); try { sleep((int) (Math.random() * 100)); } catch (InterruptedException e) { return; } } } } class Numbers { private final int[] items; public Numbers(int n) { items = new int[n]; } public int getNum() { return items.length; } public void set(int index, int x) { items[index] = x; } public void print() { for (int i = 0; i &lt; items.length; i++) { System.out.print(items[i] + "\t"); } System.out.println(); int i = 0; while (i &lt; items.length - 1 &amp;&amp; items[i] == items[i + 1]) { i++; } if (i &gt;= items.length - 1) { System.out.println("ALL EQUAL!!!!"); } } } </code></pre> <p><strong>OBSERVER-OBSERVABLE IMPLEMENTATION:</strong></p> <p><strong>Model:</strong></p> <pre><code> package slot; import static java.lang.Thread.sleep; import java.util.Observable; import java.util.Random; public class Model extends Observable { private static final int N = 3; Numbers numbers = new Numbers(N); NumberGenerator ng = new NumberGenerator(numbers); class NumberGenerator extends Thread { private Numbers nums; public NumberGenerator(Numbers numbers) { nums = numbers; } public void run() { Random r = new Random(); for (int i = 1; i &lt; 25; i++) { int index = r.nextInt(nums.getNum()); nums.set(index, r.nextInt(5)); setChanged(); notifyObservers(); try { sleep((int) (Math.random() * 100)); } catch (InterruptedException e) { return; } } } } class Numbers { private final int[] items; public Numbers(int n) { items = new int[n]; } public int getNum() { return items.length; } public void set(int index, int x) { items[index] = x; } public void print() { for (int i = 0; i &lt; items.length; i++) { System.out.print(items[i] + "\t"); } System.out.println(); int i = 0; while (i &lt; items.length - 1 &amp;&amp; items[i] == items[i + 1]) { i++; } if (i &gt;= items.length - 1) { System.out.println("ALL EQUAL!!!!"); } } } } </code></pre> <p><strong>View:</strong></p> <pre><code>package slot; import java.util.Observable; import java.util.Observer; public class View implements Observer { @Override public void update(Observable o, Object arg) { if (o != null &amp;&amp; o instanceof Model) { ((Model) o).numbers.print(); } } } </code></pre> <p><strong>Controller:</strong></p> <pre><code>package slot; public class Controller { private Model model; private View view; public Controller(Model m, View v){ this.model = m; this.view =v; } } </code></pre> <p><strong>Main:</strong></p> <pre><code>package slot; public class Slot { public static void main(String[] args) { Model model = new Model(); View view = new View(); Controller controller = new Controller(model, view); model.addObserver(view); model.ng.start(); } } </code></pre> <p>MVC is not required I just like to use it for practice! If I did something wrong even in the MVC I would like to know please! I know that my Controller is doing nothing but actually I don't know which method to put inside to let Model and View comunicate since Observer-Observable calls update() from model to view.</p> <p><strong>Thread - Implementation with 3 NumberGenerator:</strong></p> <pre><code>import java.util.*; public class SlotMachineApp { private static final int N = 3; public static void main(String[] args) { Numbers numbers = new Numbers(N); NumberGenerator ng1 = new NumberGenerator(numbers); NumberGenerator ng2 = new NumberGenerator(numbers); NumberGenerator ng3 = new NumberGenerator(numbers); ng1.start(); ng2.start(); ng3.start(); } } class NumberGenerator extends Thread { private Numbers nums; public NumberGenerator(Numbers numbers) { nums = numbers; } public void run() { Random r = new Random(); for (int i = 1; i &lt; 25; i++) { int index = r.nextInt(nums.getNum()); nums.set(index, r.nextInt(5)); nums.print(); try { sleep((int) (Math.random() * 100)); } catch (InterruptedException e) { return; } } } } class Numbers { private final int[] items; public Numbers(int n) { items = new int[n]; } public synchronized int getNum() { return items.length; } public synchronized void set(int index, int x) { items[index] = x; } public synchronized void print() { for (int i = 0; i &lt; items.length; i++) { System.out.print(items[i] + "\t"); } System.out.println(); int i = 0; while (i &lt; items.length - 1 &amp;&amp; items[i] == items[i + 1]) { i++; } if (i &gt;= items.length - 1) { System.out.println("ALL EQUAL!!!!"); } } } </code></pre> <p>I modified the getNum (), set(), and print() methods by adding the keyword synchronized because I think that in this way each thread can work on its own avoiding race condition.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T07:34:34.003", "Id": "212517", "Score": "1", "Tags": [ "java", "multithreading", "mvc", "observer-pattern" ], "Title": "Applying Observer-Observable pattern to a code and multithreading" }
212517
<p>I am a beginner Python developer and I wrote a python script which reads releases data from Github for a specific release of a repository and write those release details to a specific file in google sheet. I used Github package for reading data from github API and gspread package for writing data to google sheet file. But my script is not structured well in code and has slow performance. I really like get comments about improving code structure and performance of script.</p> <pre><code># -*- coding: utf-8 -*- #! /user/bin/python2 # Import packages and libraries from github import Github from github import BadCredentialsException import gspread_formatting import gspread import oauth2client from oauth2client.service_account import ServiceAccountCredentials import getpass class ReadRelease: # Instances vairables sheet = '' username = '' password = '' repository_name = '' release_name = '' # Get user credentials from consule def get_user_credentials (self): self.username = raw_input("Github username: ") self.password = getpass.getpass(prompt='Github password: ') self.repository_name = raw_input("Repository name: ") self.release_name = raw_input('Release name: ') # Read details of all releases in a repository def read_requested_release_detials(self, release, tag_name, sheet, is_release_found): is_release_found = True release_body = release.body lines_in_release_body = (release_body.splitlines(0)) ReadRelease.read_lines_start_with_dash(self, lines_in_release_body, self.sheet, tag_name) # Read all releases names of a repository def read_all_releases_names(self, repository, release_name, sheet): is_release_found = False for release in repository.get_releases(): tag_name = (release.tag_name).encode('utf-8') name = (release.title).encode('utf-8') # Filter releases name with give release name if name == release_name: is_release_found = True ReadRelease.read_requested_release_detials(self, release, tag_name, self.sheet, is_release_found) if not is_release_found: print "'Release Name' is wrong!, Please try again with correct 'release name'" else: print "Releases inserted to the Google sheet." # Insert a line to google sheet file (those issues which are not fixed) def issue_not_fixed(self, sheet, tag_name, line, row): sheet.insert_row([tag_name, tag_name, line[7:].encode('utf-8'), 'NO'], row) # Insert a line to google sheet file and set fix the Is fixed? column def issue_fixed(self, sheet, tag_name, line, row): sheet.insert_row([tag_name, tag_name, line[7:].encode('utf-8'), 'YES'], row) # Read all lines in ralease body whihc start with '-' def read_lines_start_with_dash(self, lines_in_release_body, sheet, tag_name): # Counter for updating rows in google sheet file row = 2 for line in lines_in_release_body: if (line[:1]).encode('utf-8') == '-': if line[1:7].encode('utf-8') == ' [FIX]': ReadRelease.issue_fixed(self, sheet, tag_name, line, row) elif line[1:7].encode('utf-8') == '------': break else: ReadRelease.issue_not_fixed(self, sheet, tag_name, line, row) row += 1 # Set google sheet api credentials and open file on google sheet def set_google_sheet_credentials(self, sheet): scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive'] google_credentials = ServiceAccountCredentials.from_json_keyfile_name('test.json', scope) file = gspread.authorize(google_credentials) self.sheet = file.open('Copy_of_MOD_Change_Worklog_Tracker.xlsx').sheet1 # Add headers to the sheet self.sheet.update_acell('A1', 'Client Version') self.sheet.update_acell('B1', 'Version Reference for Internal Purposes') self.sheet.update_acell('C1', 'Proposed Change (Expected Functional Behavior)') self.sheet.update_acell('D1', 'Bug Fix?') # URL Builder method for github repository def prepare_github_repository_url(self): return(str('someuseraccount/'+ self.repository_name)) # Authunticate user in github def github_authunticate(self, username, password, url): github_account = Github(self.username, self.password) return (github_account.get_repo(url)) def main(): read_release_obj = ReadRelease() read_release_obj.get_user_credentials() url = read_release_obj.prepare_github_repository_url() # Check if username and password exist if read_release_obj.username and read_release_obj.password: try: github_repo = read_release_obj.github_authunticate(read_release_obj.username, read_release_obj.password, url) read_release_obj.set_google_sheet_credentials(read_release_obj.sheet) read_release_obj.read_all_releases_names(github_repo, read_release_obj.release_name, read_release_obj.sheet) except BadCredentialsException: print ('Bad credentials. Try again!') else: print ('Github credentials are required!') if __name__ == "__main__": main() </code></pre>
[]
[ { "body": "<p>You are using classes wrong. Your first wrong statement is actually your first comment <code># Instances vairables</code>. Variables which you set at the class scope are class variables, they are in general shared by all instances of the class. Here this distinction does not really matter since you only ever have one instance of the class and when you do change them in the instance you override them with a new string instead of mutating the object there (which is impossible since strings are immutable in Python). But if you ever write a class where these objects are mutable (a <code>list</code> for example) you are in for a hell of a surprise:</p>\n\n<pre><code>class A:\n x = []\n\na1 = A()\na2 = A()\na1.x.append(2)\nprint(a2.x)\n# [2]\n</code></pre>\n\n<p>The next thing where you are using classes wrong is when calling the class methods. The usual way is this:</p>\n\n<pre><code>class A:\n def some_method(self, *args):\n print(\"some_method\", *args)\n\n def other_method(self):\n self.some_method(1)\n</code></pre>\n\n<p>Note that in the second method I did not write <code>A.some_method(self, 1)</code>. <code>self.some_method</code> is automatically expanded to that (and a lot more readable).</p>\n\n<hr>\n\n<p>And finally, I would question if this needs to be a class at all. Almost all parameters are explicitly passed to the methods anyways and the only state you keep around is <code>self.sheet</code>. But you might as well just keep that in a variable.</p>\n\n<p>Without a class your code could look like this:</p>\n\n<pre><code>import getpass\nimport gspread\nfrom github import Github, BadCredentialsException\nfrom oauth2client.service_account import ServiceAccountCredentials\n\n\ndef get_user_credentials():\n while True:\n username = raw_input(\"Github username: \")\n password = getpass.getpass(prompt='Github password: ')\n if username and password:\n return username, password\n print 'Github credentials are required!'\n\n\ndef get_repo(username, password, repository_name):\n try:\n github_account = Github(username, password)\n return github_account.get_repo('someuseraccount/' + repository_name)\n except BadCredentialsException:\n print 'Bad credentials. Try again!'\n raise\n\ndef get_releases(repository, release_name):\n releases = [release\n for release in repository.get_releases()\n if release.title.encode('utf-8') == release_name]\n if not releases:\n raise RuntimeError(\"'Release Name' is wrong!, Please try again with correct 'release name'\")\n return releases\n\ndef get_issues(release):\n tag_name = release.tag_name.encode('utf-8')\n for line in release.body.splitlines():\n line = line.encode('utf-8')\n if line.startswith('- [FIX]'):\n yield \"YES\", tag_name, line[7:]\n elif line.startswith('-' * 7):\n yield \"NO\", tag_name, line[7:]\n\ndef get_sheet(file_name):\n scope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\n google_credentials = ServiceAccountCredentials.from_json_keyfile_name(\n 'test.json', scope)\n f = gspread.authorize(google_credentials)\n sheet = f.open(file_name).sheet1\n # Add headers to the sheet\n sheet.update_acell('A1', 'Client Version')\n sheet.update_acell('B1', 'Version Reference for Internal Purposes')\n sheet.update_acell('C1', 'Proposed Change (Expected Functional Behavior)')\n sheet.update_acell('D1', 'Bug Fix?')\n sheet.resize(1)\n return sheet\n\ndef write_issues_to_sheet(sheet, issues):\n for fixed, tag_name, line in issues:\n sheet.append_row([tag_name, tag_name, line, fixed])\n print \"Release inserted to the Google sheet.\"\n\ndef main():\n username, password = get_user_credentials()\n repository_name = raw_input(\"Repository name: \")\n repo = get_repo(username, password, repository_name)\n sheet = get_sheet('Copy_of_MOD_Change_Worklog_Tracker.xlsx')\n\n release_name = raw_input('Release name: ')\n for release in get_releases(repo, release_name):\n write_issues_to_sheet(sheet, get_issues(release))\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>I also moved around a bit where stuff is being done in order to decouple the functions from each other. Now they are all being called from the <code>main</code> function which handles passing them the right parameters. This drastically reduced the number of parameters needed by the functions, since now they don't need to take the parameters of the functions they are going to call inside.</p>\n\n<p>I also used <code>sheet.append_row</code> which appends a row after the last row. For this to work correctly we must first set the last row to be the first one (because otherwise it will add rows starting at row 1000). For this I used <code>sheet.resize</code>. You might have to do <code>sheet.resize(2)</code> instead of <code>1</code> if it overrides your header, can't test this ATM.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T09:36:18.450", "Id": "411077", "Score": "0", "body": "Thanks for your nice guides and solution. Would you please tell more about impact of your changes and solution on performance of script?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T10:09:56.740", "Id": "411080", "Score": "0", "body": "@IbrahimRahimi The script will probably not get significantly faster by changing this. It will just be easier to read and maintain. It should also be easier to figure out where the actual bottle neck is by profiling how long each function takes to execute." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T09:19:11.237", "Id": "212525", "ParentId": "212518", "Score": "3" } } ]
{ "AcceptedAnswerId": "212525", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T07:35:55.027", "Id": "212518", "Score": "3", "Tags": [ "python", "performance", "beginner" ], "Title": "Reading releases details from github and writing to google sheet file" }
212518
<p>I am currently developing a Task Scheduler to run different methods at a certain time. In general it is a Spring-boot application an task execution/scheduling is just a very tiny piece of the whole project. My idea is to define several Runnables that execute depending on a CronTrigger. In the Runnable I create an object <code>Job</code> that holds information about the current task, like <code>startTime</code>, <code>status</code> and others.</p> <pre><code>public class Job { private Long id; private Class clazz; private Date startTime; private boolean status; private String parameter; private CronTrigger cronTrigger; private String exception; Job(long id, Class&lt;?&gt; clazz, boolean status, Date startTime, String parameter, CronTrigger cronTrigger, String exception) { this.id = id; this.clazz = clazz; this.startTime = startTime; this.status = status; this.parameter = parameter; this.cronTrigger = cronTrigger; this.exception = exception; } //Getter, Setter, toString() } </code></pre> <p>To represent which thread is currently running/waiting I add it to <code>ConcurrentHashMap&lt;Long, Job&gt;</code> there are two, one for sleeping Thread and one for running Threads. There are also two methods <code>addTask(Long task, Job job)</code> and <code>removeTask(Long task, Job job)</code> that put/remove Jobs to/from the two ConcurrentHashMaps and set <code>status</code> of an <code>Job</code>.</p> <pre><code>private ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); private HashMap&lt;Long, CronTrigger&gt; cronTriggers = new HashMap&lt;&gt;(); private ScheduledFuture&lt;?&gt; task0; private ScheduledFuture&lt;?&gt; task1; private ScheduledFuture&lt;?&gt; task2; private ScheduledFuture&lt;?&gt; task3; private ScheduledFuture&lt;?&gt; task4; private ScheduledFuture&lt;?&gt; task5; private ScheduledFuture&lt;?&gt; task6; private ScheduledFuture&lt;?&gt; task7; private ScheduledFuture&lt;?&gt; task8; private ScheduledFuture&lt;?&gt; task9; private final ConcurrentHashMap&lt;Long, Job&gt; scheduledTasksRunning = new ConcurrentHashMap&lt;&gt;(); private final ConcurrentHashMap&lt;Long, Job&gt; scheduledTasksSleeping = new ConcurrentHashMap&lt;&gt;(); private Job selectedScheduledJob; private int POOL_SIZE = 10; @Bean public ThreadPoolTaskScheduler taskScheduler() { this.scheduler.setPoolSize(POOL_SIZE); this.scheduler.initialize(); for (int i = 0; i &lt; POOL_SIZE; i++){ cronTriggers.put(((long) i), new CronTrigger("1 1 1 1 * *")); } for (int i = 0; i &lt; POOL_SIZE; i++){ Job job = new Job((long) i, getClass(), false, new Date(),null, cronTriggers.get((long) i), null); scheduledTasksSleeping.put(((long) i), job); } task0 = scheduler.schedule(new Task0(), cronTriggers.get(0L)); task1 = scheduler.schedule(new Task1(), cronTriggers.get(1L)); task2 = scheduler.schedule(new Task2(), cronTriggers.get(2L)); task3 = scheduler.schedule(new Task3(), cronTriggers.get(3L)); task4 = scheduler.schedule(new Task4(), cronTriggers.get(4L)); task5 = scheduler.schedule(new Task5(), cronTriggers.get(5L)); task6 = scheduler.schedule(new Task6(), cronTriggers.get(6L)); task7 = scheduler.schedule(new Task7(), cronTriggers.get(7L)); task8 = scheduler.schedule(new Task8(), cronTriggers.get(8L)); task9 = scheduler.schedule(new Task9(), cronTriggers.get(9L)); return scheduler; } public class Task0 implements Runnable { public void run() { Long id = 0L; Job job = new Job(id, getClass(), true, new Date(), null, cronTriggers.get(id), null); addTask(id, job); try { Thread.sleep(10000); } catch (InterruptedException e) { job.setException(e.toString()); e.printStackTrace(); } removeTask(id, job); } } public class Task1 implements Runnable { public void run() { Long id = 1L; Job job = new Job(id, getClass(), true, new Date(), null, cronTriggers.get(id), null); addTask(id, job); try { Thread.sleep(10000); } catch (InterruptedException e) { job.setException(e.toString()); e.printStackTrace(); } removeTask(id, job); } } // 8 other Runnables /** * manually stop a running Job via GUI * */ public void taskCancel(){ Long id = selectedScheduledJob.getId(); switch (toIntExact(id)){ case 0: task0.cancel(true); break; case 1: task1.cancel(true); break; // 8 other cases for each Thread } } /** * manually start a selected Job via GUI and force it to trigger at next * scheduled time */ public void taskStart(){ Long id = selectedScheduledJob.getId(); switch (toIntExact(id)){ case 0: scheduler.schedule(new Task0(), new Date()); scheduler.schedule(new Task0(), cronTriggers.get(id)); break; case 1: scheduler.schedule(new Task1(), new Date()); scheduler.schedule(new Task1(), cronTriggers.get(id)); break; // 8 other cases for each Thread } } private synchronized void addTask(Long task, Job job) { scheduledTasksSleeping.remove(task); scheduledTasksRunning.put(task, job); } private synchronized void removeTask(Long task, Job job) { job.setStatus(false); scheduledTasksRunning.remove(task); scheduledTasksSleeping.put(task, job); } // Getter and Setter for GUI </code></pre> <p>I know however that the definition of <code>ScheduledFuture&lt;?&gt; taskX;</code> is not that good and I tend to use a <code>ArrayList</code> in future.</p> <p>Some things I am interested in:</p> <ul> <li>Is there anything I did that is blatantly the wrong way of doing it?</li> <li>Do you see any way to improve the performance or speed?</li> <li>Is it thread-safe?</li> </ul>
[]
[ { "body": "<p>You've already mentioned your definition of the <code>ScheduledFuture&lt;?&gt;</code> instances could be improved with an <code>ArrayList</code>. </p>\n\n<pre><code>for (long i=0; i&lt;9; i++) {\n tasks[i] = scheduler.schedule(new Task(i), cronTriggers.get(i));\n}\n</code></pre>\n\n<p>Instead of 10 class definitions for the tasks you could set the <code>id</code> for your task in the constructor as you define the array of tasks. This will make your code more <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> and easier to maintain.</p>\n\n<pre><code>public class Task implements Runnable { \n private long id;\n public Task(long id) {\n this.id = id;\n }\n\n public void run() {\n Job job = new Job(\n id, getClass(), true, new Date(), null, cronTriggers.get(this.id), null);\n addTask(this.id, job);\n try {\n Thread.sleep(10000);\n } catch (InterruptedException e) {\n job.setException(e.toString());\n e.printStackTrace();\n }\n removeTask(this.id, job);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T00:47:59.820", "Id": "212595", "ParentId": "212519", "Score": "0" } } ]
{ "AcceptedAnswerId": "212595", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T07:50:42.890", "Id": "212519", "Score": "1", "Tags": [ "java", "thread-safety", "spring" ], "Title": "Spring TaskScheduling with HashMap" }
212519
<p>I've following code that insert single row in <code>if (rows == 1) {</code> part and inside loop it is batch insert.<br> So I'm thinking to skip single insert and have it in batch insert code. </p> <pre><code>private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { int rows = jTable.getRowCount(); if (rows == 1) { String itemName = (String) jTable.getValueAt(0, 0); int itemQty = (int) jTable.getValueAt(0, 1); Double itemPrice = (Double) jTable.getValueAt(0, 2); Items items = new Items(); items.setName(itemName); items.setPrice(itemPrice); items.setQty(itemQty); items.setTransactionNumber(manager.getTransNo()); manager.saveItems(items); </code></pre> <p>Above part insert single record if there's only one row in a <code>JTable</code> Below in <code>else</code> part inside <code>loop</code> performed batch insert if <code>JTable</code> contains more than one row. </p> <pre><code> } else { for (int i = 0; i &lt; 1; i++) { String itemName = (String) jTable.getValueAt(i, 0); int itemQty = (int) jTable.getValueAt(i, 1); Double itemPrice = (Double) jTable.getValueAt(i, 2); Items items = new Items(); items.setName(itemName); items.setPrice(itemPrice); items.setQty(itemQty); items.setTransactionNumber(manager.getTransNo()); int max = items.getTransactionNumber(); manager.saveItems(items); </code></pre> <p>And here in a second loop it does perform insertion after first row in a <code>JTable</code> when <code>int i = 1</code>. </p> <pre><code>for (i = 1; i &lt; rows; i++) { String itemsName = (String) jTable.getValueAt(i, 0); int itemsQty = (int) jTable.getValueAt(i, 1); Double itemsPrice = (Double) jTable.getValueAt(i, 2); items.setName(itemsName); items.setPrice(itemsPrice); items.setQty(itemsQty); items.setTransactionNumber(max); manager.saveItems(items); } } } } </code></pre> <p>I was thinking to save all rows without considering is either only one row or more.<br> So my modified version would not have <code>if (rows == 1) {....}</code> part<br> Will have only <code>for (int i = 0; i &lt;= 0; i++) {</code><br> So if there will have only one row in a JTable would this modified version can be cause of lower performance?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T09:28:35.317", "Id": "411075", "Score": "1", "body": "No, absolutely no MCVEs on Code Review. We need to see your real code and a description of what it does (and why). Otherwise we can't say much useful things about it. It's all explained in the link provided. In this case, a usage example could be a useful part of the description." } ]
[ { "body": "<p>Short answer to your question: No it's the same performance wise.</p>\n\n<hr>\n\n<p>Full review:</p>\n\n<p>My first concern with your code is the double for loop that uses the same looping variable <code>i</code>. This makes it harder to understand when you see an <code>i</code> inside the inner for loop. </p>\n\n<p>My other major concern is that the only difference between the code before the inner for loop and the code inside the inner loop is setting the variable <code>max</code> which I had no idea what it should be at first sight. Let's start by renaming that to <code>transactionNumber</code>. And since this is independent of the loop itself let's initialise that from the manager right above the loops instead:</p>\n\n<pre><code>int transactionNumber = manager.getTransNo();\nfor (int i = 0; i &lt; 1; i++) {\n String itemName = (String) jTable.getValueAt(i, 0);\n int itemQty = (int) jTable.getValueAt(i, 1);\n Double itemPrice = (Double) jTable.getValueAt(i, 2);\n Items items = new Items();\n items.setName(itemName);\n items.setPrice(itemPrice);\n items.setQty(itemQty);\n items.setTransactionNumber(transactionNumber);\n manager.saveItems(items);\n\n for (i = 1; i &lt; rows; i++) {\n String itemsName = (String) jTable.getValueAt(i, 0);\n int itemsQty = (int) jTable.getValueAt(i, 1);\n Double itemsPrice = (Double) jTable.getValueAt(i, 2);\n\n items.setName(itemsName);\n items.setPrice(itemsPrice);\n items.setQty(itemsQty);\n items.setTransactionNumber(transactionNumber);\n manager.saveItems(items);\n }\n}\n</code></pre>\n\n<p>Now with a closer look there's a second difference. You only instantiate <code>items</code> once and overwrite that with the setters. I don't think this is a good idea. You should probably create a new items object each time with it's own name, price, quantity and save that independent of any previous values. This means we can just combine the 2 for loops into 1 like so:</p>\n\n<pre><code>int transactionNumber = manager.getTransNo();\nfor (int i = 0; i &lt; rows; i++) {\n String itemName = (String) jTable.getValueAt(i, 0);\n int itemQty = (int) jTable.getValueAt(i, 1);\n Double itemPrice = (Double) jTable.getValueAt(i, 2);\n Items items = new Items();\n items.setName(itemName);\n items.setPrice(itemPrice);\n items.setQty(itemQty);\n items.setTransactionNumber(transactionNumber);\n manager.saveItems(items);\n}\n</code></pre>\n\n<p>If you now take a close look at what would happen if you only had 1 row you can see that the code inside the loop gets executed exactly 1 time with the <code>i</code> replaced by a <code>0</code>. This is exactly the same code you have inside your <code>if(rows == 1)</code> block so you can remove that check and only keep the for loop.</p>\n\n<p>Depending on how the Items are used in the rest of your code I also strongly suggest to remove the setters and pass any needed parameters with the constructor instead. This results in the following implementation of the entire method:</p>\n\n<pre><code>private void jButton1ActionPerformed (java.awt.event.ActionEvent evt){\n int transactionNumber = manager.getTransNo();\n for (int i = 0; i &lt; rows; i++) {\n String itemName = (String) jTable.getValueAt(i, 0);\n int itemQty = (int) jTable.getValueAt(i, 1);\n Double itemPrice = (Double) jTable.getValueAt(i, 2);\n Items items = new Items(transactionNumber, itemName, itemPrice, itemQty);\n manager.saveItems(items);\n }\n}\n</code></pre>\n\n<p>The only improvement you should consider is to rename <code>jTable</code> to something more meaningful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T10:50:33.433", "Id": "411086", "Score": "0", "body": "Thanks a lot for your efforts. I was thinking it's big deal with either original code or modified code. I think there's no need of second loop if I would remove check I had cause of rest of table rows. I was thinking If loop is burden for single row. Thanks a lot." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T10:27:13.150", "Id": "212529", "ParentId": "212521", "Score": "1" } } ]
{ "AcceptedAnswerId": "212529", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T08:21:36.707", "Id": "212521", "Score": "1", "Tags": [ "java" ], "Title": "Performing batch insertion for a single row" }
212521
<p>I have created a simple version of the classic game Hunt the Wumpus in C++. The rules for the game can be found <a href="//codegolf.stackexchange.com/q/26128">on Code Golf SE</a>.</p> <p>The rules of the game are (from PPCG):</p> <blockquote> <p><em>The player starts in a random room on an icosahedral map (thus there are 20 rooms in total, connected to each other like the faces of an icosahedron, and every room has exactly three exits).</em></p> <p><em>The wumpus starts in a randomly selected different room. The wumpus stinks, and its odor can be detected in any of the three rooms adjacent to its location, though the direction of the odor is impossible for the player to determine. The game reports only &quot;you smell a wumpus.&quot;</em></p> <p><em>The player carries a bow and an infinite number of arrows, which he may shoot at any time into the room in front of him. If the wumpus is in that room, it dies and the player wins. If the wumpus was not in that room, it is startled and moves randomly into any of the three rooms connected to its current location.</em></p> <p><em>One, randomly selected room (guaranteed not to be the room in which the player starts) contains a bottomless pit. If the player is in any room adjacent to the pit, he feels a breeze, but gets no clue as to which door the breeze came from. If he walks into the room with the pit, he dies and wumpus wins. The wumpus is unaffected by the pit.</em></p> <p><em>If the player walks into the wumpus's room, or if the wumpus walks into the player's room, the wumpus wins.</em></p> </blockquote> <p>This is the first non-trivial program I have created and would like to know what I could have done better.</p> <p>Does my code follow the best practices? Is there anything I can do to clean it up? Can there be any improvements?</p> <pre><code>#include&lt;iostream&gt; #include&lt;vector&gt; #include&lt;algorithm&gt; #include&lt;limits&gt; constexpr int ROOMS = 20; constexpr int BATS = 3; constexpr int PITS = 3; constexpr int END_GAME = -1; struct Room { std::vector&lt;int&gt;adjRooms{std::vector&lt;int&gt;(3)}; bool player{false}; bool bat{false}; bool wump{false}; bool pit{false}; }; class Player { std::vector&lt;int&gt; adjRooms{std::vector&lt;int&gt;(3)}; int currRoom; void setAdjRooms(); public: void setCurrRoom(int r){currRoom = r; setAdjRooms();} int room() const {return currRoom;} int getAdj(int i) const {return adjRooms[i];} }; void Player::setAdjRooms() { int t = 2+2*(currRoom&amp;1); adjRooms[0] = ROOMS-1-currRoom; adjRooms[1] = (currRoom+t)%ROOMS; adjRooms[2] = (currRoom-t+20)%ROOMS; } class Map { std::vector&lt;Room&gt; cave{std::vector&lt;Room&gt;(20)}; std::vector&lt;int&gt; vacant; //vector to keep track of empty rooms Player p; void addWump(); void addBats(); void addPits(); void addPlayer(); void reportState(); int input(); int movePlayer(int); int shoot(int target); void batEncounter(); int moveWump(); public: void init(); void play(); void printState(); //Only for debugging. Not part of the game. }; void Map::addPlayer() //spawn player { int r = rand()%vacant.size(); cave[vacant[r]].player = true; p.setCurrRoom(vacant[r]); //std::cout&lt;&lt;&quot;Player in room &quot;&lt;&lt;vacant[r]&lt;&lt;std::endl; vacant.erase(vacant.begin()+r); //no enemies should spawn adjacent to player for(int i = 0; i &lt; 3; ++i) vacant.erase(std::find(vacant.begin(),vacant.end(),p.getAdj(i))); } void Map::addWump() //spawns the wumpus in a random room { int r = rand()%vacant.size(); cave[vacant[r]].wump = true; //std::cout&lt;&lt;&quot;Wumpus in room &quot;&lt;&lt;vacant[r]&lt;&lt;std::endl; vacant.erase(vacant.begin()+r); //remove vacancy } void Map::addBats() //spawns bats { for(int i = 0; i &lt; BATS; ++i){ int r = rand()%vacant.size(); cave[vacant[r]].bat = true; //std::cout&lt;&lt;&quot;Bat in room &quot;&lt;&lt;vacant[r]&lt;&lt;std::endl; vacant.erase(vacant.begin()+r); } } void Map::addPits() //place pits { for(int i = 0; i &lt; PITS; ++i){ int r = rand()%vacant.size(); cave[vacant[r]].pit = true; //std::cout&lt;&lt;&quot;Pit in room &quot;&lt;&lt;vacant[r]&lt;&lt;std::endl; vacant.erase(vacant.begin()+r); } } void Map::printState() //for debugging { for(int i = 0; i &lt; ROOMS; ++i){ std::cout &lt;&lt; &quot;Room #&quot; &lt;&lt; i &lt;&lt; &quot;:&quot; &lt;&lt; std::endl; std::cout &lt;&lt; &quot;\tWumpus -&gt; &quot; &lt;&lt; ((cave[i].wump)?&quot;yes&quot;:&quot;no&quot;) &lt;&lt; std::endl; std::cout &lt;&lt; &quot;\tBat -&gt; &quot; &lt;&lt; ((cave[i].bat)?&quot;yes&quot;:&quot;no&quot;) &lt;&lt; std::endl; std::cout &lt;&lt; &quot;\tPit -&gt; &quot; &lt;&lt; ((cave[i].pit)?&quot;yes&quot;:&quot;no&quot;) &lt;&lt; std::endl; std::cout &lt;&lt; &quot;\tPlayer -&gt; &quot; &lt;&lt; ((cave[i].player)?&quot;yes&quot;:&quot;no&quot;) &lt;&lt; std::endl; std::cout &lt;&lt; &quot;\tAdjacent Rooms -&gt; &quot; &lt;&lt;(cave[i].adjRooms[0])&lt;&lt;&quot;, &quot; &lt;&lt;(cave[i].adjRooms[1])&lt;&lt;&quot;, &quot;&lt;&lt;cave[i].adjRooms[2]&lt;&lt;std::endl; std::cout &lt;&lt; std::endl; } } void Map::reportState() { std::cout &lt;&lt; &quot;You are in room &quot; &lt;&lt; p.room() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Adjacent rooms are &quot; &lt;&lt; p.getAdj(0) &lt;&lt;&quot;, &quot;&lt;&lt;p.getAdj(1) &lt;&lt;&quot;, &quot;&lt;&lt;p.getAdj(2)&lt;&lt;std::endl; if(cave[p.getAdj(0)].bat || cave[p.getAdj(1)].bat || cave[p.getAdj(2)].bat) std::cout &lt;&lt; &quot;I hear a bat.&quot; &lt;&lt; std::endl; if(cave[p.getAdj(0)].pit || cave[p.getAdj(1)].pit || cave[p.getAdj(2)].pit) std::cout &lt;&lt; &quot;I feel a draft.&quot; &lt;&lt; std::endl; if(cave[p.getAdj(0)].wump || cave[p.getAdj(1)].wump || cave[p.getAdj(2)].wump) std::cout &lt;&lt; &quot;I smell the wumpus.&quot; &lt;&lt; std::endl; } int Map::movePlayer(int pos) { if(pos != p.getAdj(0) &amp;&amp; pos != p.getAdj(1) &amp;&amp; pos != p.getAdj(2)){ std::cout &lt;&lt; &quot;Invalid choice. Please move to an ADJACENT room.&quot; &lt;&lt; std::endl; return 0; } cave[p.room()].player = false; cave[pos].player = true; vacant.push_back(p.room()); p.setCurrRoom(pos); if(cave[p.room()].wump){ std::cout &lt;&lt; &quot;The Wumpus got you! YOU LOSE.&quot; &lt;&lt; std::endl; return END_GAME; } if(cave[p.room()].pit){ std::cout &lt;&lt; &quot;You fell into a bottomless pit! YOU LOSE.&quot; &lt;&lt; std::endl; return END_GAME; } if(cave[p.room()].bat){ std::cout &lt;&lt; &quot;A giant bat takes you to another room!&quot; &lt;&lt; std::endl; batEncounter(); return 0; } } int Map::moveWump() //move wumpus to a random adjacent room { int r = rand()%3; int pos = 0; for(; !(cave[pos].wump); ++pos); //get the room that contains the wumpus cave[pos].wump = false; if((cave[pos].wump &amp;&amp; !(cave[pos].bat)) || (cave[pos].wump &amp;&amp; !(cave[pos].pit))) vacant.push_back(pos); cave[cave[pos].adjRooms[r]].wump = true; if(cave[cave[pos].adjRooms[r]].player){ std::cout &lt;&lt; &quot;The Wumpus got you! YOU LOSE.&quot; &lt;&lt; std::endl; return END_GAME; } return 0; } int Map::shoot(int target) { if(target != p.getAdj(0) &amp;&amp; target != p.getAdj(1) &amp;&amp; target != p.getAdj(2)){ std::cout &lt;&lt; &quot;Invalid choice. Please target an ADJACENT room.&quot; &lt;&lt; std::endl; return 0; } if(cave[target].wump){ std::cout &lt;&lt; &quot;You killed the Wumpus! YOU WIN!&quot; &lt;&lt; std::endl; return END_GAME; } else if(cave[p.getAdj(0)].wump || cave[p.getAdj(1)].wump || cave[p.getAdj(2)].wump) return moveWump(); } void Map::batEncounter() { int r = rand()%vacant.size(); cave[p.room()].player = false; vacant.push_back(p.room()); cave[vacant[r]].player = true; p.setCurrRoom(vacant[r]); vacant.erase(vacant.begin()+r); } void Map::init() //set up map //place player, bats, pits and the wumpus { //generate the dodecahedral cave for(int i = 0; i &lt; ROOMS; ++i){ int t = 2+2*(i&amp;1); cave[i].adjRooms[0] = ROOMS-1-i; cave[i].adjRooms[1] = (i+t)%ROOMS; cave[i].adjRooms[2] = (i-t+20)%ROOMS; vacant.push_back(i); } //add entities addPlayer(); addWump(); addBats(); addPits(); //restore vacant rooms adjacent to player for(int i = 0; i &lt; 3; ++i) vacant.push_back(p.getAdj(i)); } void Map::play() { reportState(); while(input() != END_GAME){ reportState(); } } int Map::input() { char c = 0; int r = -1; std::cout &lt;&lt; &quot;Type mXX(sXX) to move(shoot) to(at) room XX.&quot; &lt;&lt; std::endl; while(1){ std::cout &lt;&lt; &quot;Enter command: &quot;; if(std::cin &gt;&gt; c &gt;&gt; r) { break; } else if(std::cin.fail() || (c != 'm' &amp;&amp; c != 's')){ std::cin.clear(); std::cin.ignore(std::numeric_limits&lt;int&gt;::max(),'\n'); std::cout &lt;&lt; &quot;Invalid input. Type mXX(sXX) to move(shoot) to(at) room XX.&quot; &lt;&lt; std::endl; } } return (c == 'm') ? movePlayer(r) : shoot(r); } int main() { srand(unsigned(time(0))); Map game; game.init(); game.play(); //game.printState(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T19:41:19.007", "Id": "411200", "Score": "1", "body": "Your `Map::shoot` function doesn't fit the rules: the Wumpus only moves if he was adjacent to the player. Per the spec, the Wumpus should move unless he was shot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T11:45:09.447", "Id": "411280", "Score": "0", "body": "Oh shoot! I overlooked that detail. I'll have to get on that when I have time." } ]
[ { "body": "<p>I think your solution is a good start for a first bigger programming task. I'd probably structure the program a little bit differently but I'm not sure if this required or even good. For the size of the problem the layout really is appropriate (meaning exactly right).</p>\n\n<p>I've found some stuff nevertheless. Here you go (simply search for the code parts):</p>\n\n<p><strong>Bugs</strong></p>\n\n<ul>\n<li>in <code>if((cave[pos].wump &amp;&amp; !(cave[pos].bat)) || (cave[pos].wump &amp;&amp; !(cave[pos].pit)))\n</code> the expression <code>cave[pos].wump</code> is always false, hence the line <code>vacant.push_back(pos);</code> is never run</li>\n<li>restoring the vacant rooms in <code>Map::Init()</code> does not consider non-player entities. If the player spawns by accident next to wumpus, the room will be considered vacant by the game.</li>\n<li>wrong input in <code>Map::input()</code> will lead to shoot being called. The <code>input</code> method should only return if the input is indeed acceptable. Ideally <code>input</code> returns some abstract command structure or is renamed to something like <code>handleInput()</code>.</li>\n</ul>\n\n<p><strong>Possible Bugs</strong></p>\n\n<ul>\n<li>in <code>for(; !(cave[pos].wump); ++pos);</code> add a check for the end of <code>cave</code></li>\n<li><code>Map::MovePlayer()</code> and <code>Map::shoot()</code> contain code paths that may not always return a value </li>\n</ul>\n\n<p><strong>Style Improvements</strong></p>\n\n<ul>\n<li>use same name for a member in all locations, e.g. <code>setCurrRoom()</code> and <code>room()</code>. Note that <code>room()</code> offers enough information and is much shorter than <code>currRoom</code></li>\n<li>use <code>ROOMS</code> only for initialization of the cave, stick to <code>cave.size()</code> in all other places</li>\n<li>it makes sense to somehow mark the member variables to make them distinguishable from local variables and globals, prepending <code>m_</code> to the variable name is common: <code>vacant</code> -> <code>m_vacant</code>.</li>\n<li>add more whitespace: newlines and spaces can be used to show parts of a function that belong logically together</li>\n<li>You can reduce <code>!(cave[pos].wump)</code> to <code>!cave[pos].wump</code>.</li>\n</ul>\n\n<p><strong>General Hints</strong></p>\n\n<ul>\n<li>you can hide debugging code behind a compiler switch:</li>\n</ul>\n\n<pre><code>#ifdef DEBUG\ngame.printState();\n#endif\n</code></pre>\n\n<p>If you compile with <code>-DDEBUG</code> you will generate debug output</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T15:25:48.163", "Id": "411142", "Score": "0", "body": "Thanks a lot for the valuable comments and pointing out bugs which could be game-breaking if not fixed. However, I don't see why the second point you mention is a bug. The Player never spawns next to the wumpus. Instead, the wumpus never spawns next to the player, so to me, the rooms being restored are indeed vacant. Please correct me if I am wrong. Thanks again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T15:36:36.743", "Id": "411143", "Score": "1", "body": "Sorry, didn't see that you're removing adjacent rooms from the vacant list in `addPlayer()`. You should definitely put the removal of the rooms closer to the reinsertion of them. In the current state it is very easy to introduce a bug if you change `addPlayer()` and don't remember that you need to change something else in `init()` as well. Generally speaking: put things that belong together in the same entity (here: function)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T12:50:52.440", "Id": "212540", "ParentId": "212523", "Score": "7" } }, { "body": "<ul>\n<li><p><code>#include &lt;ctime&gt;</code> (for <code>time()</code>).</p></li>\n<li><p>The C++ versions of standard functions are declared in the <code>std</code> namespace, not the global namespace, so we should use <code>std::srand</code> and <code>std::time</code>.</p></li>\n<li><p>We can use the C++11 random number generation facilities in <code>&lt;random&gt;</code>, rather than <code>srand</code> and <code>rand</code> to generate random numbers. e.g.</p>\n\n<pre><code>std::mt19937 rng(std::random_device()()); // seed the random number generator (do this once)\n\n...\nstd::uniform_int_distribution&lt;int&gt; dist(0, vacant.size() - 1);\nint r = dist(rng); // generate an int with the given distribution\n</code></pre></li>\n<li><p><code>int</code> is not an appropriate type to store room indices. We should use the index type of the container (i.e. <code>std::vector&lt;Room&gt;::size_type</code>, which is <code>std::size_t</code>), since that covers the correct range of values.</p></li>\n<li><p>Constant variables (<code>ROOMS</code>, <code>BATS</code>, etc.) are better than <code>#defines</code>, but there's no reason these can't be normal member variables (e.g. in the <code>Map</code> class). This would, for example, give us the flexibility to start a new game with different number of rooms or pits.</p></li>\n<li><p>The <code>Player</code> stores the index of the current room. Each <code>Room</code> stores the adjacent room indices. There is therefore no reason for the <code>Player</code> class to store adjacent room indices as well. We can get these from the <code>Map</code> instead.</p></li>\n<li><p><code>warning C4715: 'Map::movePlayer': not all control paths return a value</code>, <code>warning C4715: 'Map::shoot': not all control paths return a value</code> - we should fix that!</p></li>\n</ul>\n\n<hr>\n\n<p><code>Map</code>:</p>\n\n<ul>\n<li><p><code>Map</code> is a slightly misleading name, since this class largely handles game logic. Perhaps the game logic could be split into a <code>Game</code> class, or the class itself renamed <code>Game</code>.</p></li>\n<li><p>Use the <code>Map</code> constructor to do initialization, removing the need to call a separate <code>init</code> function.</p></li>\n<li><p>One would expect the vector of <code>Room</code>s in <code>Map</code> to be called <code>rooms</code>, not <code>cave</code>.</p></li>\n<li><p>Since the bats, wumpus, and pit can all coexist, the <code>Map::add*</code> functions may be slightly wrong - we only need to place a bat in a room with no other bats.</p></li>\n<li><p>We should probably check that we don't run out of vacant rooms in which to place things.</p></li>\n<li><p><code>Map::input</code> returns an integer value. However, we're not using it as a number, but to represent game state. C++ has <code>enum</code>s for this purpose, e.g. <code>enum class MoveResult { END_GAME, CONTINUE }</code>, and we should return one of these instead.</p></li>\n</ul>\n\n<hr>\n\n<p>bit-flags:</p>\n\n<ul>\n<li><p>There is some duplication of code when referring to the <code>.bat</code>, <code>.pit</code>, <code>.wump</code> members of <code>Room</code>. It would be nice to remove this, and abstract some more functionality (e.g. checking for an adjacent feature) into a single function. This would be easier if we used bit-flags for the room contents. e.g.:</p>\n\n<pre><code>enum RoomFeatures\n{\n Player = 1 &lt;&lt; 0,\n Bat = 1 &lt;&lt; 1,\n Pit = 1 &lt;&lt; 2,\n Wumpus = 1 &lt;&lt; 3,\n};\n\nstruct Room\n{\n ...\n RoomFeatures features;\n};\n\n...\n\nroom.features |= RoomFeatures::Bat; // add bat to room\nif (room.features &amp; RoomFeatures::Pit) ... // test for pit\nroom.features &amp;= ~RoomFeatures::Wumpus // remove wumpus from room\n</code></pre>\n\n<p>While the bitwise operators are admittedly rather awkward, we could wrap this in a neat interface, which lets us do something like this:</p>\n\n<pre><code>bool Map::isAdjacentTo(int roomIndex, RoomFeatures feature) const\n{\n for (auto i : cave[roomIndex].adjRooms)\n if (cave[i].contains(feature)) // `bool Room::contains() const` tests the bit-flag\n return true;\n\n return false;\n}\n\n...\n\n// e.g. in reportState\nif (isAdjacentTo(p.room(), RoomFeatures::Bat))\n std::cout ... ;\n</code></pre></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><p>It would be nice to separate the input and output from the game logic:</p>\n\n<ul>\n<li><p>At the moment we output messages about the player losing or winning in <code>Map::shoot</code>, <code>Map::moveWump</code>, and <code>Map::movePlayer</code> .</p></li>\n<li><p><code>movePlayer()</code> and <code>shoot()</code> are called from the input function, rather than as part of the main loop as one might expect.</p></li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T12:57:52.413", "Id": "212544", "ParentId": "212523", "Score": "7" } } ]
{ "AcceptedAnswerId": "212544", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T08:31:34.313", "Id": "212523", "Score": "9", "Tags": [ "c++", "object-oriented", "game" ], "Title": "Hunt the Wumpus game in C++" }
212523
<p>I'm new to programming and even more new to C++. Anyway, I started to watch and read some tutorials and resources I found on the web.</p> <p>I created this program to offer the user a coffee, expecting an answer of <code>O</code> (for "oui") or <code>N</code> (for "non"):</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; int main() { char cafe('G'); //Initialisation de la variable cafe while (cafe != 'O' &amp;&amp; cafe != 'N' ) // Boucle: tant que l'utilsateur ne répond pas par O ou N, ça recommence. { cout &lt;&lt; "Veux-tu du café ? O/N" &lt;&lt; endl; cin &gt;&gt; cafe; // input de l'utilisateur. if (cafe != 'O' &amp;&amp; cafe != 'N') { cout &lt;&lt; "Merci de répondre par O ou par N." &lt;&lt; endl; } else if(cafe == 'O') { cout &lt;&lt; "Regalez-vous !" &lt;&lt; endl; } else if(cafe == 'N') { cout &lt;&lt; "Tant pis, a la prochaine !" &lt;&lt; endl; } } return 0; } </code></pre> <p>One thing I dislike about it is that if the user enters a nonsense string like <code>HJEHUEUHUEOOEL</code>, then we'll get a prompt for each of those characters until <code>O</code> or <code>N</code> is found.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T08:51:31.047", "Id": "411065", "Score": "0", "body": "Welcome to Code Review. The current question title and description, which state your concerns about the code, apply to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. The description on the other hand should state the goals in more detail. Please see [ask] for examples, and [edit] the title and description accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T12:54:46.593", "Id": "411103", "Score": "0", "body": "Thanks to both of you for helping me on the site. I should have read more before posting, sorry. I'm going to edit the code right now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T13:30:24.850", "Id": "411112", "Score": "0", "body": "Concerning the fact that user may enter too many characters, one possibility is to read a string (with std::getline) and to check the value of the first entered character of the string only." } ]
[ { "body": "<h1>Includes</h1>\n<p>We include <code>&lt;string&gt;</code> but don't use anything from it, so that line can be removed.</p>\n<h1>Namespace <code>std</code></h1>\n<p>Avoid <code>using namespace std</code> - it won't hurt in simple programs, but it's a bad habit that could subtly change the meaning of programs. Import just the names you need, in the smallest reasonable scope, or just get used to writing <code>std::</code> - it's intentionally very short!</p>\n<h1>Indentation</h1>\n<p>Pick a common indentation style, and use it consistently (perhaps that's a problem of how you've copied the code into the question, rather than a fault in the code itself?).</p>\n<h1>Always test input operations</h1>\n<p>The reading of a character with <code>&gt;&gt;</code> can fail - for example, if the input stream is closed.</p>\n<h1>Prefer <code>do</code>-<code>while</code></h1>\n<p>Our loop should run at least once. <code>do</code>-<code>while</code> expresses that better than <code>while</code>, and means that we don't need to initialise <code>cafe</code> outside the loop.</p>\n<h1>Rearrange the <code>if</code></h1>\n<p>We can re-order the <code>if</code> so that our current first case becomes the <code>else</code> clause:</p>\n<pre><code> if (cafe == 'O') {\n std::cout &lt;&lt; &quot;Regalez-vous !&quot; &lt;&lt; std::endl;\n } else if (cafe == 'N') {\n std::cout &lt;&lt; &quot;Tant pis, a la prochaine !&quot; &lt;&lt; std::endl;\n } else {\n std::cout &lt;&lt; &quot;Merci de répondre par O ou par N.&quot; &lt;&lt; std::endl;\n }\n</code></pre>\n<h1>Consider <code>switch</code></h1>\n<p>Any time we have different behaviours for particular values of a variable, we might use a <code>switch</code> statement instead of chained <code>if</code>/<code>else if</code> statements.</p>\n<h1>Exit early from the loop</h1>\n<p>We can <code>break</code> or <code>return</code> out of the loop in the success cases, rather than testing against <code>O</code> or <code>N</code> again. In this case, the loop can be indefinite (<code>while (true)</code>) and that's conventionally written as a <code>while</code> rather than <code>do</code>-<code>while</code>, so we change that back again.</p>\n<h1>Accept lower case letters</h1>\n<p>Allow the user to input <code>o</code> instead of <code>O</code>, or <code>n</code> instead of <code>N</code>. Users are simple creatures and will expect the program to cope with their assumptions.</p>\n<h1>Discard the rest of the input line</h1>\n<p>Something alluded to in the description: if the user enters a nonsense word, then each character in the word will be tested. We could ignore everything up to the next newline, like this:</p>\n<pre><code> std::cin.ignore(999 , '\\n');\n</code></pre>\n<p>(the <code>999</code> is just a &quot;large&quot; number of characters to ignore; we don't expect that many from one user line).</p>\n<hr />\n<h1>Improved code</h1>\n<pre><code>#include &lt;iostream&gt;\n\nint main()\n{ \n while (true) {\n std::cout &lt;&lt; &quot;Veux-tu du café ? O/N&quot; &lt;&lt; std::endl;\n char cafe;\n std::cin &gt;&gt; cafe;\n if (!std::cin) {\n std::cerr &lt;&lt; &quot;Read error!\\n&quot;;\n return 1;\n }\n // ignore rest of line\n std::cin.ignore(999 , '\\n');\n\n switch (cafe) {\n case 'O':\n case 'o':\n std::cout &lt;&lt; &quot;Regalez-vous !&quot; &lt;&lt; std::endl;\n return 0;\n case 'N':\n case 'n':\n std::cout &lt;&lt; &quot;Tant pis, a la prochaine !&quot; &lt;&lt; std::endl;\n return 0;\n default:\n std::cout &lt;&lt; &quot;Merci de répondre par O ou par N.&quot; &lt;&lt; std::endl;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T13:37:43.117", "Id": "411114", "Score": "0", "body": "Hey ! Thank you so much for the answer. That's so complete ! I will try this out." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T13:33:41.903", "Id": "212547", "ParentId": "212524", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T08:32:12.967", "Id": "212524", "Score": "2", "Tags": [ "c++", "beginner" ], "Title": "Offering coffee" }
212524
<p>I'm looking for improvement / advice / reviews on how I can improve this code. I feel like there is a better way or more efficient way of doing this and I am over looking it.</p> <p>The Plugin I made is very simple:</p> <ol> <li>It stores a list of Postcodes that the admin inputs into a textarea - 1 Per Line.</li> <li>Plugin creates a text input on the front end that allows their customers to search if their postcode is in the list with Ajax.</li> </ol> <p>The Plugin has a few options to allow the admin to customize the look and functionality of the plugin. Below is the function that takes the postcode and searches the list:</p> <pre><code>function sapc_ajax_check() { $checker_defaults = get_option( 'sapc_checker_settings_options' ); $found = 0; $msg = ''; $passed = 0; if (!empty( $_POST ) &amp;&amp; isset($_POST['action']) &amp;&amp; strcmp($_POST['action'], 'sapc_ajax_check') === 0) { if(isset($_POST['pc'])){ if(isset($_POST['verify-int']) &amp;&amp; $_POST['verify-int'] == 'on'){ if(is_numeric($_POST['pc']) &amp;&amp; is_int((int)$_POST['pc'])){ $passed = 1; } }elseif($checker_defaults['verify-int'] == 'on'){ $passed = 1; }else{$passed = 1;} if($passed === 1){ $temp_l = $checker_defaults['postcodes']; $postcode_l = explode(PHP_EOL, $temp_l); if(is_array($postcode_l) &amp;&amp; !empty($postcode_l)){ foreach($postcode_l as $i=&gt;$temp_p){ if( strpos($temp_p, ':') !== false) { $v = explode(':', $temp_p); if(strcmp($v[0], $_POST['pc']) === 0){ $found = 1; $msg .= $v[1] .', '; } }else{ if(strcmp($temp_p, $_POST['pc']) === 0){ $found = 1; $msg .= $temp_p .', '; } } } if($msg != ''){ $msg = substr($msg, 0, strlen($msg) - 2); } }else{$msg ='Error: Try Again';} }else{$msg ='Error: Invalid Postcode';} }else{$msg ='Error: No Postcode';} }else{$msg = 'Error: No Data';} if($found == 0){ echo json_encode(array('Error', 'Postcode Not Found'), JSON_FORCE_OBJECT); }else{ echo json_encode(array('Success', $msg), JSON_FORCE_OBJECT); } die(); } </code></pre> <p>There are 2 sets of variables.</p> <ol> <li><p>First set is the default settings from the admin options page, this helps with placing widgets and allows admins to set their own defaults. Postcodes can only be set here.</p></li> <li><p>Second set is from the widget instance which allows admins to personalize each widget if need be.</p></li> </ol> <p>I'll explain some of the variables.</p> <p><code>$_POST['pc']</code> = Postcode from User</p> <p><code>$_POST['verify-int']</code> = Option to check if postcode is all integers - Passed from Postcode Widget</p> <p><code>$checker_defaults['postcodes']</code> = list of postcodes</p> <p>Postcode List accepts the following formats:</p> <p>Postcode:Surbubr Postcode</p> <p>(1 per line)</p> <p>What can I do to make this function more efficient and more cleaner? If you need anything else please let me know I think I've covered everything.</p>
[]
[ { "body": "<p>It looks like you could benefit by trying to avoid the <a href=\"http://wiki.c2.com/?ArrowAntiPattern\" rel=\"nofollow noreferrer\">arrowhead anti-pattern</a>. </p>\n\n<p>This occurs when you check the validity of your inputs before proceeding to do the work within the conditional body, and can lean to hard to read code when there are many conditionals to check, each relying on the previous condition passing.You end up with \"wide\" code due to the arrow shape, and there can be a lot of lines between where a condition fails, and how it is handled.</p>\n\n<pre><code>/* arrowhead code */\n\nif (input !== null) {\n if (input.property !== null) {\n if (checkIfValid(input.property) &gt; 0) {\n\n // do the work\n\n } else {\n // handle invalid property\n } else {\n // no property\n} else {\n // no input\n}\n</code></pre>\n\n<p>This can be prevented with a \"fail fast\" approach. Instead of checking that a condition is valid and putting everything in its body, try checking if the condition is invalid, and if so, handle it (by logging a message in this case), and exit the function. Then check if the next condition is invalid, etc. Once you've confirmed the inputs are valid in this fail fast logic at the top, you can do the real work in a less deeply nested block that is easier to read and understand.</p>\n\n<pre><code>/* arrowhead removed */\n\nif (input === null) {\n // no input\n}\nif (input.property !== null) {\n // no property\n}\nif (checkIfValid(input.property) &lt;= 0) {\n // handle invalid property\n}\n\n // do the work\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T13:28:53.267", "Id": "212546", "ParentId": "212526", "Score": "2" } }, { "body": "<p>I agree with the advice in <a href=\"https://codereview.stackexchange.com/a/212546/120114\">the answer by user4963355</a>. In <a href=\"https://www.youtube.com/watch?v=GtB5DAfOWMQ\" rel=\"nofollow noreferrer\">this presentation about cleaning up code</a> Rafael Dohms talks about limiting the indentation level to one per method and avoiding the <code>else</code> keyword. (<a href=\"https://www.slideshare.net/rdohms/bettercode-phpbenelux212alternate/11-OC_1Only_one_indentation_level\" rel=\"nofollow noreferrer\">see the slides here</a>).</p>\n\n<p>One other suggestion I have is whenever you find an element to add to the message, e.g. values in <code>$v[1]</code> or <code>$temp_p</code>, instead of appending them to <code>$msg</code>, push them into an array. Instead of checking if <code>$found</code> is 0, you can check if the length of the array is 0 (using <a href=\"https://php.net/count\" rel=\"nofollow noreferrer\"><code>count()</code></a>). If it is not 0, construct the message using <a href=\"https://php.net/implode\" rel=\"nofollow noreferrer\"><code>implode()</code></a>. That way there is no need to remove excess characters from the end of the string and you can use the <em>semantics</em> of \"<em>found</em>\" using <code>count()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T22:19:00.833", "Id": "411217", "Score": "0", "body": "Yes pushing to array and imploding is a much better idea. Thanks for the link will check it out." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:08:42.723", "Id": "212566", "ParentId": "212526", "Score": "2" } }, { "body": "<p>Inside of a function call, avoid echoing. By hardcoding echoes, you prevent the \"silent\" usage of the function. It may be necessary in the future to present the output in more than one format, so use a <code>return</code> inside the function declaration and perform the echo on the function call.</p>\n\n<p>Pay close attention to <a href=\"https://www.php-fig.org/psr/psr-2/#5-control-structures\" rel=\"nofollow noreferrer\">psr-2's guidelines on control structures</a>. They will help you (and future developers of your code) to read your code. Always imagine that the next person to read your code will have a headache, a hatchet, and your home address; don't set them off.</p>\n\n<p>Empty on <code>$_POST</code> is an imprecise way of checking for expected submission data. </p>\n\n<p><code>strcmp()</code> provides <a href=\"https://stackoverflow.com/a/3333369/2943403\">greater specificity than your condition logic requires</a>. For your logic, just check if the input is identical to the string without a function call.</p>\n\n<p>Condense conditionals within the same block that have the same outcome. Multiple conditions lead to <code>$passed = 1</code> so they can be consolidated. I didn't really bother to understand the conditional logic behind <code>$passed = 1</code> but it should certainly be refined.</p>\n\n<p>Refine your validation check on <code>$_POST['pc']</code>. You are checking if <code>is_numeric()</code>, that's fine. Then checking if the value that is cast as <code>(int)</code> is an integer -- um, at this point of course it is, it has no choice. Better yet, why not just make a single check with <code>ctype_digit()</code>? You might also like to check that the <code>strlen()</code> is valid (only you will know if/how to design this for your region). If you want to check the quality and length of the postcode value, perhaps it would be more sensible to use <code>preg_match()</code> where you can design robust/flexible validation with a single function call (again, only you can determine this).</p>\n\n<p><code>$temp_l</code> and <code>$temp_p</code> are poor variable naming choices. As a new dev to your script, I don't instantly know what they contains (I can venture a guess, but don't ask devs to do this). Try to practice a more literal naming convention. Furthermore, try to avoid declaring single-use variables (<code>$temp_l</code>). Often, fewer variables will lead to fewer typos/mistakes, concise code, and improved readability. When data needs some explaining, use commenting. *notes: 1. I have read some cases where declaring a variable prior to a foreach loop can improve performance 2. Some devs don't like to see functions fed to a foreach loop, I can respect this and I don't typically do this in my own projects.</p>\n\n<p>There is no use in checking if the return value from <code>explode()</code> is an array. It returns an array by design, so you can remove that check. Even if you explode a empty string with <code>PHP_EOL</code>, you will not get a <code>true</code> evaluation from <code>empty()</code>, so that check is pointless to write. At the end of the day, if you try to use <code>foreach()</code> on an empty array, it simply won't iterate -- no worries.</p>\n\n<p>If you have no intentions of using <code>$i</code> in your foreach loop, don't bother to declare it. I don't like single-use variables; I super don't like no-use variables.</p>\n\n<p>How to get the substring before the first occurrence of a character without <code>explode()</code>? <code>strstr()</code> with a <code>true</code> third parameter. Otherwise, explode has to create an array enroute to delivering the string that you need. My suggested snippet will attempt to extract the substring before the first colon, if there is no colon the full string will be used.</p>\n\n<p>By storing qualifying matches as an array, you can avoid having to trim any trailing delimiters from your output string. In fact, return the data without delimiters as an array so that you can easily adjust the way that your qualifying values are delimited.</p>\n\n<p>Strictly speaking, having zero qualifying results from a postcode search doesn't mean that there was an \"Error\", so just have your function calling script accommodate for \"Successful\" yet \"Empty\" results.</p>\n\n<p>I can't imagine a benefit from <code>JSON_FORCE_OBJECT</code>.</p>\n\n<p><code>die()</code> in nearly every scenario should be avoided.</p>\n\n<p>Suggested Code Overhaul:</p>\n\n<pre><code>function sapc_ajax_check() {\n $checker_defaults = get_option('sapc_checker_settings_options');\n\n if (!isset($_POST['action']) || $_POST['action'] !== 'sapc_ajax_check') {\n $errors[] = 'Missing required submission data';\n }\n if (!isset($_POST['pc'])) {\n $errors[] = 'Missing postcode value';\n }\n if (isset($_POST['verify-int']) &amp;&amp; $_POST['verify-int'] === 'on' &amp;&amp; ctype_digit($_POST['pc'])) {\n $errors[] = 'Invalid postcode value';\n }\n if (isset($errors)) {\n return json_encode(['Error', $errors]);\n }\n\n $result = [];\n foreach (explode(PHP_EOL, $checker_defaults['postcodes']) as $postcode) {\n $before_colon = strstr($postcode, ':', true);\n $postcode = ($before_colon === false ? $postcode : $before_colon);\n if ($postcode === $_POST['pc'])) {\n $result[] = $postcode;\n }\n }\n return json_encode(['Success', $result]); \n}\n</code></pre>\n\n<p><strong>Much cleaner right?</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T01:41:54.763", "Id": "411230", "Score": "1", "body": "Looks much cleaner thank you. After the other answers I had started working on something similar to yours with the exception of using `ctype_digit`, `strstr` and the `foreach`. Glad I was heading in the right direction. Definitely all makes sense now it's in front of me. Much appreciated." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T01:21:34.737", "Id": "212596", "ParentId": "212526", "Score": "4" } } ]
{ "AcceptedAnswerId": "212596", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T09:46:13.953", "Id": "212526", "Score": "3", "Tags": [ "php", "strings", "array", "iteration", "wordpress" ], "Title": "Check if a postcode is in a list" }
212526
<p>The following code is part of the front-end of a micro webservice for users to allow them to register MAC addresses of their network devices and administrators to enable those and to generate a <code>dhcpd.conf</code> file for a firewall application. You can find the whole project <a href="https://github.com/conqp/macreg" rel="nofollow noreferrer">here</a>.</p> <p><code>macreg.js</code></p> <pre><code>/* (C) 2018 Richard Neumann &lt;mail at richard dash neumann period de&gt; 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 3 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;http://www.gnu.org/licenses/&gt;. */ 'use strict'; var macreg = macreg || {}; macreg.LOGIN_URL = 'login'; macreg.SUBMIT_URL = 'mac'; /* Makes a request returning a promise. */ macreg.makeRequest = function (method, url, data=null, ...headers) { function parseResponse (response) { try { return JSON.parse(response); } catch (error) { return response; } } function executor (resolve, reject) { function onload () { if (this.status &gt;= 200 &amp;&amp; this.status &lt; 300) { resolve({ response: parseResponse(xhr.response), status: this.status, statusText: xhr.statusText }); } else { reject({ response: parseResponse(xhr.response), status: this.status, statusText: xhr.statusText }); } } function onerror () { reject({ response: parseResponse(xhr.response), status: this.status, statusText: xhr.statusText }); } const xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.open(method, url); for (let header of headers) { xhr.setRequestHeader(...header); } xhr.onload = onload; xhr.onerror = onerror; if (data == null) { xhr.send(); } else { xhr.send(data); } } return new Promise(executor); }; /* Filters MAC address records. */ macreg._filter = function* (records) { const filterString = document.getElementById('filter').value.trim(); if (filterString == '') { yield* records; return; } for (let record of records) { let matchDate = record.timestamp.includes(filterString); let matchUserName = record.userName.includes(filterString); let matchMacAddress = record.macAddress.includes(filterString); let matchDescription = record.description.includes(filterString); let matchIpv4address = record.ipv4address.includes(filterString); if (matchDate || matchUserName || matchMacAddress || matchDescription || matchIpv4address) { yield record; } } }; /* Creates a toggle button for the respective record. */ macreg._toggleButton = function (record) { const column = document.createElement('td'); const buttonToggle = document.createElement('button'); buttonToggle.setAttribute('data-id', record.id); if (record.ipv4address == null) { buttonToggle.setAttribute('class', 'btn btn-success macreg-toggle'); buttonToggle.textContent = 'Enable'; } else { buttonToggle.setAttribute('class', 'btn btn-warning macreg-toggle'); buttonToggle.textContent = 'Disable'; } column.appendChild(buttonToggle); return column; }; /* Creates a delete button for the respective record. */ macreg._deleteButton = function (record) { const column = document.createElement('td'); const buttonDelete = document.createElement('button'); buttonDelete.setAttribute('class', 'btn btn-danger macreg-delete'); buttonDelete.setAttribute('data-id', record.id); buttonDelete.setAttribute('data-toggle', 'tooltip'); buttonDelete.setAttribute('data-placement', 'top'); buttonDelete.setAttribute('title', 'Delete this MAC address.'); buttonDelete.textContent = 'Delete'; column.appendChild(buttonDelete); return column; }; /* Renders the respective records. */ macreg._render = function (response) { const container = document.getElementById('records'); container.innerHTML = ''; const records = macreg._filter(response.response); for (let record of records) { let row = document.createElement('tr'); let fields = [ record.timestamp, record.userName, record.macAddress, record.description, record.ipv4address || 'N/A' ]; for (let field of fields) { let column = document.createElement('td'); column.textContent = field; row.appendChild(column); } row.appendChild(macreg._toggleButton(record)); row.appendChild(macreg._deleteButton(record)); container.appendChild(row); } for (let button of document.getElementsByClassName('macreg-toggle')) { button.addEventListener('click', function() { macreg._toggle(button.getAttribute('data-id')); }); } for (let button of document.getElementsByClassName('macreg-delete')) { button.addEventListener('click', function() { macreg._delete(button.getAttribute('data-id')); }); } }; /* Toggles a MAC address between enabled / disabled. */ macreg._toggle = function (id) { return macreg.makeRequest('PATCH', macreg.SUBMIT_URL + '/' + id).then( macreg.render, function (error) { alert(error.response); if (error.status == 401) { window.location = 'index.html'; } } ); }; /* Deletes a MAC address. */ macreg._delete = function (id) { return macreg.makeRequest('DELETE', macreg.SUBMIT_URL + '/' + id).then( macreg.render, function (error) { alert(error.response); if (error.status == 401) { window.location = 'index.html'; } } ); }; /* Initializes the login page. */ macreg.loginInit = function () { document.removeEventListener('DOMContentLoaded', macreg.loginInit); document.getElementById('btnLogin').addEventListener('click', function(event) { event.preventDefault(); }); }; /* Initializes the submit page. */ macreg.submitInit = function () { document.removeEventListener('DOMContentLoaded', macreg.submitInit); document.getElementById('btnSubmit').addEventListener('click', function(event) { event.preventDefault(); }); document.getElementById('filter').addEventListener('change', macreg.render); return macreg.render(); }; /* Renders the page. */ macreg.render = function () { return macreg.makeRequest('GET', macreg.SUBMIT_URL).then( macreg._render, function (error) { if (error.status == 401) { // Session expired. alert(error.response); window.location = 'index.html'; } } ); }; /* Performs a login. */ macreg.login = function () { const userName = document.getElementById('userName').value; const password = document.getElementById('password').value; const header = ['Content-Type', 'application/json']; const payload = {'userName': userName, 'passwd': password}; const data = JSON.stringify(payload); return macreg.makeRequest('POST', macreg.LOGIN_URL, data, header).then( function () { window.location = 'submit.html'; }, function (error) { alert(error.response || 'Anmeldung fehlgeschlagen.'); } ); }; /* Submits a new MAC address. */ macreg.submit = function () { const macAddress = document.getElementById('macAddress').value; const description = document.getElementById('description').value; const payload = {'macAddress': macAddress.trim(), 'description': description.trim()}; const header = ['Content-Type', 'application/json']; const data = JSON.stringify(payload); return macreg.makeRequest('POST', macreg.SUBMIT_URL, data, header).then( function () { const form = document.getElementById('submitForm'); form.reset(); macreg.render(); }, function (error) { alert(error.response); switch(error.status) { case 401: window.location = 'index.html'; break; default: macreg.render(); break; } } ); }; </code></pre> <p><code>index.html</code></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;head&gt; &lt;meta charset="utf-8"/&gt; &lt;title&gt;MAC Address registration&lt;/title&gt; &lt;link rel="stylesheet" href="bootstrap.min.css"&gt; &lt;script src="macreg.js"&gt;&lt;/script&gt; &lt;script&gt; document.addEventListener('DOMContentLoaded', macreg.loginInit); &lt;/script&gt; &lt;/head&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col col-md-12"&gt; &lt;h1&gt;Login&lt;/h1&gt; &lt;form&gt; &lt;div class="form-group"&gt; &lt;label for="userName"&gt;User Name&lt;/label&gt; &lt;input type="text" class="form-control" id="userName" aria-describedby="userNameHelp" placeholder="User Name"&gt; &lt;small id="userNameHelp" class="form-text text-muted"&gt;Your local user name.&lt;/small&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="password"&gt;Password&lt;/label&gt; &lt;input type="password" class="form-control" id="password" aria-describedby="passwordHelp" placeholder="Password"&gt; &lt;small id="passwordHelp" class="form-text text-muted"&gt;Never give your password to somebody else.&lt;/small&gt; &lt;/div&gt; &lt;button id="btnLogin" onclick="macreg.login();" type="submit" class="btn btn-primary btn-block"&gt;Login&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><code>submit.html</code></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;head&gt; &lt;meta charset="utf-8"/&gt; &lt;title&gt;MAC Address registration&lt;/title&gt; &lt;link rel="stylesheet" href="bootstrap.min.css"&gt; &lt;script src="macreg.js"&gt;&lt;/script&gt; &lt;script&gt; document.addEventListener('DOMContentLoaded', macreg.submitInit); &lt;/script&gt; &lt;/head&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col col-md-12"&gt; &lt;h1&gt;MAC Address registration&lt;/h1&gt; &lt;form id="submitForm"&gt; &lt;div class="form-group"&gt; &lt;label for="macAddress"&gt;MAC Address&lt;/label&gt; &lt;input type="text" class="form-control" id="macAddress" aria-describedby="macAddressHelp" placeholder="MAC Address"&gt; &lt;small id="macAddressHelp" class="form-text text-muted"&gt;On Windows press &lt;kbd&gt;&lt;kbd&gt;Ctrl&lt;/kbd&gt; + &lt;kbd&gt;R&lt;/kbd&gt;&lt;/kbd&gt;, type &lt;code&gt;cmd&lt;/code&gt; then hit Enter. In the terminal run &lt;code&gt;ipconfig /all&lt;/code&gt;.&lt;br/&gt; In the output, look for your respective Ethernet or Wifi Addapter and search for the line &lt;code&gt;Physical Address&lt;/code&gt;. &lt;/small&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="description"&gt;Description&lt;/label&gt; &lt;input type="text" class="form-control" id="description" aria-describedby="descriptionHelp" placeholder="Description"&gt; &lt;small id="descriptionHelp" class="form-text text-muted"&gt;Describe what kind of device this MAC address is for.&lt;/small&gt; &lt;/div&gt; &lt;button id="btnSubmit" onclick="macreg.submit();" type="submit" class="btn btn-primary btn-block"&gt;Submit&lt;/button&gt; &lt;/form&gt; &lt;br/&gt; &lt;h2&gt;Registered MAC addresses&lt;/h2&gt; &lt;input type="text" class="form-control" id="filter" aria-describedby="macAddressHelp" placeholder="Filter..."&gt; &lt;table class="table"&gt; &lt;thead&gt; &lt;tr id="headRow"&gt; &lt;th scope="row"&gt;Date&lt;/th&gt; &lt;th scope="row"&gt;User Name&lt;/th&gt; &lt;th scope="row"&gt;MAC Address&lt;/th&gt; &lt;th scope="row"&gt;Description&lt;/th&gt; &lt;th scope="row"&gt;IPv4 Address&lt;/th&gt; &lt;th scope="row"&gt;Toggle&lt;/th&gt; &lt;th scope="row"&gt;Delete&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody id="records"&gt;&lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I'd like to get feedback especially on the ES6 code quality and possible improvements.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T09:52:30.283", "Id": "212527", "Score": "1", "Tags": [ "javascript", "ecmascript-6", "html5" ], "Title": "JavaScript code for MAC registration micro webservice" }
212527
<p>The aim of the program is to read the yahoo finance website in order to find potentially profitable stocks based on their past performance.</p> <p>I have some code that works but I think it is of poor quality. I am trying to scrape data from a website. If the internet connection fails, the program should wait 5 seconds before retrying. </p> <p><strong>Program.cs</strong></p> <pre><code>using HtmlAgilityPack; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EarningEdge { class Program { static void Main(string[] args) { DateTime currDate = new DateTime(Constants.startYear, Constants.startMonth, Constants.startDay); DateTime endDate = new DateTime(Constants.endYear, Constants.endMonth, Constants.endDay); DateTime weekDate = currDate.AddDays(7 - (currDate.Day % 7 + 2)); string currDir = Environment.CurrentDirectory + @"\Stock\"; System.IO.Directory.CreateDirectory(currDir); while (currDate.CompareTo(endDate) &lt; 0) { if (currDate.DayOfWeek.Equals(DayOfWeek.Saturday)) { weekDate = weekDate.AddDays(7); } // Do nothing on the weekend. For thy shall rest on the sabbath. if (currDate.DayOfWeek.Equals(DayOfWeek.Saturday) || currDate.DayOfWeek.Equals(DayOfWeek.Sunday)) { currDate = currDate.AddDays(1); continue; } HtmlWeb web = new HtmlWeb(); //var html = @"https://finance.yahoo.com/calendar/earnings?from=2019-01-20&amp;to=2019-01-26&amp;day=2019-01-25"; var html = @"https://finance.yahoo.com/calendar/earnings?from=" + weekDate.AddDays(-6).Year + "-" + weekDate.AddDays(-6).Month.ToString("D2") + "-" + (weekDate.AddDays(-6).Day.ToString("D2")) + "&amp;to=" + weekDate.Year + "-" + weekDate.Month.ToString("D2") + "-" + weekDate.Day.ToString("D2") + "&amp;day=" + currDate.Year + "-" + currDate.Month.ToString("D2") + "-" + currDate.Day.ToString("D2"); HtmlDocument htmlDoc = null; try { htmlDoc = web.Load(html); } catch (Exception e) { System.IO.File.AppendAllText(currDir + @"ErrorLog.txt", "\nDate of Earning Report : " + currDate.ToString("dd-MM-yyyy") + "\nError occured at : " + DateTime.Now.ToString("dd-MM-yyyy") + "\nError message : " + e.Message + "\nInner message : " + e.InnerException + "\nHtml : " + html + "\n\n"); // I don't need to worry about UI responsiveness so this should suffice. System.Threading.Thread.Sleep(5000); // Continue to re-run the above code after 5 seconds. continue; } if (htmlDoc.DocumentNode != null) { var nodes = htmlDoc.DocumentNode.SelectNodes("//tbody"); foreach (var node in nodes.Descendants("tr")) { var counter = 0; var row = node.ChildNodes; string symbol = null; foreach (var col in row) { // The Symbol Column of the table. if (counter == Constants.Symbol) { symbol = col.InnerText; break; } counter++; //Console.WriteLine(symbol); } // For each company row access the earning history. if (symbol != null) { // Even if the stock isn't optionable, I will still record it. // For Academic purposes. //// Check if the stock is optionable. //html = @"https://finance.yahoo.com/quote/" + symbol + "/options?p=" + symbol; ////html = @"https://finance.yahoo.com/quote/FMBM/options?p=FMBM"; //while (true) //{ // try // { // htmlDoc = web.Load(html); // } // catch (Exception e) // { // System.IO.File.AppendAllText(currDir + @"ErrorLog.txt", // "\nDate of Earning Report : " + currDate.ToString("dd-MM-yyyy") // + "\nError occured at : " + DateTime.Now.ToString("dd-MM-yyyy") // + "\nSymbol : " + symbol // + "\nError message : " + e.Message // + "\nInner message : " + e.InnerException // + "\nHtml : " + html // + "\n\n"); // // I don't need to worry about UI responsiveness so this should suffice. // System.Threading.Thread.Sleep(5000); // continue; // } // break; //} //if (htmlDoc.DocumentNode != null) //{ // var options = htmlDoc.DocumentNode.SelectNodes("//div[@id='Main']").Descendants("Section").ElementAt(0).InnerText; // if (options == "Options data is not available") // { // continue; // } //} html = @"https://finance.yahoo.com/quote/" + symbol + "/analysis?p=" + symbol; //html = @"https://finance.yahoo.com/quote/MSG/analysis?p=MSG"; //htmlDoc = web.Load(html); while (true) { try { htmlDoc = web.Load(html); } catch (Exception e) { System.IO.File.AppendAllText(currDir + @"ErrorLog.txt", "\nDate of Earning Report : " + currDate.ToString("dd-MM-yyyy") + "\nError occured at : " + DateTime.Now.ToString("dd-MM-yyyy") + "\nSymbol : " + symbol + "\nError message : " + e.Message + "\nInner message : " + e.InnerException + "\nHtml : " + html + "\n\n"); // I don't need to worry about UI responsiveness so this should suffice. System.Threading.Thread.Sleep(5000); continue; } break; } if (htmlDoc.DocumentNode != null) { var earningNode = htmlDoc.DocumentNode.SelectNodes("//section[@data-test='qsp-analyst']"); // No earning history avaliable. if (earningNode == null) { continue; } var tables = earningNode.Descendants("table"); var earnings = tables.ElementAt(2).Descendants("tbody").ElementAt(0).Descendants("tr").ElementAt(3); var growthStr = tables.ElementAt(5).Descendants("tbody").ElementAt(0).Descendants("tr").ElementAt(0).Descendants("td").ElementAt(1).InnerText.Trim('%'); float growth; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Date: " + currDate.ToString("dd-MM-YY")); Console.WriteLine("Symbol : " + symbol); if (float.TryParse(growthStr, out growth)) { Console.WriteLine("Growth : " + growth); } float q1; if (float.TryParse(earnings.Descendants("td").ElementAt(1).InnerText.Trim('%'), out q1)) { Console.WriteLine(q1); } float q2; if (float.TryParse(earnings.Descendants("td").ElementAt(2).InnerText.Trim('%'), out q2)) { Console.WriteLine(q2); } float q3; if (float.TryParse(earnings.Descendants("td").ElementAt(3).InnerText.Trim('%'), out q3)) { Console.WriteLine(q3); } float q4; if (float.TryParse(earnings.Descendants("td").ElementAt(4).InnerText.Trim('%'), out q4)) { Console.WriteLine(q4); } if (q1 &lt; 0 || q2 &lt; 0 || q3 &lt; 0 || q4 &lt; 0) { continue; } if (growth &lt; 80) { continue; } Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(symbol + " : Is expecting a 3 week climb"); Console.ForegroundColor = ConsoleColor.Green; System.IO.File.AppendAllText(currDir + @"3WeekClimb.txt", currDate.ToString("dd-MM-yyyy") + " symbol: " + symbol + "\n"); // Store this stock in the database. Expect a 3 week climb. // Manually check the chart to see if the climb already happened. } } } } currDate = currDate.AddDays(1); } } } } </code></pre> <p><strong>Constants.cs</strong></p> <pre><code>namespace EarningEdge { static class Constants { public const int Symbol = 1; public const int startDay = 29; public const int startMonth = 1; public const int startYear= 2019; public const int endDay = 28; public const int endMonth = 2; public const int endYear= 2019; } } </code></pre> <p>Is there a more elegant way of doing this?</p> <p>Is this bad practice? My intention is to have an infinite loop just in case the internet dies the program will continue to run, polling the website every 5 seconds until the internet is back online.</p> <p>This is a console app using c#. I am using htmlAgilityPack to load the web page.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T11:30:37.470", "Id": "411091", "Score": "0", "body": "This looks incomplete - you'll get better reviews if you include the full program, including any imports and your `main()` function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T11:31:25.437", "Id": "411092", "Score": "0", "body": "Re \"*I'm not sure if this is the right place for this question.*\" As currently written, it isn't. The code is a snippet without enough context to properly understand what it's doing (e.g. what the type of `web` is). You could edit to provide a larger, more self-contained, block of code, provided you accept that answers can address any perceived issues with the code and not just your personal concerns with it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T12:37:21.333", "Id": "411102", "Score": "1", "body": "Appreciate the advice. I have included most of the code." } ]
[ { "body": "<p>Don't split up dates into year/month/day, instead use a <code>static DateTime</code>. Which means you need to rename your <code>Constants</code> class to something like <code>Setup</code> or <code>Configuration</code>.</p>\n\n<hr>\n\n<p>Your <code>Main</code> is a 200+ lines long method. You should split this up into smaller methods and maybe even move some of those to dedicated classes.</p>\n\n<hr>\n\n<p>Don't create your own (primitive) logging system, instead use an established platform like NLog or Serilog.</p>\n\n<hr>\n\n<p>I'm somewhat baffled by the meaning of <code>public const int Symbol = 1;</code>. Especially since there is also a variable named <code>symbol</code>. Names should convey a meaning, and that seems to be totally lacking here.</p>\n\n<hr>\n\n<p>Why do you loop through all the columns in a row when you only need the second one?</p>\n\n<hr>\n\n<p>This code is repeated four times with only minimal changes:</p>\n\n<pre><code>float q1;\nif (float.TryParse(earnings.Descendants(\"td\").ElementAt(1).InnerText.Trim('%'), out q1))\n{\n Console.WriteLine(q1);\n}\n</code></pre>\n\n<p>Don't copy-paste code; instead move this to a dedicated method.</p>\n\n<hr>\n\n<p>Do not pointlessly abbreviate: <code>currDate</code> is harder to read than <code>currentdate</code> and doesn't gain you anything.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T12:55:13.107", "Id": "212543", "ParentId": "212532", "Score": "2" } } ]
{ "AcceptedAnswerId": "212543", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T11:06:25.343", "Id": "212532", "Score": "1", "Tags": [ "c#", "console", "web-scraping" ], "Title": "Handle connection time outs when loading a web page in a c# console app" }
212532
<p><a href="https://www.codewars.com/kata/number-of-anagrams-in-an-array-of-words/train/python" rel="nofollow noreferrer">Codewars Kata in Question</a>. </p> <blockquote> <p>An anagram is a word, a phrase, or a sentence formed from another by rearranging its letters. An example of this is "angel", which is an anagram of "glean".</p> <p>Write a function that receives an array of words, and returns the total number of distinct pairs of anagramic words inside it.</p> <p>Some examples:</p> <p>There are 2 anagrams in the array <code>["dell", "ledl", "abc", "cba"]</code> </p> <p>There are 7 anagrams in the array <code>["dell", "ledl", "abc", "cba", "bca", "bac"]</code></p> </blockquote> <p>My code is usually not optimal, and I would like to improve my coding practices, and coding sense which is why I try to put up for review all nontrivial code I write.</p> <h3>My Code</h3> <pre><code>from collections import Counter import math def choose(n, k): #Each distinct anagram pair is a selection from the set of all words that have the same count. f = math.factorial return (f(n)//(f(n-k)*f(k))) def anagram_counter(words): words = list(set(words)) #Suppress duplicates. unique = set() #Set of unique words. count = {} #Dictionary that stores the count for each word. unique = set() for word in words: #The current word is not an anagram of any word already in the set. wordID = Counter(word) if not unique or all((wordID != count[distinct][1] for distinct in unique)): unique.add(word) count[word] = [1,wordID] #A tuple containing number of anagrams of a word and its `wordID`. else: #If the current word is an anagram of a word already in the set. for distinct in list(unique): if count[distinct][1] == wordID: #If the word is an anagram of a preexisting word. count[distinct][0] += 1 #Increment the counter. break return 0 if count == {} else sum((choose(itm[0], 2) for itm in count.values() if itm[0] &gt; 1)) </code></pre>
[]
[ { "body": "<p>You are making your life too difficult, IMO. Whenever you iterate over all members of a <code>set</code> to see if some element is in it or write <code>list(unique)</code>, you are probably doing something wrong.</p>\n\n<p>I would just transform each word into a canonical form (you could choose a <code>frozenset</code> of the <code>Counter</code> items or just a sorted string). Then just count how often each appears:</p>\n\n<pre><code>def anagram_counter(words):\n count = Counter(frozenset(Counter(word).items()) for word in words)\n return sum(choose(x, 2) for x in count.values() if x &gt; 1)\n\ndef anagram_counter2(words):\n count = Counter(\"\".join(sorted(word)) for word in words)\n return sum(choose(x, 2) for x in count.values() if x &gt; 1)\n</code></pre>\n\n<p>You could optimize the last line by using <code>Counter.most_common</code> and stopping as soon as you get to the elements that appeared only once:</p>\n\n<pre><code>from itertools import takewhile\n\ndef anagram_counter3(words):\n count = Counter(\"\".join(sorted(word)) for word in words)\n return sum(choose(x[1], 2)\n for x in takewhile(lambda t: t[1] &gt; 1, count.most_common()))\n</code></pre>\n\n<p>Comparing the timings for some small input:</p>\n\n<pre><code>x = [\"foo\", \"bar\", \"oof\", \"rab\", \"foobar\"]\n%timeit anagram_counter(x)\n# 27.2 µs ± 1.4 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n%timeit anagram_counter2(x)\n# 9.71 µs ± 656 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n%timeit anagram_counter3(x)\n# 11.9 µs ± 492 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n%timeit anagram_counter_op(x)\n# 25.6 µs ± 472 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n</code></pre>\n\n<p>And for some larger inputs:</p>\n\n<pre><code>import random\nimport string\nimport numpy as np\n\n# increasing number of words, always 5 letters\nx1 = [[\"\".join(random.choices(string.ascii_lowercase, k=5)) for _ in range(n)]\n for n in np.logspace(1, 4, num=10, dtype=int)]\n# increasing length of words, always 500 words\nx2 = [[\"\".join(random.choices(string.ascii_lowercase, k=n)) for _ in range(500)]\n for n in np.logspace(1, 4, num=10, dtype=int)]\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/r0xZ5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/r0xZ5.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/jDHlU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jDHlU.png\" alt=\"enter image description here\"></a></p>\n\n<p>(Note that both axis are logarithmic on both plots.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T12:53:43.347", "Id": "212541", "ParentId": "212534", "Score": "2" } }, { "body": "<p>Graipher answer is nice, but there is one possible inefficiency not taken into account: choice.</p>\n\n<p>If you have a lot of anagrams, it's better to replace the generic version with the explicit formula for pair:</p>\n\n<pre><code>def count_pairs(n):\n return (n * (n-1)) // 2\n</code></pre>\n\n<p>here some timings, with a big list with only a few different canonical anagrams:</p>\n\n<pre><code>def random_anagram(w):\n l = w[:]\n random.shuffle(l)\n return \"\".join(l)\n\nbase_anagrams = [random.choices(string.ascii_lowercase, k=30) for i in range(4)]\n\nx4 = [random_anagram(random.choice(base_anagrams)) for _ in range(100000)]\n\ndef anagram_counter5(words): \n count = Counter(\"\".join(sorted(word)) for word in words)\n return sum(count_pairs(x) for x in count.values() if x &gt; 1)\n</code></pre>\n\n<p>gives on my machine</p>\n\n<pre><code>%timeit anagram_counter2(x)\n353 ms ± 2.09 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n%timeit anagram_counter5(x)\n253 ms ± 4.74 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T14:54:57.787", "Id": "212552", "ParentId": "212534", "Score": "2" } } ]
{ "AcceptedAnswerId": "212541", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T11:27:46.187", "Id": "212534", "Score": "2", "Tags": [ "python", "performance", "beginner", "algorithm" ], "Title": "Number of anagrams in an array of words (Codewars)" }
212534
<p>I have written a program in golang which checks the mongodb is running or not using commands. But I'm not sure that the program is sufficient or there is something that needs to change in the program. Can you review my code so I can be sure that my code does not have any error or doesn't break if there is any problem at all?</p> <p>Code </p> <pre><code>package main import ( "bytes" "fmt" "os/exec" ) /* *Function check mongodb is running? if not running then it will help to run it by command */ func main() { status := ExecuteCommand("systemctl is-active mongod") if status == true { fmt.Println("Connected") } else { fmt.Println("disconnected") status = ExecuteCommand("echo &lt;password&gt; | sudo -S service mongod start") if status == true { fmt.Println("Connected") } } } /* * Function to execute the command using golang code. * * Params command type string * * Used by main func * * Returns nil (if no error) * or err type error (if error occurs) */ func ExecuteCommand(command string) bool { cmd := exec.Command("sh", "-c", command) var out bytes.Buffer var stderr bytes.Buffer cmd.Stdout = &amp;out cmd.Stderr = &amp;stderr err := cmd.Run() if err != nil { fmt.Println(fmt.Sprint(err) + ": " + stderr.String()) return false } return true } </code></pre> <p>Golang <a href="https://play.golang.org/p/nhrn7StmcFc" rel="nofollow noreferrer">playground</a></p>
[]
[ { "body": "<p>I think your code works. Another approach would be trying to connect to the database using the MongoDB Go Driver.</p>\n\n<pre><code>import (\n\"context\"\n\"log\"\n\n\"go.mongodb.org/mongo-driver/mongo\"\n\"go.mongodb.org/mongo-driver/mongo/options\"\n\"go.mongodb.org/mongo-driver/mongo/readpref\")\n\nfunc GetClient() *mongo.Client {\n clientOptions := options.Client().ApplyURI(\"mongodb://localhost:27017\")\n client, err := mongo.NewClient(clientOptions)\n if err != nil {\n log.Fatal(err)\n }\n err = client.Connect(context.Background())\n if err != nil {\n log.Fatal(err)\n }\n return client\n}\n</code></pre>\n\n<p>If you can't connect (assuming you passing the right information), it means that the database is not running.</p>\n\n<p>But like I said, it's just another approach.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T19:30:56.117", "Id": "431235", "Score": "1", "body": "Please review the OP when proposing an alternative solution." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T19:09:07.287", "Id": "222727", "ParentId": "212538", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T12:46:50.813", "Id": "212538", "Score": "1", "Tags": [ "go", "mongodb" ], "Title": "Check mongodb status is running or not" }
212538
<p>I have a task to write the function: <code>int read_palindrome(); // input comes from stdin</code></p> <p>which will read one line from standard input and returns 1 if the line is a palindrome and 0 otherwise. A line is terminated by the newline character (’\n’) and the does not include the newline. </p> <p>There are requirements to be met:</p> <p>There is no assumption about the length of the input. You are also not allowed to read the input twice, e.g. read the input, forget you read the input but remember the length, read the input again. which results in the input being read twice. </p> <p>You are also not allowed to create a very large buffer to store the input reasoning that the input line might be expected to be smaller than a very large buffer. The reason for this restriction is that we will consider the memory usage of the program. </p> <p>The task is to come out with a correct program with the best CPU time and memory usage.</p> <p>I have attempted my code below. May I know if there is anything I could improve on here to optimise for correctness, CPU and memory?</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;stdio.h&gt; int read_palindrome(); int check_palindrome2(char *, int); int main() { if (read_palindrome()) printf("input is a palindrome"); else printf("input is not a palindrome"); return 0; } int read_palindrome() { unsigned int len_max = 128; unsigned int current_size = 0; char *pStr = malloc(len_max); current_size = len_max; int i; char c; if (pStr != NULL) { while (( c = getchar() ) != '\n') { pStr[i] = (char)c; i++; if(i == current_size) { current_size = i+len_max; pStr = realloc(pStr, current_size); } } pStr[i] = '\0'; free(pStr); } return check_palindrome2(pStr,i); } int check_palindrome2(char *s, int length) { for (int i = 0; i &lt; length; i++) { if (s[i]!= s[length-i-1]) { return 0; } } return 1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T14:46:19.523", "Id": "411135", "Score": "0", "body": "In `check_palindrome2()`, you only need to perform the comparison until `length/2`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T14:55:23.587", "Id": "411138", "Score": "0", "body": "@Damien ok, noted, anything else?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T15:02:15.390", "Id": "411139", "Score": "1", "body": "To read, `fgets()` may be more efficient. To be tested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T22:48:20.607", "Id": "411218", "Score": "0", "body": "@Damien Comments are for seeking clarification to the question, and may be deleted. Please put all suggestions for improvements in answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T09:01:34.343", "Id": "411257", "Score": "0", "body": "@200_success Until now, I mainly contributed to SO. There, partial answers are very rapidly downvoted! I had to suppress some of my answers. Usage may be different on this site as the kind of question (\"how to improve ...\") is different. Anyway, i tried to develop my comments and proposed an answer as you suggested" } ]
[ { "body": "<ul>\n<li><p><code>free(pStr)</code> is misplaced. Once it is freed, you may not touch it anymore. Calling <code>check_palindrome2(pStr)</code> after freeing causes an undefined behavior.</p>\n\n<p>Consider</p>\n\n<pre><code> int rc = check_palindrome2(pStr, i);\n free(pStr);\n return rc;\n</code></pre></li>\n<li><p><code>check_palindrome2</code> could be called with a null pointer, but doesn't test it.</p></li>\n<li><p><code>current_size += len_max</code> is more clear than <code>current_size = i+len_max</code>.</p></li>\n<li><p><code>read_palindrome</code> is a misnomer. It doesn't read a <em>palindrome</em>. It reads a string of an unknown length. Now, SRP mandates splitting it into independent <code>read_line</code> and <code>is_palindrome</code> functions.</p></li>\n<li><p>You test <code>malloc</code> for a failure. Keep in mind that <code>realloc</code> may fail as well.</p>\n\n<pre><code> char * tmp = realloc(....);\n if (tmp == NULL) {\n free(pStr);\n return error;\n }\n pStr = tmp;\n</code></pre>\n\n<p>NB: a simple <code>pStr = realloc(....)</code> is not good. If realloc fails, you'd have a memory leak.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:08:27.737", "Id": "411165", "Score": "0", "body": "for `read_palindrome`, I can't change the function because the driver code was provided and I have to implement `read_palindrome` according to the signature, not sure if the rest of the things depend on that flaw." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:30:02.237", "Id": "411170", "Score": "0", "body": "@PrashinJeevaganth That's unfortunate. The third bullet is not applicable. Still keep it in mind." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:34:05.993", "Id": "411172", "Score": "0", "body": "so are you suggesting that `free(pStr)` should not be placed? I'm not sure of its application as I always see `malloc` and `free`in pairs. And how would you recommend accounting for `realloc` fails" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:38:21.583", "Id": "411175", "Score": "0", "body": "@PrashinJeevaganth See edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:42:51.187", "Id": "411178", "Score": "0", "body": "Just to clarify, when you meant `check_palindrome2` should handle a null pointer, do u mean I should include a line `if (s==NULL)` return 0`?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:50:55.497", "Id": "212562", "ParentId": "212548", "Score": "3" } }, { "body": "<p>A first point concern palindrome checking. In <code>check_palindrome2()</code>, you only need to perform the comparison until <code>length/2</code>.<br>\nFrom a performance point of view, this part is unlikely to be critical compared to the other ones. However, if it is a homework, useless to stress your Professor. </p>\n\n<p>A critical point concerns the number of reallocation, which clearly decreases the time efficiency of your programme. You cannot avoid it as memory usage is an important criteria according to the requirements. Effectively, allocating a buffer of some Mbytes to read a few bytes is wasting memory. However, increasing memory size by step of 128 bytes to read 1 Gbytes is really not efficient. It is such a situation when one has to find the best trade-off between time efficiency and memory efficiency. One possibility is to make this trade-off <em>adaptive</em>. You start with a small increment (128 in your program), as you did, but then, if you detect that too many reallocations occur, you increase the increment, for example by doubling it. You can do it several times. Maybe pay attention to set a maximum value of this increment. </p>\n\n<p>Another critical point is the efficiency of reading the input. You do it character per character. It may be more efficient to read <code>n</code> characters in a raw, for example with <code>fgets()</code>. Pay attention in this case that in the last reading, it is likely that you will read less than <code>n</code> characters. You will have to test it carefully. </p>\n\n<p>Last but not least, pay attention to avoid memory leakage or premature <code>free</code>. This point was clearly stated in the previous answer. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T21:37:10.893", "Id": "411344", "Score": "0", "body": "Note: `fgets()` has its corner weaknesses 1) Code certainly needs to walk it to find strings length. 2) It uses a size of type `int` which is problematic for _huge_ strings when using robust `size_t` dynamically as you suggest. 3) Should input unexpectedly include a _null character_, `fgets()` affords no ready solution to its detection." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T21:51:12.443", "Id": "411349", "Score": "0", "body": "@chux Note that we don't have a lot of information about the kind of data to deal with. Concerning the dynamic increase of the increment, my concern was the number of reallocations. Even if this increment is huge, we can continue to read a reasonable number of characters in a row. This being said, I agree with the difficulty to use `fgets()`. Maybe overskilled for this problem" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T08:57:42.673", "Id": "212610", "ParentId": "212548", "Score": "2" } }, { "body": "<p>\"There is no assumption about the length of the input.\" is not reasonable - there is alwasy some reasonable limiting factor - perhaps more than <code>UINT_MAX</code>.</p>\n\n<p>This code assumes <code>current_size &lt;= UINT_MAX</code> by using <code>unsigned</code>.</p>\n\n<p>Using <code>size_t</code> would make more sense as that is the type used by <code>*alloc()</code> and the right-size type for array indexing/pointer math.</p>\n\n<pre><code>// unsigned int len_max = 128;\n// unsigned int current_size = 0;\nsize_t len_max = 128;\nsize_t current_size = 0;\n</code></pre>\n\n<hr>\n\n<p><strong>Use _Bool for boolean functions</strong></p>\n\n<pre><code>// int check_palindrome2(char *s, int length) {\n_Bool check_palindrome2(char *s, int length) {\n// or with &lt;stdbool.h&gt;\nbool check_palindrome2(char *s, int length) {\n</code></pre>\n\n<hr>\n\n<p><strong>Use <code>const</code></strong></p>\n\n<p>For referenced data that does not change, use <code>const</code> for potential optimizations , wider code application and function clarity.</p>\n\n<pre><code>// int check_palindrome2(char *s, int length) {\nint check_palindrome2(const char *s, int length) {\n</code></pre>\n\n<hr>\n\n<p><strong>Double loop check speed</strong></p>\n\n<p>Perform <code>length/2</code> checks, not <code>length</code> checks as in <code>for (int i = 0; i &lt; length; i++)</code></p>\n\n<p>With above improvements: </p>\n\n<pre><code>#include &lt;stdbool.h&gt;\n\nbool check_palindrome2(const char *s, size_t length) {\n const char *end = s + length;\n while (end &gt; s) {\n end--;\n if (*end != *s) {\n return false;\n }\n s++;\n }\n return true;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T21:07:06.330", "Id": "212654", "ParentId": "212548", "Score": "0" } }, { "body": "<p>You are storing characters in a string, and then checking them for being a palindrome. This is CPU efficient, but memory inefficient.</p>\n\n<p>To store a palindrome really only requires at most <code>n/2 + 2</code> characters, maximum (for odd length palindromes, <code>n/2 + 1</code> for evens). If you check each character input against (*note) <code>str[-1]</code> (even) and <code>str[-2]</code> (odd), you could track how many duplicate characters you had seen, and only lengthen the string on a mismatch.</p>\n\n<p>(*note: using Perl/Python notation that <code>str[-1]</code> is last character in <code>str,</code> etc.)</p>\n\n<p>This would take more CPU, but would save memory in the case of very long palindromes.</p>\n\n<p>For example, with the odd palindrome <strong>abcba</strong> you only need to store the <strong>abc</strong> string. The rest could be comparisons going backwards until you reach start-of-string and <code>'\\n'</code> at the same time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T23:17:07.447", "Id": "212663", "ParentId": "212548", "Score": "0" } } ]
{ "AcceptedAnswerId": "212562", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T13:43:02.943", "Id": "212548", "Score": "1", "Tags": [ "c", "strings", "palindrome", "memory-optimization" ], "Title": "Read a palindrome of unknown length" }
212548
<p>I programmed a chess AI in Python. It uses the alpha-beta algorithm with move ordering. I want it to be able to look further than depth 4, without increasing calculation time. I am wondering how I possibly could improve the efficiency of my code. I have a feeling that my code does a lot of unnecessary calculations.</p> <pre><code>king1_moved = False king2_moved = False rook1_left = False rook1_right = False rook2_left = False rook2_right = False iteration = 0 def game(): board = create_starting_board() player1_pawn_promotion_line = [26, 27, 28, 29, 30, 31, 32, 33] print_board(board) print("") print("") while True: castling = "" # castling: if board[110] == "r-1" and board[111] == " 0 " and board[112] == " 0 " and board[113] == " 0 " \ and board[114] == "k-1": castling = input("Do you want to castle?") if castling == "y": x_piece = int(input("x_piece:")) y_piece = int(input("y_piece:")) x_move = int(input("x_move:")) y_move = int(input("y_move:")) piece_pos = (109 + x_piece) - (y_piece - 1) * 12 move_pos = (109 + x_move) - (y_move - 1) * 12 board[move_pos] = board[piece_pos] board[piece_pos] = " 0 " x_piece = int(input("x_piece:")) y_piece = int(input("y_piece:")) x_move = int(input("x_move:")) y_move = int(input("y_move:")) piece_pos = (109 + x_piece) - (y_piece - 1) * 12 move_pos = (109 + x_move) - (y_move - 1) * 12 board[move_pos] = board[piece_pos] board[piece_pos] = " 0 " if board[117] == "r-1" and board[116] == " 0 " and board[115] == " 0 " and board[114] == "k-1": castling = input("Do you want to castle?") if castling == "y": x_piece = int(input("x_piece:")) y_piece = int(input("y_piece:")) x_move = int(input("x_move:")) y_move = int(input("y_move:")) piece_pos = (109 + x_piece) - (y_piece - 1) * 12 move_pos = (109 + x_move) - (y_move - 1) * 12 board[move_pos] = board[piece_pos] board[piece_pos] = " 0 " x_piece = int(input("x_piece:")) y_piece = int(input("y_piece:")) x_move = int(input("x_move:")) y_move = int(input("y_move:")) piece_pos = (109 + x_piece) - (y_piece - 1) * 12 move_pos = (109 + x_move) - (y_move - 1) * 12 board[move_pos] = board[piece_pos] board[piece_pos] = " 0 " if castling != "y": x_piece = int(input("x_piece:")) y_piece = int(input("y_piece:")) x_move = int(input("x_move:")) y_move = int(input("y_move:")) piece_pos = (109 + x_piece) - (y_piece - 1) * 12 move_pos = (109 + x_move) - (y_move - 1) * 12 board[move_pos] = board[piece_pos] board[piece_pos] = " 0 " if "p-1" in board: if board.index("p-1") in player1_pawn_promotion_line: board[move_pos] = "q-1" # check if king/queen has moved: global king1_moved, rook1_right, rook1_left if board[move_pos] == "k-1": king1_moved = False elif board[move_pos] == "r-1" and piece_pos == 110: rook1_left = False elif board[move_pos] == "r-1" and piece_pos == 117: rook1_right = False print_board(board) print("") print("") maximize(board, -1, 4, -100000, 100000) def sort_moves(scores, piece_positions, possible_moves, player): where_did_items_go = [] if player == 1: sorted_scores = sorted(scores, reverse=True) else: sorted_scores = sorted(scores, reverse=False) for item in scores: num = sorted_scores.index(item) while num in where_did_items_go: num += 1 where_did_items_go.append(num) piece = [x for _, x in sorted(zip(where_did_items_go, piece_positions))] possible = [x for _, x in sorted(zip(where_did_items_go, possible_moves))] return piece, possible def maximize(board, player, depth, alpha, beta): max_depth = 4 player2_pawn_promotion_line = [110, 111, 112, 113, 114, 115, 116, 117] pos = -1 if depth == 0: return evaluation(board) max_value = alpha positions, moves = find_all_possible_moves(board, player) for move in moves: pawn_promotion = False global iteration iteration += 1 pos += 1 # perform move if isinstance(move, int): piece = board[move] board[move] = board[positions[pos]] board[positions[pos]] = " 0 " # pawn promotion if "p-2" in board: if player == -1 and board.index("p-2") in player2_pawn_promotion_line: board[move] = "q-2" pawn_promotion = True value = minimize(board, player * -1, depth - 1, max_value, beta) # reverse move if not pawn_promotion: board[positions[pos]] = board[move] board[move] = piece else: board[positions[pos]] = "p-2" board[move] = piece else: piece_1 = board[move[0]] piece_2 = board[move[1]] board[move[0]] = board[positions[pos][0]] board[move[1]] = board[positions[pos][1]] board[positions[pos][0]] = " 0 " board[positions[pos][1]] = " 0 " value = minimize(board, player * -1, depth - 1, max_value, beta) # reverse move board[positions[pos][0]] = board[move[0]] board[positions[pos][1]] = board[move[1]] board[move[0]] = piece_1 board[move[1]] = piece_2 if value &gt;= max_value: max_value = value best_move = move best_piece = positions[pos] if max_value &gt;= beta: break if depth == max_depth: # perform move + check if kings/rooks moved if moves == []: print("Check_Mate: You won!") exit() if isinstance(best_move, int): board[best_move] = board[best_piece] board[best_piece] = " 0 " # pawn promotion if "p-2" in board: if board.index("p-2") in player2_pawn_promotion_line: board[best_move] = "q-2" # check if king/queen has moved: global king2_moved, rook2_right, rook2_left if board[best_move] == "k-2": king2_moved = True elif board[best_move] == "r-2" and best_piece == 26: rook2_left = True elif board[best_move] == "r-2" and best_piece == 33: rook2_right = True else: board[best_move[0]] = board[best_piece[0]] board[best_move[1]] = board[best_piece[1]] board[best_piece[0]] = " 0 " board[best_piece[1]] = " 0 " print_board(board) print(max_value) print(iteration) print("") print("") return max_value def minimize(board, player, depth, alpha, beta): player1_pawn_promotion_line = [26, 27, 28, 29, 30, 31, 32, 33] pos = -1 if depth == 0: return evaluation(board) min_value = beta positions, moves = find_all_possible_moves(board, player) for move in moves: global iteration iteration += 1 pawn_promotion = False pos += 1 # perform move if isinstance(move, int): piece = board[move] board[move] = board[positions[pos]] board[positions[pos]] = " 0 " # pawn promotion if "p-1" in board: if player == 1 and board.index("p-1") in player1_pawn_promotion_line: board[move] = "q-1" pawn_promotion = True value = maximize(board, player * -1, depth - 1, alpha, min_value) # reverse move if not pawn_promotion: board[positions[pos]] = board[move] board[move] = piece else: board[positions[pos]] = "p-1" board[move] = piece else: piece_1 = board[move[0]] piece_2 = board[move[1]] board[move[0]] = board[positions[pos][0]] board[move[1]] = board[positions[pos][1]] board[positions[pos][0]] = " 0 " board[positions[pos][1]] = " 0 " value = maximize(board, player * -1, depth - 1, alpha, min_value) # reverse move board[positions[pos][0]] = board[move[0]] board[positions[pos][1]] = board[move[1]] board[move[0]] = piece_1 board[move[1]] = piece_2 if value &lt; min_value: min_value = value if min_value &lt;= alpha: break return min_value def evaluation(board): # simple material_count king = 3600 queen = 360 rook = 200 bishop = 120 knight = 120 pawn = 40 value = 0 search_range = [26, 27, 28, 29, 30, 31, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 50, 51, 52, 53, 54, 55, 56, 57, 62, 63, 64, 65, 66, 67, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 98, 99, 100, 101, 102, 103, 104, 105, 110, 111, 112, 113, 114, 115, 116, 117] prawn_table_AI = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 5,-10,-10, 5, 10, 10, 0, 0, 0, 0, 5, 0, 5, 0, 0, 5, 0, 5, 0, 0, 0, 0, 0, 0, 5, 20, 20, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 10, 10, 5, 5, 5, 0, 0, 0, 0, 10, 10, 10, 20, 20, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] knight_table_AI = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -10, 0, 0, 0, 0, -10, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, 15, 15, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, 15, 15, 10, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] bishop_table_AI = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -10, 0, 0, -10, 0, 0, 0, 0, 0, 0,0, 0, 0, 5, 5, 0, 0, 0, 0, 0, 0, 0,0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0,0, 5, 10, 15, 15, 10, 5, 0, 0, 0, 0, 0,0, 5, 10, 15, 15, 10, 5, 0, 0, 0, 0, 0,0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0,0, 0, 0, 5, 5, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] rook_table_AI = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] prawn_table_H = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 20, 20, 10, 10, 10, 0, 0, 0, 0, 5, 5, 5, 10, 10, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 20, 20, 5, 0, 0, 0, 0, 0, 0, 5, 0, 5, 0, 0, 5, 0, 5, 0, 0, 0, 0, 10, 10, 5, -10, -10, 5, 10, 10, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] knight_table_H = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, 10, 15, 15, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, 15, 15, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, -10, 0, 0, 0, 0, -10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,] bishop_table_H = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 5, 10, 15, 15, 10, 5, 0, 0, 0, 0, 0, 0, 5, 10, 15, 15, 10, 5, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, -10, 0, 0, -10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] rook_table_H = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # material_score for square in search_range: if "1" in board[square]: player_string = "1" player_int = -1 else: player_string = "2" player_int = 1 if "p-" + player_string in board[square]: value = value + player_int * pawn if "n-" + player_string in board[square]: value = value + player_int * knight if "b-" + player_string in board[square]: value = value + player_int * bishop if "r-" + player_string in board[square]: value = value + player_int * rook if "q-" + player_string in board[square]: value = value + player_int * queen if "k-" + player_string in board[square]: value = value + player_int * king # position score for square in search_range: if "1" in board[square]: if "p" in board[square]: value -= prawn_table_H[square] if "b" in board[square]: value -= bishop_table_H[square] if "n" in board[square]: value -= knight_table_H[square] if "r" in board[square]: value -= rook_table_H[square] else: if "p" in board[square]: value += prawn_table_AI[square] if "b" in board[square]: value += bishop_table_AI[square] if "n" in board[square]: value += knight_table_AI[square] if "r" in board[square]: value += rook_table_AI[square] # Castling if board[31] == "r-2" and board[32] == "k-2": value += 4 if board[29] == "r-2" and board[28] == "k-2": value += 4 if board[115] == "r-1" and board[116] == "k-1": value -= 4 if board[113] == "r-1" and board[112] == "k-1": value -= 4 return value def create_starting_board(): board = ["x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "r-2", "n-2", "b-2", "q-2", "k-2", "b-2", "n-2", "r-2", "x", "x", "x", "x", "p-2", "p-2", "p-2", "p-2", "p-2", "p-2", "p-2", "p-2", "x", "x", "x", "x", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", "x", "x", "x", "x", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", "x", "x", "x", "x", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", "x", "x", "x", "x", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", "x", "x", "x", "x", "p-1", "p-1", "p-1", "p-1", "p-1", "p-1", "p-1", "p-1", "x", "x", "x", "x", "r-1", "n-1", "b-1", "q-1", "k-1", "b-1", "n-1", "r-1", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x"] return board def print_board(board): for i in range(8): if i &gt; 0: print("---------------------------------") print("¦" + board[26 + i * 12] + "¦" + board[12 * i + 27] + "¦" + board[12 * i + 28] + "¦" + board[ i * 12 + 29] + "¦" + board[12 * i + 30] + "¦" + board[12 * i + 31] + "¦" + board[12 * i + 32] + "¦" + board[12 * i + 33] + "¦") def king_exists(board, player): search_range = [26, 27, 28, 29, 30, 31, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 50, 51, 52, 53, 54, 55, 56, 57, 62, 63, 64, 65, 66, 67, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 98, 99, 100, 101, 102, 103, 104, 105, 110, 111, 112, 113, 114, 115, 116, 117] if player == 1: player_string = "1" else: player_string = "2" for i in search_range: if "k-" + player_string in board[i]: return True return False def king_under_attack(board, player): position, moves = make_all_next_moves(board, player * -1) pos = -1 player1_pawn_promotion_line = [26, 27, 28, 29, 30, 31, 32, 33] player2_pawn_promotion_line = [110, 111, 112, 113, 114, 115, 116, 117] # perform all moves and check if in one of the moves the king doesn't exist, if true, then the king is under check # in the current board_state for move in moves: pawn_promotion = False pos += 1 if isinstance(move, int): piece = board[move] board[move] = board[position[pos]] board[position[pos]] = " 0 " # pawn promotion if "p-1" in board: if player == 1 and board.index("p-1") in player1_pawn_promotion_line: board[move] = "q-1" pawn_promotion = True if "p-2" in board: if player == -1 and board.index("p-2") in player2_pawn_promotion_line: board[move] = "q-2" pawn_promotion = True if not king_exists(board, player): # reverse move if not pawn_promotion: board[position[pos]] = board[move] board[move] = piece else: if player == 1: board[position[pos]] = "p-1" board[move] = piece else: board[position[pos]] = "p-2" board[move] = piece return True # reverse move if not pawn_promotion: board[position[pos]] = board[move] board[move] = piece else: if player == 1: board[position[pos]] = "p-1" board[move] = piece else: board[position[pos]] = "p-2" board[move] = piece else: piece_1 = board[move[0]] piece_2 = board[move[1]] board[move[0]] = board[position[pos][0]] board[move[1]] = board[position[pos][1]] board[position[pos][0]] = " 0 " board[position[pos][1]] = " 0 " if not king_exists(board, player): # reverse move board[position[pos][0]] = board[move[0]] board[position[pos][1]] = board[move[1]] board[move[0]] = piece_1 board[move[1]] = piece_2 return True # reverse move board[position[pos][0]] = board[move[0]] board[position[pos][1]] = board[move[1]] board[move[0]] = piece_1 board[move[1]] = piece_2 return False def make_all_next_moves(board, player): possible_moves = [] piece_position = [] search_range = [26, 27, 28, 29, 30, 31, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 50, 51, 52, 53, 54, 55, 56, 57, 62, 63, 64, 65, 66, 67, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 98, 99, 100, 101, 102, 103, 104, 105, 110, 111, 112, 113, 114, 115, 116, 117] pawn1_start = [98, 99, 100, 101, 102, 103, 104, 105] pawn2_start = [38, 39, 40, 41, 42, 43, 44, 45] if player == 1: player_string = "1" attack_player = "2" pawn_starting_positions = pawn1_start else: player_string = "2" attack_player = "1" pawn_starting_positions = pawn2_start # find all possible moves with pawn, bishop, knight, rook, queen and king for i in search_range: # pawn if "p-" + player_string in board[i]: # pawn_forward if board[i - player * 12] == " 0 ": piece_position.append(i) possible_moves.append(i - player * 12) # pawn_right if attack_player in board[i - player * 11]: piece_position.append(i) possible_moves.append(i - player * 11) # pawn_left if attack_player in board[i - player * 13]: piece_position.append(i) possible_moves.append(i - player * 13) # pawn_two_forward if board[i - player * 24] == " 0 " and board[i - player * 12] == " 0 " and i in pawn_starting_positions: piece_position.append(i) possible_moves.append(i - player * 24) # bishop if "b-" + player_string in board[i]: # bishop_up_right x = i while True: x = x - 11 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # bishop_up_left x = i while True: x = x - 13 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # bishop_down_left x = i while True: x = x + 11 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # bishop_down_right x = i while True: x = x + 13 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # knight if "n-" + player_string in board[i]: # 8 cases if " 0 " in board[i - 23] or attack_player in board[i - 23]: piece_position.append(i) possible_moves.append(i - 23) if " 0 " in board[i - 25] or attack_player in board[i - 25]: piece_position.append(i) possible_moves.append(i - 25) if " 0 " in board[i - 10] or attack_player in board[i - 10]: piece_position.append(i) possible_moves.append(i - 10) if " 0 " in board[i - 14] or attack_player in board[i - 14]: piece_position.append(i) possible_moves.append(i - 14) if " 0 " in board[i + 23] or attack_player in board[i + 23]: piece_position.append(i) possible_moves.append(i + 23) if " 0 " in board[i + 25] or attack_player in board[i + 25]: piece_position.append(i) possible_moves.append(i + 25) if " 0 " in board[i + 10] or attack_player in board[i + 10]: piece_position.append(i) possible_moves.append(i + 10) if " 0 " in board[i + 14] or attack_player in board[i + 14]: piece_position.append(i) possible_moves.append(i + 14) # rook if "r-" + player_string in board[i]: # rook_up x = i while True: x = x - 12 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # rook_down x = i while True: x = x + 12 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # rook_right x = i while True: x = x + 1 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # rook_left x = i while True: x = x - 1 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # queen if "q-" + player_string in board[i]: # queen_up x = i while True: x = x - 12 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # queen_down x = i while True: x = x + 12 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # queen_right x = i while True: x = x + 1 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # queen_left x = i while True: x = x - 1 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # queen_up_right x = i while True: x = x - 11 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # queen_up_left x = i while True: x = x - 13 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # queen_down_left x = i while True: x = x + 11 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # queen_down_right x = i while True: x = x + 13 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # king if "k-" + player_string in board[i]: # king_up if " 0 " in board[i - 12] or attack_player in board[i - 12]: piece_position.append(i) possible_moves.append(i - 12) # king_down if " 0 " in board[i + 12] or attack_player in board[i + 12]: piece_position.append(i) possible_moves.append(i + 12) # king_right if " 0 " in board[i + 1] or attack_player in board[i + 1]: piece_position.append(i) possible_moves.append(i + 1) # king_left if " 0 " in board[i - 1] or attack_player in board[i - 1]: piece_position.append(i) possible_moves.append(i - 1) # king_up_right if " 0 " in board[i - 11] or attack_player in board[i - 11]: piece_position.append(i) possible_moves.append(i - 11) # king_up_left if " 0 " in board[i - 13] or attack_player in board[i - 13]: piece_position.append(i) possible_moves.append(i - 13) # king_down_right if " 0 " in board[i + 11] or attack_player in board[i + 11]: piece_position.append(i) possible_moves.append(i + 11) # king_down_left if " 0 " in board[i + 13] or attack_player in board[i + 13]: piece_position.append(i) possible_moves.append(i + 13) # Castling global king1_moved, king2_moved, rook1_left, rook1_right, rook2_left, rook2_right if player == 1 and not king1_moved: # 2 castling options if board[110] == "r-1" and board[111] == " 0 " and board[112] == " 0 " \ and board[113] == " 0 " and board[114] == "k-1" and not rook1_left: piece_position.append([114, 110]) possible_moves.append([112, 113]) if board[117] == "r-1" and board[116] == " 0 " and board[115] == " 0 " \ and board[114] == "k-1" and not rook1_right: piece_position.append([114, 117]) possible_moves.append([116, 115]) if player == -1 and not king2_moved: # 2 castling options if board[26] == "r-2" and board[27] == " 0 " and board[28] == " 0 " \ and board[29] == " 0 " and board[30] == "k-2" and not rook2_left: piece_position.append([30, 26]) possible_moves.append([28, 29]) if board[33] == "r-2" and board[32] == " 0 " and board[31] == " 0 " \ and board[30] == "k-2" and not rook2_right: piece_position.append([30, 33]) possible_moves.append([32, 31]) # En passe --&gt; maybe add it later on (a bit unnessecary but okay i guess i'll just add it later) return piece_position, possible_moves def find_all_possible_moves(board, player): possible_moves = [] piece_position = [] search_range = [26, 27, 28, 29, 30, 31, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 50, 51, 52, 53, 54, 55, 56, 57, 62, 63, 64, 65, 66, 67, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91, 92, 93, 98, 99, 100, 101, 102, 103, 104, 105, 110, 111, 112, 113, 114, 115, 116, 117] pawn1_start = [98, 99, 100, 101, 102, 103, 104, 105] pawn2_start = [38, 39, 40, 41, 42, 43, 44, 45] if player == 1: player_string = "1" attack_player = "2" pawn_starting_positions = pawn1_start else: player_string = "2" attack_player = "1" pawn_starting_positions = pawn2_start # find all possible moves with pawn, bishop, knight, rook, queen and king for i in search_range: # pawn if "p-" + player_string in board[i]: # pawn_forward if board[i - player * 12] == " 0 ": piece_position.append(i) possible_moves.append(i - player * 12) # pawn_right if attack_player in board[i - player * 11]: piece_position.append(i) possible_moves.append(i - player * 11) # pawn_left if attack_player in board[i - player * 13]: piece_position.append(i) possible_moves.append(i - player * 13) # pawn_two_forward if board[i - player * 24] == " 0 " and board[i - player * 12] == " 0 " and i in pawn_starting_positions: piece_position.append(i) possible_moves.append(i - player * 24) # bishop if "b-" + player_string in board[i]: # bishop_up_right x = i while True: x = x - 11 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # bishop_up_left x = i while True: x = x - 13 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # bishop_down_left x = i while True: x = x + 11 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # bishop_down_right x = i while True: x = x + 13 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # knight if "n-" + player_string in board[i]: # 8 cases if " 0 " in board[i - 23] or attack_player in board[i - 23]: piece_position.append(i) possible_moves.append(i - 23) if " 0 " in board[i - 25] or attack_player in board[i - 25]: piece_position.append(i) possible_moves.append(i - 25) if " 0 " in board[i - 10] or attack_player in board[i - 10]: piece_position.append(i) possible_moves.append(i - 10) if " 0 " in board[i - 14] or attack_player in board[i - 14]: piece_position.append(i) possible_moves.append(i - 14) if " 0 " in board[i + 23] or attack_player in board[i + 23]: piece_position.append(i) possible_moves.append(i + 23) if " 0 " in board[i + 25] or attack_player in board[i + 25]: piece_position.append(i) possible_moves.append(i + 25) if " 0 " in board[i + 10] or attack_player in board[i + 10]: piece_position.append(i) possible_moves.append(i + 10) if " 0 " in board[i + 14] or attack_player in board[i + 14]: piece_position.append(i) possible_moves.append(i + 14) # rook if "r-" + player_string in board[i]: # rook_up x = i while True: x = x - 12 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # rook_down x = i while True: x = x + 12 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # rook_right x = i while True: x = x + 1 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # rook_left x = i while True: x = x - 1 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # queen if "q-" + player_string in board[i]: # queen_up x = i while True: x = x - 12 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # queen_down x = i while True: x = x + 12 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # queen_right x = i while True: x = x + 1 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # queen_left x = i while True: x = x - 1 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # queen_up_right x = i while True: x = x - 11 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # queen_up_left x = i while True: x = x - 13 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # queen_down_left x = i while True: x = x + 11 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # queen_down_right x = i while True: x = x + 13 if board[x] == " 0 ": piece_position.append(i) possible_moves.append(x) elif attack_player in board[x]: piece_position.append(i) possible_moves.append(x) break else: break # king if "k-" + player_string in board[i]: # king_up if " 0 " in board[i - 12] or attack_player in board[i - 12]: piece_position.append(i) possible_moves.append(i - 12) # king_down if " 0 " in board[i + 12] or attack_player in board[i + 12]: piece_position.append(i) possible_moves.append(i + 12) # king_right if " 0 " in board[i + 1] or attack_player in board[i + 1]: piece_position.append(i) possible_moves.append(i + 1) # king_left if " 0 " in board[i - 1] or attack_player in board[i - 1]: piece_position.append(i) possible_moves.append(i - 1) # king_up_right if " 0 " in board[i - 11] or attack_player in board[i - 11]: piece_position.append(i) possible_moves.append(i - 11) # king_up_left if " 0 " in board[i - 13] or attack_player in board[i - 13]: piece_position.append(i) possible_moves.append(i - 13) # king_down_right if " 0 " in board[i + 11] or attack_player in board[i + 11]: piece_position.append(i) possible_moves.append(i + 11) # king_down_left if " 0 " in board[i + 13] or attack_player in board[i + 13]: piece_position.append(i) possible_moves.append(i + 13) # Castling global king1_moved, king2_moved, rook1_left, rook1_right, rook2_left, rook2_right if not king_under_attack(board, player): if player == 1 and not king1_moved: # 2 castling options if board[110] == "r-1" and board[111] == " 0 " and board[112] == " 0 " \ and board[113] == " 0 " and board[114] == "k-1" and not rook1_left: piece_position.append([114, 110]) possible_moves.append([112, 113]) if board[117] == "r-1" and board[116] == " 0 " and board[115] == " 0 " \ and board[114] == "k-1" and not rook1_right: piece_position.append([114, 117]) possible_moves.append([116, 115]) if player == -1 and not king2_moved: # 2 castling options if board[26] == "r-2" and board[27] == " 0 " and board[28] == " 0 " \ and board[29] == " 0 " and board[30] == "k-2" and not rook2_left: piece_position.append([30, 26]) possible_moves.append([28, 29]) if board[33] == "r-2" and board[32] == " 0 " and board[31] == " 0 " \ and board[30] == "k-2" and not rook2_right: piece_position.append([30, 33]) possible_moves.append([32, 31]) scores = [] player1_pawn_promotion_line = [26, 27, 28, 29, 30, 31, 32, 33] player2_pawn_promotion_line = [110, 111, 112, 113, 114, 115, 116, 117] for i in range(len(possible_moves) - 1, -1, -1): pawn_promotion = False deletion = False if isinstance(possible_moves[i], int): piece = board[possible_moves[i]] board[possible_moves[i]] = board[piece_position[i]] board[piece_position[i]] = " 0 " # pawn promotion if "p-1" in board: if player == 1 and board.index("p-1") in player1_pawn_promotion_line: board[possible_moves[i]] = "q-1" pawn_promotion = True if "p-2" in board: if player == -1 and board.index("p-2") in player2_pawn_promotion_line: board[possible_moves[i]] = "q-2" pawn_promotion = True if king_under_attack(board, player): deletion = True else: # add score for move ordering scores.append(evaluation(board)) # reverse move if not pawn_promotion: board[piece_position[i]] = board[possible_moves[i]] board[possible_moves[i]] = piece else: if player == 1: board[piece_position[i]] = "p-1" board[possible_moves[i]] = piece else: board[piece_position[i]] = "p-2" board[possible_moves[i]] = piece else: piece_1 = board[possible_moves[i][0]] piece_2 = board[possible_moves[i][1]] board[possible_moves[i][0]] = board[piece_position[i][0]] board[possible_moves[i][1]] = board[piece_position[i][1]] board[piece_position[i][0]] = " 0 " board[piece_position[i][1]] = " 0 " if king_under_attack(board, player): deletion = True else: # add score for move ordering scores.append(evaluation(board)) # reverse move board[piece_position[i][0]] = board[possible_moves[i][0]] board[piece_position[i][1]] = board[possible_moves[i][1]] board[possible_moves[i][0]] = piece_1 board[possible_moves[i][1]] = piece_2 if deletion: del possible_moves[i] del piece_position[i] # En passe --&gt; maybe add it later on (a bit unnecessary but okay i guess i'll just add it later) piece_position, possible_moves = sort_moves(scores, piece_position,possible_moves, player) return piece_position, possible_moves game() </code></pre> <p>Here is a description of how my program works:</p> <p>This is one of my first attempts on making a chess-AI. It uses alpha-beta pruning with move ordering. The program isn't finished, but it is already usable. It knows about pawn promotion and castling, but I haven't yet implemented En passet. It currently searches at a depth of 4. </p> <p>How to use it: When you start it up, the board will be printed out and the human starts playing with the white pieces. The human player has to enter the coordinates of the piece to move and after that, the coordinates where he wants to move the selected piece too (Unlike in the AI-functions I have currently not implemented a function, which would only allow legal moves by the human.) After that, the updated board is printed.</p> <pre><code>¦r-2¦n-2¦b-2¦q-2¦k-2¦b-2¦n-2¦r-2¦ --------------------------------- ¦p-2¦p-2¦p-2¦p-2¦p-2¦p-2¦p-2¦p-2¦ --------------------------------- ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ --------------------------------- ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ --------------------------------- ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ --------------------------------- ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ --------------------------------- ¦p-1¦p-1¦p-1¦p-1¦p-1¦p-1¦p-1¦p-1¦ --------------------------------- ¦r-1¦n-1¦b-1¦q-1¦k-1¦b-1¦n-1¦r-1¦ x_piece:4 y_piece:2 x_move:4 y_move:4 ¦r-2¦n-2¦b-2¦q-2¦k-2¦b-2¦n-2¦r-2¦ --------------------------------- ¦p-2¦p-2¦p-2¦p-2¦p-2¦p-2¦p-2¦p-2¦ --------------------------------- ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ --------------------------------- ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ --------------------------------- ¦ 0 ¦ 0 ¦ 0 ¦p-1¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ --------------------------------- ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ --------------------------------- ¦p-1¦p-1¦p-1¦ 0 ¦p-1¦p-1¦p-1¦p-1¦ --------------------------------- ¦r-1¦n-1¦b-1¦q-1¦k-1¦b-1¦n-1¦r-1¦ </code></pre> <p>Then, it's the AI's turn. It tries to find the best move with alpha-beta pruning (with move ordering). The evaluation function takes into consideration: the position of the pieces (with the help of hash tables) and material balance. When it finishes calculating, it performs the move and prints the updated board. Under the board, it spits out its predicted score and under that the number of chess boards it searched through:</p> <pre><code>¦r-2¦n-2¦b-2¦q-2¦k-2¦b-2¦n-2¦r-2¦ --------------------------------- ¦p-2¦p-2¦ 0 ¦p-2¦p-2¦p-2¦p-2¦p-2¦ --------------------------------- ¦ 0 ¦ 0 ¦p-2¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ --------------------------------- ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ --------------------------------- ¦ 0 ¦ 0 ¦ 0 ¦p-1¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ --------------------------------- ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ 0 ¦ --------------------------------- ¦p-1¦p-1¦p-1¦ 0 ¦p-1¦p-1¦p-1¦p-1¦ --------------------------------- ¦r-1¦n-1¦b-1¦q-1¦k-1¦b-1¦n-1¦r-1¦ 25 &lt;--- score prediction 141936 &lt;--- amount of searched chess boards </code></pre> <p>The goal with this project is to make an AI which outperforms decent chess players. I would like it to reach an ELO somewhere around 1600, but in order to do that, my number 1 priority is to improve the search depth. The problem with this is that it already takes an age to search at depth 4. I wonder if anyone could help me and point at some improvements I could make. My programming skills are quite basic and I probably should comment my code better.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:15:02.620", "Id": "411167", "Score": "0", "body": "Traditionally White and Black pieces are represented with upper- and lowercase letters respectively. `-1` and `-2` look noisy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T10:31:14.717", "Id": "411267", "Score": "0", "body": "Ah okay thanks, I'll probably be changing this sometime in the future." } ]
[ { "body": "<p>Your functions are really long. For example <code>game()</code> has 88 lines.</p>\n\n<p>Some parts are extracted (great!), for example <code>print_board()</code>. I would do the same for example with castling code that is really long and move it to its own function.</p>\n\n<p>Shorter function make analysis of code easier - it is much easier to notice mistakes.</p>\n\n<blockquote>\n <p>how I possibly could improve the efficiency of my code. I have a feeling that my code does a lot of unnecessary calculations.</p>\n</blockquote>\n\n<p>I would recommend using one of profilers (see <a href=\"https://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script\">https://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script</a> ) - special tools that report which functions are the most costly. It allows to spot functions where optimization will be useful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T10:33:08.413", "Id": "411268", "Score": "0", "body": "Thanks for your reply. I'll be making my functions as short as possible and then test it in the profilers you sent me. I am going to post the updated code later on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T13:07:33.310", "Id": "411285", "Score": "0", "body": "Note that you should not update code in this question but rather post a new question (and possibly select one of the answers here as accepted)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:19:34.767", "Id": "212567", "ParentId": "212554", "Score": "2" } } ]
{ "AcceptedAnswerId": "212567", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T15:14:50.933", "Id": "212554", "Score": "6", "Tags": [ "python", "performance", "ai", "chess" ], "Title": "Chess engine programmed in Python" }
212554
<p>This is a simple and clean script for sorting a specific column in a table. You could edit and parametrize it to add more customization, but I wanted to share the base concept.</p> <p>Base concept (I think its a pretty cool 3 line code):</p> <pre><code>t = document.getElementById('myTable'); [...t.tBodies[0].rows] //Transforming HTMLCollection to an Array .sort( (a,b) =&gt; a.cells[0].textContent &lt; b.cells[0].textContent) .forEach(r =&gt; t.tBodies[0].appendChild(r)) //Appending the rows themselves, so the table is reordered without needing to create any new element </code></pre> <p>Parametrization example: </p> <pre><code>function sortTableColumn(tableID, columnIndex){ t = document.getElementById(`#${tableID}`); [...t.tBodies[0].rows] .sort( (a,b) =&gt; a.cells[columnIndex].textContent &lt; b.cells[columnIndex].textContent) .forEach(r =&gt; t.tBodies[columnIndex].appendChild(r)) } </code></pre> <p>Concerns:</p> <ul> <li><p>Performance: is the use of spread operator ok here? Or is <code>Array.from</code> preferred?</p></li> <li><p>Visual sorting: Since you're re-appending each element one by one, in a large table the user would see the table arranging until it is done. I couldn't think of a way of "one shotting" the appending without affecting performance too much. Maybe adding a loading overlay is the best solution?</p></li> <li><p>What if we're dealing with a table with 1000+ records? What could go wrong?</p></li> </ul> <p>Fiddle: <a href="http://jsfiddle.net/ppgab/nu0q62br/22/" rel="nofollow noreferrer">http://jsfiddle.net/ppgab/nu0q62br/22/</a></p> <p>Table (any table with one body should work):</p> <pre class="lang-html prettyprint-override"><code> &lt;table id="myTable"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th scope="col"&gt;First&lt;/th&gt; &lt;th scope="col"&gt;Last&lt;/th&gt; &lt;th scope="col"&gt;Handle&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Mark&lt;/td&gt; &lt;td&gt;Otto&lt;/td&gt; &lt;td&gt;@mdo&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Jacob&lt;/td&gt; &lt;td&gt;Thornton&lt;/td&gt; &lt;td&gt;@fat&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Larry&lt;/td&gt; &lt;td&gt;the Bird&lt;/td&gt; &lt;td&gt;@twitter&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:02:29.210", "Id": "411145", "Score": "0", "body": "Can you add the html table example too :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:05:31.520", "Id": "411146", "Score": "1", "body": "@G.aziz sure, added the fiddle too" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-03T17:30:57.750", "Id": "411580", "Score": "0", "body": "*\"user would see the table arranging\"* ... not at all likely to be visible. For larger set will get better performance sorting outside the dom and replacing tbody all at one time" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-05T11:57:01.483", "Id": "411771", "Score": "0", "body": "@charlietfl yes but, is replacing the whole tbody at once better performance?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T15:59:00.403", "Id": "212557", "Score": "2", "Tags": [ "javascript", "ecmascript-6" ], "Title": "Simple table sorting using plain Javascript" }
212557
<p>I have a folder with zip files that contain CSVs for each day. Each CSV contains rows with IPs and a company ID. I want to calculate a distribution of the number of firms accessed. Meaning that I want to know how many users accessed only 1 firm, 2 firms and so on. </p> <p>The code asks for a specific date interval and then only selects those zips in the specified date interval. First I create a dataframe (<code>final_df</code>) that has 2 columns: n_firms and n_users by importing it from a CSV:</p> <pre><code>index n_firms n_users 0 1 0 1 2 0 ... ... ... </code></pre> <p>Then, the first <code>for</code> loop opens the zip file and reads the CSV and returns the CSV contents to <code>master_df</code>. Then I group by IPs because I have to count how many <strong>unique</strong> firms one specific user has accessed (the reason why I drop duplicates in the second <code>for</code> loop).</p> <p>Since the index is offset by 1 from the n_firms, I subtract 1 from the line of the unique firms the user accessed. Then it reads the previous value in the final_df corresponding to the number of firms accessed and adds 1 because now there is one extra user who accessed that number of firms. </p> <p>From what I can tell, the second <code>for</code> loop is slow and I want to know if there is some way I can improve that. </p> <p>My code is the following: </p> <pre><code>import pandas as pd import zipfile from tqdm import tqdm def _load_log_file(inputFile): colsToKeep = ['ip', 'cik'] # Open the raw compressed file from EDGAR with zipfile.ZipFile(inputFile, 'r') as zippedLogFile: # Archive contains a CSV plus a readme, get the CSV name for fn in zippedLogFile.namelist(): if '.csv' in fn: break logFile = pd.read_csv(zippedLogFile.open(fn, 'r'), usecols=colsToKeep) return logFile if __name__ == '__main__': print("Please enter start date: ") startdate = input() print("Please enter end date: ") enddate = input() final_df = pd.read_csv('D:/empty_df.csv') final_df.n_cik = final_df.n_cik.astype(int) print("length of the matrix: ", len(final_df.index)) path_to_zips = 'D:/SBP/{year}/Qtr{qtr}/log{year}{mnth:02d}{day:02d}.zip' dates = [(date.year, date.quarter, date.month, date.day) for date in pd.date_range(startdate, enddate)] logFilesToProcess = [path_to_zips.format(year=y, qtr=q, mnth=m, day=d) for y, q, m, d in dates] counter = 0 for each_zip_file in tqdm(logFilesToProcess): counter += 1 name = each_zip_file.split(".") name = name[0] name = name.split("/") name_csv = name[-1] master_df = _load_log_file(each_zip_file) master_df = master_df.groupby("ip") for item, df_ip in master_df: df_ip = df_ip.drop_duplicates(subset="cik", keep="first") number_of_firms = len(df_ip.index)-1 read_number = final_df.at[number_of_firms, 'n_users'] final_df.at[number_of_firms, 'n_users'] = read_number + 1 final_df.to_csv("D:/2004.csv", index=False) </code></pre> <p>Each CSV file looks like this (and I only keep the IP and the CIK= central index key. Each company has a unique CIK and you can use that number to search for the company's fillings on the securities and exchange comission website <strong><a href="https://www.sec.gov/edgar/searchedgar/companysearch.html" rel="nofollow noreferrer">https://www.sec.gov/edgar/searchedgar/companysearch.html</a></strong>):</p> <pre><code>ip date time zone cik 199.43.32.edd 03/01/2004 00:00:00 500 78890 67.82.239.bhe 03/01/2004 00:00:00 500 746838 67.82.239.bhe 03/01/2004 00:00:00 500 1001082 67.82.239.bhe 03/01/2004 00:00:00 500 746838 67.82.239.bhe 03/01/2004 00:00:00 500 752642 67.82.239.bhe 03/01/2004 00:00:00 500 1001082 151.196.250.ahd 03/01/2004 00:00:01 500 825411 208.61.82.abc 03/01/2004 00:00:01 500 106926 67.82.239.bhe 03/01/2004 00:00:01 500 82020 67.82.239.bhe 03/01/2004 00:00:01 500 1001082 67.82.239.bhe 03/01/2004 00:00:01 500 101829 67.82.239.bhe 03/01/2004 00:00:01 500 1001082 151.196.250.ahd 03/01/2004 00:00:02 500 825411 207.168.174.jdd 03/01/2004 00:00:02 500 714756 66.108.151.fgg 03/01/2004 00:00:02 500 1000180 </code></pre> <p>The first few lines from the 2003 CSV output is the following:</p> <pre><code>n_firms n_users 1 2392550 2 478414 3 205789 4 115967 5 73688 6 51690 7 37297 8 28025 9 21959 10 17480 11 14295 12 11983 13 9937 14 8513 15 7451 16 6611 17 5749 18 4991 19 4702 20 4001 21 3668 22 3330 23 2971 24 2638 25 2462 26 2338 27 2177 28 2006 </code></pre> <p>There are 2006 users in the year 2003 that accessed 28 unique firms in a day or there are 2392550 users in the year 2003 that accessed only 1 unique firm in a day.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:48:42.963", "Id": "411160", "Score": "0", "body": "It is not quite clear what is contained in those csv files and what you want in the end. Wouldn't it just be enough to count for each user how many unique companies they visited? Can you share an example csv file (obviously not with real user date, just some random one)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T08:29:56.060", "Id": "411252", "Score": "0", "body": "@Graipher I added an example of one of the CSV files. In the end, I want to know how many users have accessed 1 firm, 2 firms... 100 firms and so on. So I can make a distribution graph. I need to store the data into the `final_df` and then read from it and update the fields because the IPs are coded (the last 3 digits are replaced) and I have to do this for each day of the year." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T08:46:17.870", "Id": "411254", "Score": "0", "body": "Please add the data as text, otherwise we cannot use it to test our or your code. I'm not going to transcribe a hundred fields. What is a CIK? Company Identification K? When you say the last IP block is encoded, that encoding is unique for each number, right? How big are all CSV files together (would a concated dataframe fit into memory)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T08:56:06.333", "Id": "411255", "Score": "1", "body": "@Graipher Thank you for taking the time to look into my issue. I added the date as a text format. About the IP encoding.. what I know is that for each day they scramble randomly the last three digits with numbers. Meaning there is no way to track 1 ip from 1 day to another day.\n\nAll the CSV files together for one year add up to more than 60GB and even more for recent years where there is considerably more traffic..therefore making a dataframe that big is impossible (for my machine with 16GB of RAM)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T08:58:04.397", "Id": "411256", "Score": "0", "body": "So then you will not track the distribution of how many companies each unique user visited, but the distribution of how many unique companies each user visited within a day?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T09:02:31.450", "Id": "411258", "Score": "1", "body": "Yes. Sorry for not being clear enough. As you have said, I want to track the distribution of how many unique companies each user visited within a day." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T09:09:36.640", "Id": "411260", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/89055/discussion-between-adrian-and-graipher)." } ]
[ { "body": "<p>Getting the base name from a file is best done using either the <code>os</code> package or the <code>pathlib</code> package:</p>\n\n<pre><code>import os\nfrom pathlib import Path\n\npath = \"some/directory/file_name.csv\"\nprint(os.path.splitext(os.path.basename(path))[0])\n# file_name\nprint(Path(path).stem)\n# file_name\n</code></pre>\n\n<hr>\n\n<p>As for your inner loop, you can simplify getting the number of different companies visited by writing:</p>\n\n<pre><code>visits_distribution = master_df.groupby(\"ip\").cik.unique().apply(len)\n</code></pre>\n\n<p>Which will give you the distribution per user for that day:</p>\n\n<pre><code>ip\n151.196.250.ahd 1\n199.43.32.edd 1\n207.168.174.jdd 1\n208.61.82.abc 1\n66.108.151.fgg 1\n67.82.239.bhe 5\nName: cik, dtype: int64\n</code></pre>\n\n<p>On this you can just call <code>np.bincount</code>, which can take as an optional argument what the maximum number is supposed to be:</p>\n\n<pre><code>n = len(final_df.index)\nhist_on_day = np.bincount(visits_distribution, minlength=n)\n</code></pre>\n\n<p>Then you just need to sum all these arrays for every day, which eliminates the inner loop completely (by being done by <code>numpy</code>):</p>\n\n<pre><code>...\nn = len(final_df.index)\nfinal_hist = np.zeros(n)\n\nfor zip_file in tqdm(logFilesToProcess):\n name_csv = Path(zip_file).stem\n df = _load_log_file(each_zip_file)\n visits_distribution = df.groupby(\"ip\").cik.unique().apply(len)\n hist_on_day = np.bincount(visits_distribution, minlength=n)\n final_hist += hist_on_day\n\nfinal_df[\"n_users\"] = final_hist\nfinal_df.to_csv(\"D:/2004.csv\", index=False)\n</code></pre>\n\n<p>Instead of <code>minlength</code> you could also use <a href=\"https://stackoverflow.com/a/45422028/4042267\"><code>numpy.pad</code></a> (test which one is faster):</p>\n\n<pre><code>hist_on_day = np.bincount(visits_distribution)\nfinal_hist += np.pad(hist_on_day, (0, len(final_hist)), 'constant')\n</code></pre>\n\n<hr>\n\n<p>You should also separate this into multiple functions, the inner part of the <code>for</code> loop (without the last line) would be perfect for one:</p>\n\n<pre><code>def parse_file(file_name):\n df = _load_log_file(file_name)\n visits_distribution = df.groupby(\"ip\").cik.unique().apply(len)\n return np.bincount(visits_distribution, minlength=n)\n</code></pre>\n\n<hr>\n\n<p>And one way to make it a bit faster is to not generate all dates at the beginning with a list comprehension, but instead use a generator comprehension which will produce them as needed:</p>\n\n<pre><code>dates = ((date.year, date.quarter, date.month, date.day)\n for date in pd.date_range(start_date, end_date))\nlog_files = (path_to_zips.format(year=y, qtr=q, mnth=m, day=d)\n for y, q, m, d in dates)\n</code></pre>\n\n<p>However, that does preclude you from using <code>tqdm</code> for the progress (since generators don't have a length), but <a href=\"https://stackoverflow.com/questions/41985993/tqdm-show-progress-for-a-generator-i-know-the-length-of\">there are ways around that</a>:</p>\n\n<pre><code>n_days = (pd.to_datetime(end_date) - pd.to_datetime(start_date)).days\nfor zip_file in tqdm(log_files, total=n_days):\n ...\n</code></pre>\n\n<p>Note that I renamed some of your variables to conform to Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T09:59:34.217", "Id": "411263", "Score": "0", "body": "Wow. Thank you so much for explaining and for showing me how to improve my code. You've been a great help. My machine is a bit slow and this will help me save quite a lot of hours!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T09:33:30.547", "Id": "212612", "ParentId": "212559", "Score": "2" } } ]
{ "AcceptedAnswerId": "212612", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:10:00.503", "Id": "212559", "Score": "1", "Tags": [ "python", "python-3.x", "pandas" ], "Title": "Pandas: updating cells with new value plus old value" }
212559
<p>To support a demonstration I'm going to be doing, I need a short C# program that can be unit tested. I decided to make a FizzBuzz split into a few methods:</p> <pre><code>using System; namespace FizzBuzz { class FizzBuzzer { public static void Main() { FizzBuzzer fizzBuzzer = new FizzBuzzer(); int n = Convert.ToInt32(Console.ReadLine()); fizzBuzzer.StartLoop(n); } public int StartLoop(int n) { int fizzBuzzes = 0; for(int i = 0; i &lt; n; i++) { string output = getOutputForI(i); if(output == "FizzBuzz") { fizzBuzzes++; } Console.WriteLine(output); } return fizzBuzzes; } public string getOutputForI(int i) { string s = ""; if(i % 3 == 0) { s += "Fizz"; } if(i % 5 == 0) { s += "Buzz"; } if(s.Length == 0) { s = "" + i; } return s; } } } </code></pre> <p>I want people to focus on the point of my demonstration, and not on potential mistakes in my code. As someone new to C#, I can't evaluate my code very well. Are there any beginner mistakes that would distract pedantic C# experts?</p> <p>I am of course open to any type feedback, I mainly just want people to not laugh at or get annoyed by my code.</p> <hr> <p>Edit:</p> <p>here are example unit tests</p> <pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FizzBuzz.Tests { [TestClass()] public class FizzBuzzerTests { [TestMethod()] public void StartLoopTest() { Assert.AreEqual(6, FizzBuzzer.StartLoop(100)); } [TestMethod()] public void GetOutputFor0() { Assert.AreEqual("FizzBuzz", FizzBuzzer.getOutputForI(0)); } [TestMethod()] public void GetOutputFor4() { Assert.AreEqual("4", FizzBuzzer.getOutputForI(4)); } } } </code></pre> <p>and for context, here is the updated code (based on <a href="https://codereview.stackexchange.com/a/212569/37800">Ron Beyer's answer</a>) that those tests are run against:</p> <pre><code>using System; namespace FizzBuzz { public static class FizzBuzzer { public static void Main() { } public static int CountFizzBuzzes(int max) { int fizzBuzzes = 0; for (int i = 1; i &lt;= max; i++) { string result = FizzBuzz(i); if (result == "FizzBuzz") { fizzBuzzes++; } Console.WriteLine(result); } return fizzBuzzes; } public static string FizzBuzz(int input) { string s = ""; if (input % 3 == 0) { s += "Fizz"; } if (input % 5 == 0) { s += "Buzz"; } if (s.Length == 0) { s = "" + input; } return s; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:34:17.467", "Id": "411151", "Score": "6", "body": "Since your focus is on unit-testing then I think you should provide your tests too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:35:37.837", "Id": "411152", "Score": "0", "body": "And about mistakes that can distract your audience... we don't give classes the same name as the enclosing namespace." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:36:42.937", "Id": "411153", "Score": "0", "body": "@t3chb0t I don't have unit tests, I just have code that _can be_ unit tested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:37:44.417", "Id": "411154", "Score": "0", "body": "And thanks for catching the namespace; I did actually change that already, I just copied the wrong version of the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:38:05.773", "Id": "411155", "Score": "1", "body": "Well, nobody knows whether some code can be tested until you actually **try** to write tests ;-] This is a very deceiving feeling so I'd be really good if you wrote tests first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:38:48.260", "Id": "411156", "Score": "2", "body": "I can already tell that **this is not testable** because of your console output... so..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:44:01.770", "Id": "411157", "Score": "1", "body": "@t3chb0t Understood. I'll see if I can prototype some unit tests soon." } ]
[ { "body": "<p>Since it's a code-review site, I'll focus on issues you have with your code...</p>\n<h3>Having <code>Main</code> in your class</h3>\n<p>I would generally avoid this. I understand that this is probably a single-class demonstration project, but typically C# projects have a <code>Program</code> class that has <code>Main</code> inside of it, and I would stick with that. If you want to be able to unit-test <code>FizzBuzzer</code>, the <code>Main</code> function would not be unit-testable. As a result, your code-coverage of this class will be lower.</p>\n<h3>Inconsistent method names</h3>\n<p>You have a method properly cased as <code>StartLoop</code> and then you have an improper cased <code>getOutputForI</code>. Stick with the Microsoft recommendation of <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions\" rel=\"noreferrer\">Capitalization Rules for Methods</a> which should be Pascal Cased.</p>\n<h3>Method names and parameters that don't self-document</h3>\n<p>The name you give a method should identify to the caller what it does. <code>StartLoop</code> both starts and ends a loop, and runs the entire sequence. Ideally this would be named <code>Run</code> instead of <code>StartLoop</code>, but even then, what is it returning? Maybe <code>CountFizzBuzz</code> would be even better. Similarly, <code>getOutputForI</code> certainly gets the output for the method parameter <code>I</code>, but that really doesn't say what it does. Maybe consider renaming it to <code>FizzBuzz(int input)</code> instead.</p>\n<p>Similarly the method parameters are not self documenting. What is <code>n</code> exactly in <code>StartLoop</code>? It would be more apparent if the method were something like <code>Run(int max)</code>. Which would also require a modification of your <code>for</code> loop because you would stop just shy of <code>max</code>. <code>i</code> is also not apparent of what it is (see a suggested version in the paragraph above).</p>\n<h3>Mixing UI with code</h3>\n<p>This makes your code unit-test unfriendly. You can't unit test the output to the console, so in order to unit test this you would need to pass a stream to the output:</p>\n<pre><code>public int CountFizzBuzz(int max, TextWriter output)\n{\n int fizzBuzzes = 0;\n for (int i = 0; i &lt;=max; i++)\n {\n string fizzBuzz = FizzBuzz(i);\n if (fizzBuzz == &quot;FizzBuzz&quot;)\n {\n fizzBuzzes++;\n }\n output.WriteLine(fizzBuzz);\n }\n return fizzBuzzes;\n}\n</code></pre>\n<p>Now this is unit-testable because you can create a <code>TextWriter</code> and pass in a value that can be <code>Assert</code>ed later.</p>\n<h2>Inconsistent Brackets</h2>\n<p>You have two methods of writing brackets in your code, the &quot;Microsoft&quot; way, and the &quot;Java&quot; way. Again, I would stick with Microsoft practices here and use the one that has both brackets on their own lines.</p>\n<h3>Using an instance object for something that has no state</h3>\n<p><code>FizzBuzzer</code> has no state, so why isn't everything <code>static</code>? There isn't a good reason to require a <code>new</code> each time you have to run the &quot;Fizz Buzzer&quot;, take up space on the stack, etc. This class should be made <code>static</code>.</p>\n<hr/>\n<p>So with all my recommendations, here is what it would <em>possibly</em> turn out like:</p>\n<pre><code>public static class FizzBuzzer\n{\n public static int CountFizzBuzzes(int max)\n {\n return CountFizzBuzzes(max, Console.Out);\n }\n\n public static int CountFizzBuzzes(int max, TextWriter output)\n {\n int fizzBuzzes = 0;\n for (int i = 0; i &lt;= max; i++)\n {\n string result = FizzBuzz(i);\n\n if (result == &quot;FizzBuzz&quot;)\n fizzBuzzes++;\n\n output.WriteLine(result);\n }\n return fizzBuzzes;\n }\n\n public static string FizzBuzz(int input)\n {\n string s = &quot;&quot;;\n\n if (input % 3 == 0)\n s += &quot;Fizz&quot;;\n\n if (input % 5 == 0)\n s += &quot;Buzz&quot;;\n\n if (s.Length == 0)\n s = &quot;&quot; + input;\n\n return s;\n }\n}\n</code></pre>\n<p>I still don't find this completely &quot;ideal&quot; as <code>CountFizzBuzzes</code> really does two things, counts them and outputs them to the stream. This really should be two separate methods for separation of concerns.</p>\n<p>Just as a final note, your <code>Main</code> has an issue... Right now when you start the program it just stares at you with a blank window until you mash the right key(s).</p>\n<pre><code>public static void Main()\n{\n FizzBuzzer fizzBuzzer = new FizzBuzzer();\n int n = Convert.ToInt32(Console.ReadLine());\n fizzBuzzer.StartLoop(n);\n}\n</code></pre>\n<p>What is to stop the user here from entering &quot;My Name Is&quot; instead of &quot;42&quot;? The <code>Convert.ToInt32</code> will throw an exception and the program will terminate. The user isn't even prompted for a number or any thing. At least prompt the user:</p>\n<p>There are a multitude of questions on here about how to validate console input, so I'll leave that to you to research, but you should prompt the user <em>&quot;Please Enter a Number:&quot;</em> and if that isn't a number, tell them and ask again (and provide them a way to quit).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T18:44:10.880", "Id": "411190", "Score": "3", "body": "I wouldn't necessarily call not-using `{}` as _cleaned_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T19:05:53.170", "Id": "411196", "Score": "0", "body": "@t3chb0t Maybe a poor choice of words, revised" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T13:09:59.010", "Id": "411287", "Score": "0", "body": "Upvoted, very good answer - I would only point out that many *pedantic C# experts* you say making the conditional block scopes implicit isn't improving the code's maintainability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T16:34:20.080", "Id": "411434", "Score": "0", "body": "@MathieuGuindon I'd be one of them! All good advice, except the bit about skipping `{}` for single-line ifs, with which I disagree vehemently." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T16:36:34.223", "Id": "411438", "Score": "0", "body": "@BittermanAndy FWIW I'm one of them as well. [Rubberduck](http://www.github.com/rubberduck-vba/Rubberduck) pull requests without these braces inevitably get the review comments and change suggestions accordingly ;-)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:32:39.600", "Id": "212569", "ParentId": "212560", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:32:03.440", "Id": "212560", "Score": "5", "Tags": [ "c#", "beginner", "fizzbuzz" ], "Title": "Unit-testable C# FizzBuzz" }
212560
<p>Would like feedback on my SQL (1) efficiency and (2) readability, and if the conditions I featured in my <code>CASE</code> statement could be transferred to a join, etc. </p> <p>Here's the problem I'm solving: </p> <blockquote> <p>Say you have a table <code>bst</code> with a column of nodes and column or corresponding parent nodes:</p> <pre><code>node Parent 1 2 2 5 3 5 4 3 5 NULL </code></pre> <p>We want to write SQL such that we label each node as a “leaf”, “inner” or “Root” node, such that for the nodes above we get: </p> <pre><code>Node Label 1 Leaf 2 Inner 3 Inner 4 Leaf 5 Root </code></pre> </blockquote> <p>Here's my solution: </p> <pre><code>WITH join_table AS ( SELECT a.node a_node, a.parent a_parent, b.node b_node, b.parent b_parent FROM bst a LEFT JOIN bst b ON a.parent = b.node ) SELECT a_node as Node, CASE WHEN b_node IS NOT NULL and b_parent IS NOT NULL THEN 'Leaf' WHEN b_node IS NOT NULL and b_parent IS NULL THEN 'Inner' WHEN b_node IS NULL and b_parent IS NULL THEN 'Root' ELSE 'Error' END AS Label FROM join_table </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:58:50.040", "Id": "411161", "Score": "1", "body": "What dialect of SQL are you targeting? (Apart from that, this is a really well-asked SQL question, so well done!)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:14:51.483", "Id": "411166", "Score": "0", "body": "@TobySpeight Let's just say Hive, but Postgres or MySQL would work too -- more focused on the underlying logic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T19:17:43.430", "Id": "411199", "Score": "1", "body": "It is possible to rewrite your query without `CASE`, however, it will not help the performance since you are reading the whole tables anyway. The sequential scan is inevitable in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T16:17:56.453", "Id": "411311", "Score": "0", "body": "@RadimBača Feel free to post such a response" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T18:19:55.520", "Id": "411328", "Score": "1", "body": "@zthomas.nc it would be a solution using `UNION ALL` which would lead to three sequential scans instead of one." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T16:53:18.733", "Id": "212563", "Score": "1", "Tags": [ "sql", "join" ], "Title": "SQL self-join to label nodes on binary search tree" }
212563
<p>I am teaching programming (in this case - 1 on 1 tutoring of a teenager interested in programming) and this code will be a final stage of <a href="https://github.com/matkoniecz/quick-beautiful/tree/409d8212a251d7455e7d847bcbb26b89b78ff786/07-Sierpi%C5%84ski&#39;s-carpet" rel="noreferrer">a progression</a> toward program generating a nice image of Sierpiński's triangle.</p> <p>Any comments how this code can be improved are welcomed! But problems with unclear code that break standard practices are especially welcomed, performance issues are less important here.</p> <pre><code>from PIL import Image from PIL import ImageDraw def save_animated_gif(filename, images, duration): # done using https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html#saving first_image = images[0] other_images = images[1:] first_image.save(filename, save_all=True, append_images=other_images, duration=duration, loop=0) def make_pattern(draw, x, y, section_size, remaining_levels): if remaining_levels &lt;= 0: return hole_color = (5, 205, 65) corner = (x + section_size / 3, y + section_size / 3) # -1 necessary due to https://github.com/python-pillow/Pillow/issues/3597 opposite_corner = (x + section_size * 2/3 - 1, y + section_size * 2/3 - 1) draw.rectangle((corner, opposite_corner), fill=hole_color) parts = 3 for x_index in range(parts): for y_index in range(parts): x_anchor = x + section_size * x_index / parts y_anchor = y + section_size * y_index / parts new_size = section_size / 3 new_levels = remaining_levels - 1 make_pattern(draw, x_anchor, y_anchor, new_size, new_levels) def make_carpet(levels, size): carpet_color = (5, 60, 20) carpet = Image.new("RGBA", (size, size), carpet_color) draw = ImageDraw.Draw(carpet) make_pattern(draw, 0, 0, size, levels) return carpet levels = 7 size = 3**levels carpets = [] carpets.append(make_carpet(0, size)) standard_frame_time_in_ms = 1200 durations = [standard_frame_time_in_ms / 2] # first stage visible for a short time for i in range(levels - 1): carpets.append(make_carpet(i + 1, size)) durations.append(standard_frame_time_in_ms) durations[-1] *= 4 # final stage of animation visible for a long time save_animated_gif("Sierpiński's carpet.gif", carpets, durations) </code></pre> <p>output:</p> <p><img src="https://raw.githubusercontent.com/matkoniecz/quick-beautiful/master/Sierpi%C5%84ski&#39;s_carpet.gif" alt="linked outside site, as it is over image size limit allowed by SO"></p> <p><a href="https://raw.githubusercontent.com/matkoniecz/quick-beautiful/master/Sierpi%C5%84ski&#39;s_carpet.gif" rel="noreferrer">full sized image</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T22:18:46.100", "Id": "411216", "Score": "0", "body": "It is maybe a minor point, but the green is really, really unpleasant for the eyes. Since creating a beautiful picture should be a more motivating goal (and better to impress your friends) , I would consider switching colours." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T13:09:35.140", "Id": "411286", "Score": "1", "body": "@JishinNoben Interesting. I selected this colours because I liked them, maybe I should make a small poll. But student will select her own colours, I will certainly will not try to present mine as superior :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-16T11:30:47.960", "Id": "420899", "Score": "0", "body": "Hm. I wanted to award bounty immediately but it failed. Hopefully I will remember about it tomorrow. In case that someone wants to answer - https://codereview.stackexchange.com/questions/217549/maze-generator-for-teaching-python-3 will be much more useful (code in this question was completely rewritten and is now in a much better shape)." } ]
[ { "body": "<p>I only have a few small suggestions:</p>\n\n<p>I like to have \"tweaks\" that I may want to change later at the top of my file. This makes it easier to quickly alter them when playing around without needing to dig through the code. I'd move <code>levels</code> and <code>standard_frame_time_in_ms</code> to the top so they're a little more accessible. I might also change <code>levels</code> to <code>n_levels</code> or something similar to make it clearer that it's a number representing how many levels to have; not a collection of \"levels\".</p>\n\n<hr>\n\n<p>Right now, you're partially populating <code>durations</code> with the halved time delay, then adding the rest in the loop. I don't see a good reason to <code>append</code> to <code>durations</code> in the loop though. The data being added to <code>durations</code> has nothing to do with data available within the loop.</p>\n\n<p>I'd populate it before the loop. List multiplication makes this easy. The long variable names make this difficult to do succinctly unfortunately, but it can be split over two lines if need be:</p>\n\n<pre><code>durations = [standard_frame_time_in_ms // 2] + [standard_frame_time_in_ms] * (levels - 1)\n\ndurations = [standard_frame_time_in_ms // 2] + \\\n [standard_frame_time_in_ms] * (levels - 1)\n</code></pre>\n\n<p>I also changed it to use integer division (<code>//</code>) since fractions of a millisecond likely aren't usable by the GIF maker anyway.</p>\n\n<hr>\n\n<p>I'd stick the whole procedure in the bottom into a function:</p>\n\n<pre><code>def main():\n carpets = []\n carpets.append(make_carpet(0, size))\n\n durations = [standard_frame_time_in_ms / 2] # first stage visible for a short time\n\n for i in range(levels - 1):\n carpets.append(make_carpet(i + 1, size))\n durations.append(standard_frame_time_in_ms)\n\n durations[-1] *= 4 # final stage of animation visible for a long time\n\n save_animated_gif(\"Sierpiński's carpet.gif\", carpets, durations)\n</code></pre>\n\n<p>Now, you can call <code>main</code> when you want it to run. Especially when developing using a REPL, having long-running top-level code can be a pain. You don't necessarily want the whole thing to run just because you loaded the file.</p>\n\n<hr>\n\n<p>You have:</p>\n\n<pre><code>carpets.append(make_carpet(0, size))\n</code></pre>\n\n<p>then inside the loop you have:</p>\n\n<pre><code>carpets.append(make_carpet(i + 1, size))\n</code></pre>\n\n<p>I'm not a fan of duplication like this. There's usually a better way. It seems like you could just adjust the <code>range</code> bounds:</p>\n\n<pre><code>def main():\n carpets = []\n\n . . .\n\n for i in range(-1, levels - 1): # Start at -1 instead\n carpets.append(make_carpet(i + 1, size))\n\n . . .\n</code></pre>\n\n<p>This is basically just a transformation from a <code>range</code> to a list of carpets though. When \"converting\" one sequence to another, comprehensions come to mind:</p>\n\n<pre><code>carpets = [make_carpet(i + 1, size) for i in range(-1, levels - 1)]\n</code></pre>\n\n<p>Then, you can easily make it lazy if that proves beneficial in the future just by changing the <code>[]</code> to <code>()</code>:</p>\n\n<pre><code># Now it's a generator that only produces values as requested instead of strictly\ncarpets = (make_carpet(i + 1, size) for i in range(-1, levels - 1))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T18:06:07.537", "Id": "212574", "ParentId": "212564", "Score": "4" } }, { "body": "<h2>Algorithm</h2>\n\n<p>You can simplify the code and make it run faster if you construct the next-level carpet by continuing to work on the previous image (punching more holes in it), rather than starting with a blank slate every time. The code can look prettier and more Pythonic too, since the technique lets you get rid of the recursion.</p>\n\n<h2>Coding practices</h2>\n\n<p>It's a good habit to write docstrings, especially if you are using this code to teach a student!</p>\n\n<p>Avoid free-floating code; all code should be in a function. Follow the standard practice of writing <code>if __name__ == '__main__': main()</code> at the end of the code.</p>\n\n<p>You can combine the two <code>import</code> statements into one, since <code>Image</code> and <code>ImageDraw</code> are both being imported from the same module.</p>\n\n<p>It should be easier to tell that the color triples represent dark green and light green. A comment would work. In my solution below, I've opted to use explanatory variables. Furthermore, the colors should be specified in a more obvious place, rather than buried in some obscure place in the code.</p>\n\n<p>In Python, it is usually possible to find a more elegant way to building a list than by repeatedly <code>.append()</code>ing. Below, I construct <code>carpets</code> using a generator, and <code>durations</code> using the <code>*</code> operator.</p>\n\n<p>You know that all of the coordinates should be integers. Use integer division (<code>//</code>) rather than floating-point division (<code>/</code>) wherever possible.</p>\n\n<p>You can use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"nofollow noreferrer\"><code>itertools.product()</code></a> to avoid nested <code>for</code> loops for <code>x</code> and <code>y</code>.</p>\n\n<p>To split a list into the first element and subsequent elements, you can write <code>first_image, *other_images = images</code>.</p>\n\n<h2>Suggested solution</h2>\n\n<pre><code>from itertools import product\nfrom PIL import Image, ImageDraw\n\ndef save_animated_gif(filename, images, durations):\n \"\"\"\n Save images as frames of an animated GIF. Durations should specify the\n milliseconds to display each frame, and should be of the same length as\n images.\n \"\"\"\n # https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html#saving\n first_image, *other_images = images\n first_image.save(filename, save_all=True, append_images=other_images, duration=durations, loop=0)\n\ndef punch_hole(draw, x, y, section_size, hole_color):\n \"\"\"\n For a square with a corner at (x, y) and sides of length section_size,\n divide it into 9 tiles, and fill the center tile with hole_color.\n \"\"\"\n corner = (x + section_size // 3, y + section_size // 3)\n # -1 necessary due to https://github.com/python-pillow/Pillow/issues/3597\n opposite_corner = (x + section_size * 2//3 - 1, y + section_size * 2//3 - 1)\n draw.rectangle((corner, opposite_corner), fill=hole_color)\n\ndef make_carpets(n, carpet_color, hole_color):\n \"\"\"\n Generate n PIL Images, each of Sierpiński's carpet with increasing levels\n of detail.\n \"\"\"\n image_size = 3**n\n carpet = Image.new(\"RGBA\", (image_size, image_size), carpet_color)\n yield carpet\n for section_size in (3**i for i in range(n, 1, -1)):\n carpet = carpet.copy()\n draw = ImageDraw.Draw(carpet)\n for x, y in product(range(0, image_size, section_size), repeat=2):\n punch_hole(draw, x, y, section_size, hole_color)\n yield carpet\n\ndef main():\n N = 7\n DARK_GREEN = (5, 60, 20)\n LIGHT_GREEN = (5, 205, 65)\n\n carpets = make_carpets(N, carpet_color=DARK_GREEN, hole_color=LIGHT_GREEN)\n durations = [1200] * N # 1200ms per frame, except...\n durations[0] //= 2 # first frame is shorter\n durations[-1] *= 4 # final frame is longer\n\n save_animated_gif(\"Sierpiński's carpet.gif\", carpets, durations)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<h2>Alternative calculations</h2>\n\n<p>In the suggested solution above, I've written <code>punch_hole()</code> to be similar to your <code>make_pattern()</code>, in that they are both responsible for rendering a square of size <code>section_size</code>. However, the arithmetic can be simplified by specifying the size of the center hole instead, so that no division is necessary.</p>\n\n<pre><code>def draw_square(draw, x, y, size, color):\n \"\"\"\n Fill a square with one corner at (x, y) with the specified color.\n \"\"\"\n # -1 necessary due to https://github.com/python-pillow/Pillow/issues/3597\n draw.rectangle((x, y), (x + size - 1, y + size - 1)), fill=color)\n\ndef make_carpets(n, carpet_color, hole_color):\n \"\"\"\n Generate n PIL Images, each of Sierpiński's carpet with increasing levels\n of detail.\n \"\"\"\n image_size = 3**n\n carpet = Image.new(\"RGBA\", (image_size, image_size), carpet_color)\n for hole_size in (3**i for i in range(n, 0, -1)):\n draw = ImageDraw.Draw(carpet)\n for x, y in product(range(hole_size, image_size, 3 * hole_size), repeat=2):\n draw_square(draw, x, y, hole_size, hole_color)\n yield carpet\n carpet = carpet.copy()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T20:54:08.887", "Id": "411208", "Score": "0", "body": "Thanks, this is really, really useful! I will certainly use many (or maybe even all) suggestion. \"Follow the standard practice of writing `if __name__ == '__main__': main()`\" - in this case I deliberately skipped it for now - to avoid both explaining everything at once and to avoid cargo cult code. I planned to start adding it once projects using more than one file will appear. Do you think it is a good idea?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T20:56:15.693", "Id": "411209", "Score": "3", "body": "If you want to avoid overwhelming a beginner with the magic of `if __name__ == '__main__'`, then just call `main()` unconditionally, and tell them that you're doing it because it's good practice to put all code in a function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T21:48:07.357", "Id": "411348", "Score": "0", "body": "\"You can — and should — combine the two import statements into one, since Image and ImageDraw are both being imported from the same module.\" I am not sure about this one. PEP 8 allows it but is not mentioned as preferable, I am not seeing significant benefits here, neither `pylint` nor `autopep8` proposed to change that..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T21:52:50.947", "Id": "411350", "Score": "0", "body": "Combining the imports is what I would have done, but I don't feel strongly about it, so I've removed \"and should\"." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T20:09:36.183", "Id": "212580", "ParentId": "212564", "Score": "6" } } ]
{ "AcceptedAnswerId": "212580", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:01:22.707", "Id": "212564", "Score": "13", "Tags": [ "python", "python-3.x", "animation", "graphics", "fractals" ], "Title": "Sierpiński's carpet fractal animation for teaching Python 3" }
212564
<p><strong>Purpose:</strong> After you've submitted a resume and cover letter for a job position, you haven't heard anything back, so you decided to send a follow up email. The script generates the follow up e-mail based on <a href="https://www.themuse.com/advice/how-to-follow-up-on-a-job-application-an-email-template" rel="nofollow noreferrer">this template</a>. </p> <pre><code>""" followupemail.py A script to generate a follow up e-mail after a job application submission. Based on this example: https://www.themuse.com/advice/how-to-follow-up-on-a-job-application-an-email-template """ def determine_if_string_is_blank(stringtovalidate, parameterType): """ Determine if the stringtovalidate parameter is empty, and if so, raise an exception. Args: stringtovalidate: The string to validate. parameterType: What the stringtovalidate parameter represents in your program. Returns: None. Raises an exception. """ if not stringtovalidate: raise ValueError ("{0} is empty", parameterType) def prompt_user_with_question(question, parameterType): """ Prompt user with a question and call determine_if_string_is_blank to deteremine if an answer is empty. Args: question: the question we're going to ask parameterType: What the stringtovalidate parameter represents in your program. Returns: answer: the string that contains our user answer. """ answer = input(question) determine_if_string_is_blank(answer, parameterType) return answer def write_string_to_file(pathtofile,email): """ Writes the email to a .txt file Args: pathtofile: The path where the e-mail will be stored email: The message we're going to write. Returns: None """ with open(pathtofile, 'w') as f: f.write(email) def main(): position_title = None hiring_manager = None company_name = None your_name = None pathtofile = "email.txt" company_name = prompt_user_with_question("Company Name: ", "Company Name").strip() position_title = prompt_user_with_question("Position: ", "Position").strip() hiring_manager = prompt_user_with_question("Hiring Manager: ", "Hiring Manager") your_name = prompt_user_with_question("Your Name: ", "Your Name") email = f"Hi {hiring_manager},\n\nI hope all is well. I know how busy you probably are, but I recently applied to the \n" \ f"{position_title} position, and wanted to check in on your decision timeline.\n\n" \ f"I am excited about the opportunity to join {company_name} (insert additional details here).\n\n" \ f"Please let me know if it would be helpful for me to provide " \ f"any additional information as you move on to the next stage in the hiring process.\n\nI look forward to hearing from you,\n\n{your_name}" write_string_to_file(pathtofile,email) if __name__ == "__main__": main() </code></pre> <p><strong>Explanation</strong>: The script prompts the user for company name, position, hiring manager, and the name. It inserts those values into the <code>email</code> string and generates a text file.</p>
[]
[ { "body": "<p>You wrote a <em>lot</em> of boilerplate code to do a simple task. Before reading the rest of this review, scroll back up and imagine that you were given the assignment, \"Make your code as simple and readable as possible.\" What would you change about it?</p>\n\n<p>Here's what I'd do.</p>\n\n<hr>\n\n<pre><code>def determine_if_string_is_blank(stringtovalidate, parameterType):\n</code></pre>\n\n<p>Inconsistent style. Pick one of <code>snake_case</code>, <code>amoebacase</code>, or <code>camelCase</code>, and stick to it!</p>\n\n<p>This function triggers my \"boolean functions should be named with <code>is_</code> detector. <em>Surely,</em> I think, <em>this function should be named <code>is_blank_string</code>!</em> But in fact your name is (currently) more appropriate, because this function does not return a boolean — it returns <code>None</code> or throws an exception! This is not great design, but, okay, the name isn't the worst. However, I would write this entire function as</p>\n\n<pre><code>def assert_string_isnt_blank(s)\n assert s\n</code></pre>\n\n<p>(notice that the name of the function now <em>unambiguously tells what it does</em>) and then I would eliminate it.</p>\n\n<pre><code>def prompt_user_with_question(question, parameterType):\n answer = input(question)\n assert answer, f\"{parameterType} is empty\"\n return answer\n</code></pre>\n\n<hr>\n\n<p>By the way, what did you expect this line to do?</p>\n\n<pre><code>raise ValueError (\"{0} is empty\", parameterType)\n</code></pre>\n\n<p>Did you perhaps expect it to do the same thing as</p>\n\n<pre><code>raise ValueError (\"{0} is empty\".format(parameterType))\n</code></pre>\n\n<p>? It doesn't!</p>\n\n<p>(This suggests that you never tested your code, or at least you never tested its non-success paths. Make sure to test your code before running it in production — or posting it to StackExchange!)</p>\n\n<hr>\n\n<pre><code>def write_string_to_file(pathtofile,email):\n</code></pre>\n\n<p>The usual complaint about needing to pick a style (underscores? no underscores?) and sticking to it. But also there's a missing space here. It would be good to get in the habit of running your code through a linter like <code>flake8</code> before posting it, as well.</p>\n\n<pre><code>$ flake8 --ignore=E501 x.py\nx.py:26:25: E211 whitespace before '('\nx.py:49:36: E231 missing whitespace after ','\nx.py:81:10: E127 continuation line over-indented for visual indent\nx.py:86:36: E231 missing whitespace after ','\n</code></pre>\n\n<p>Nothing major here... but sometimes there <em>is</em> something major, and then you're glad you took the time to look for warnings!</p>\n\n<hr>\n\n<p>Your docstrings make it look like you're intending this as a 100% complete Python program. If so, then you should start the file with a hashbang:</p>\n\n<pre><code>#!/usr/bin/env python\n</code></pre>\n\n<hr>\n\n<p>For the email body itself, consider using <code>\"\"\"multi-line strings\"\"\"</code> instead of backslash-continuations. Multi-line strings can be combined with the <code>f</code> prefix.</p>\n\n<hr>\n\n<pre><code>position_title = None\nhiring_manager = None\ncompany_name = None\nyour_name = None\n</code></pre>\n\n<p>You create all these variables and then you never use them again! Or, another way to put it is, you assign <code>None</code> to all these variables and then immediately overwrite it with some other value! Eliminate the dead writes.</p>\n\n<hr>\n\n<p>In conclusion:</p>\n\n<pre><code>#!/usr/bin/env python\n\ndef prompt(question):\n answer = input(question + \": \")\n assert answer, f\"{question} is empty\"\n return answer\n\nif __name__ == \"__main__\":\n company_name = prompt(\"Company Name\").strip()\n position_title = prompt(\"Position\").strip()\n hiring_manager = prompt(\"Hiring Manager\")\n your_name = prompt(\"Your Name\")\n\n with open(\"email.txt\", \"w\") as f:\n f.write(f\"\"\"\nHi {hiring_manager},\n\nI hope all is well. I know how busy you probably are, but I recently applied to the\n{position_title} position, and wanted to check in on your decision timeline.\n\nI am excited about the opportunity to join {company_name} (insert additional details here).\n\nPlease let me know if it would be helpful for me to provide\nany additional information as you move on to the next stage in the hiring process.\n\nI look forward to hearing from you,\n{your_name}\n \"\"\".strip() + '\\n')\n</code></pre>\n\n<p>Notice that I'm using a function <em>only</em> when it makes sense — that is, only when it eliminates repetition in the code.</p>\n\n<p>Also notice that by using a multi-line string, even though it screws up my indentation, it helps to highlight an otherwise-easily-missed bug in the program!</p>\n\n<pre><code>I am excited about the opportunity to join {company_name} (insert additional details here).\n</code></pre>\n\n<p>Did you notice the <code>(insert additional details here)</code> stuffed in the middle of a string literal full of backslashes? You wouldn't want to send the email out like that, would you? :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:52:08.173", "Id": "411179", "Score": "0", "body": "*This is not great design* - could you elaborate? Do you mean raising the exception? *You wouldn't want to send the email out like that, would you?* This is why I generate a text file rather than send an email in the script. The user may want to add more details, sometimes it's good to proof read and let something you write sit a while, because you may think of a better way to say it later on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:56:45.093", "Id": "411182", "Score": "0", "body": "Another thing I missed too, I never enclosed my code with `try/catch` even though I raised an exception! I'm using Python on Windows, do still need the `#!/usr/bin/env python` line?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T18:16:31.883", "Id": "411183", "Score": "0", "body": "Re Windows: The hashbang can't hurt, and would help if you use Cygwin or git-bash or any other Unix-alike shell. I don't know if PowerShell cares; I imagine CMD doesn't. Re great design: google the phrase \"exceptions for control flow.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T18:24:13.467", "Id": "411186", "Score": "0", "body": "Given that I don't want the program to continue if a value is blank, wouldn't an exception be appropriate? Suppose if I had a `Message` class, obviously in the constructor I would validate that the values are not null and throw an exception if they are." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T19:16:09.670", "Id": "411198", "Score": "0", "body": "\"Exceptions for control flow\" should clear up that question. Constructors tend to be a special case because in most languages it is not possible to \"return failure from\" a constructor — you *must* either construct an object, or throw (or terminate or loop forever). Also see \"Single Responsibility Principle\": is this function responsible for testing a string, or for terminating the program? Is \"Both\" an acceptable answer? (In this case the answer is muddy anyway, because the function itself should never have existed.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T20:40:37.620", "Id": "411206", "Score": "1", "body": "Assertions should be used to declare facts that the programmer _knows must be true_, due to the logic. They should never be used to specify conditions that the programmer _hopes to be true_, such as input validation. The assertions will be omitted when Python code is optimized with the `-O` flag, and then the program will break!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T21:47:46.900", "Id": "411212", "Score": "0", "body": "`echo 'assert False' | python - ; echo $?` -> 1; `echo 'assert False' | python -O - ; echo $?` -> 0! Today I learned about `-O`. Thank you. :) In this _particular_ toy program, I personally would still use `assert`; but that's a very good point about input validation in general." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T23:10:30.773", "Id": "411220", "Score": "0", "body": "@200_success - Would you throw an exception to validate parameters, in my case the user input?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T00:22:37.250", "Id": "411224", "Score": "0", "body": "@EmilyScott How do you want your program to behave? Right now, your program crashes with an uncaught exception if any input is blank. Crashing is generally undesirable behavior. You could change `prompt_user_with_question()` so that it loops, and only returns after receiving a non-empty response." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T00:25:56.060", "Id": "411225", "Score": "0", "body": "@I don't want it to move forward if an invalid answer is given. Although looping is a nice alternative, I just wanted to get your point of view when it comes to exceptions and control flow. Is using exception the way I have a code smell?" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:45:26.897", "Id": "212571", "ParentId": "212565", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:07:58.213", "Id": "212565", "Score": "0", "Tags": [ "python", "python-3.x", "template" ], "Title": "Generate a text file representing an email for a job application followup" }
212565
<p>I've attempted to solve a small coding challenge <a href="https://www.youtube.com/watch?v=10WnvBk9sZc" rel="nofollow noreferrer">I found online</a> as a nice way to begin learning Rust. The largest challenge I feel going in with Rust is how working with strings is so fundamentally different from any other programming language I've used before. The challenge was this:</p> <blockquote> <p><strong>Write a function that takes two strings, s1 and s2 and returns the longest common sequence of s1 and s2:</strong></p> <p>"ABAZDC", "BACBAD" => "ABAD"<br> "AGGTAB", "GXTKAYB" => "GTAB"<br> "aaaa", "aa" => "aa"<br> "ABBA", "ABJABA" => "ABBA" </p> </blockquote> <p>The challenge seemed simple but the way I understood how I one could iterate though Rust strings proved to be very difficult. With numerous copies of iterators made and copies of <code>String</code>s being made back and forth I am aware that this program is in its most naive form.</p> <p>I wonder if collecting the string's characters into a vector would've been a better approach. I really want to find a more efficient method of solving this problem with Rust that'll be more comparable to C++ in terms of performance.</p> <pre><code>#[macro_use] extern crate criterion; use criterion::Criterion; fn longest_con_seq(s1:&amp;String, s2:&amp;String) -&gt; String { let mut max: Option&lt;String&gt; = None; // Holds value of string with maximum length let mut current = String::new(); // String container to hold current longest value let mut s1_iter = s1.chars().peekable(); // Peekable iterator for string s1 let mut s2_iter = s2.chars(); //Iterator for string s2 let mut s2_prev_pos = s2_iter.clone(); // Iterator that holds position of previous location of first iterator let mut s1_prev_pos = s1_iter.clone(); // Peekable iterator used to make sure all possible combinations are located. loop { let s1_char = s1_iter.next(); // Get character in s1 if current.len() == 0 // If no consequtive string found yet store location of iterator { s1_prev_pos = s1_iter.clone() } match s1_char{ Some(s1_char)=&gt; { loop{ match s2_iter.next() { Some(s2_char) if s1_char == s2_char =&gt; { current.push(s1_char); s2_prev_pos = s2_iter.clone(); break; }, Some(_)=&gt;continue, None=&gt;{ s2_iter = s2_prev_pos.clone(); break; }, } } }, None=&gt;{ match s1_prev_pos.peek() { Some(_) =&gt; { match max{ Some(_) =&gt; { let max_str = max.clone(); let max_str = max_str.unwrap(); if max_str.len() &lt; current.len(){ max = Some(current.clone()); } current.clear(); }, None =&gt; { max = Some(current.clone()); current.clear(); }, } s1_iter = s1_prev_pos.clone(); s2_iter = s2.chars(); }, None =&gt; break, } }, } } if let Some(_) = max { return max.unwrap(); } else { return String::from(""); } } fn criterion_benchmark(c: &amp;mut Criterion) { let s1 = "GXTKAYB".to_owned(); let s2 = "AGGTAB".to_owned(); c.bench_function("Benchmark", move |b| b.iter(|| longest_con_seq(&amp;s1, &amp;s2))); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches); </code></pre> <h1>C++ comparison</h1> <p>I wrote a C++ version of the code that manipulates the strings through their indices. I though it would outperform the Rust code but it wasn't so.</p> <pre class="lang-cpp prettyprint-override"><code> #include &lt;benchmark/benchmark.h&gt; #include &lt;string&gt; std::string longest_con_seq(std::string &amp;s1, std::string &amp;s2) { std::string max = "", current = ""; size_t s2_old_idx = 0, s1_old_idx = 0; bool first_iter = true; for(size_t s1_idx = 0; s1_idx &lt; s1.length(); ++s1_idx) { if(first_iter) s1_old_idx = s1_idx; first_iter = false; for(size_t s2_idx = s2_old_idx; s2_idx &lt; s2.length(); ++s2_idx) { if(s1[s1_idx] == s2[s2_idx]) { s2_old_idx = s2_idx + 1; current += s1[s1_idx]; break; } } if(s1_idx == s1.length()-1 &amp;&amp; s1_old_idx != s1.length()-1) { s1_idx = s1_old_idx; s2_old_idx = 0; if(max.length() == 0 || max.length() &lt; current.length()) { max = current; } current.clear(); first_iter = true; } else if( s1_old_idx == s1.length()-1 ) { break; } } return max; } static void BM_LongestConSeq(benchmark::State&amp; state) { std::string s1 = "GXTKAYB", s2 = "AGGTAB"; for (auto _ : state) { longest_con_seq(s1,s2); } } // Register the function as a benchmark BENCHMARK(BM_LongestConSeq); BENCHMARK_MAIN(); </code></pre> <h2>Results</h2> <h3>Rust</h3> <pre class="lang-none prettyprint-override"><code>**time:** [96.755 ns **97.291 ns** 98.031 ns] **change:** [-2.8521% _-1.4304%_ -0.1568%] (p = 0.04 &lt; 0.05) Change within noise threshold. _Found 12 outliers among 100 measurements (12.00%)_ 5 (5.00%) high mild 7 (7.00%) high severe </code></pre> <h1>C++</h1> <pre class="lang-none prettyprint-override"><code>Benchmark ---------- Time: **152 ns** CPU: **152 ns** Iterations: **4471469** </code></pre> <p>I really don't know how to interpret the results, I used Google Benchmark for the C++ code and Criterion for the Rust code. It seems to look like the Rust code has outperformed the C++ code, but maybe I'm wrong. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T18:22:31.907", "Id": "411185", "Score": "1", "body": "Sure, I'll write c++ version and benchmark both but its pretty clear with the ability to directly access indices with minimal to no copying of iterators the c++ solution would be much more efficient." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T23:38:23.573", "Id": "411221", "Score": "1", "body": "@BiggySmallRyeda I think you underestimate LLVM" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T07:53:29.977", "Id": "411246", "Score": "0", "body": "From experience with both C++ and Rust, performance is generally comparable, as long as you use equivalent operations. In terms of iterators specifically, C++ iterators compose badly, which generally give an edge to Rust if you start piling \"filtering\" iterators... but that's not very common." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T18:46:21.480", "Id": "411331", "Score": "1", "body": "@MatthieuM. I added the edits you and the others recommended. I don't understand the results of the benchmark very well. Also, can someone judge my rust approach to the problem." } ]
[ { "body": "<ol>\n<li>Run <a href=\"https://github.com/rust-lang-nursery/rustfmt\" rel=\"nofollow noreferrer\">Rustfmt</a>, a tool for automatically formatting Rust code to the community-accepted style.</li>\n<li>Run <a href=\"https://github.com/rust-lang-nursery/rust-clippy\" rel=\"nofollow noreferrer\">Clippy</a>, a tool for finding common mistakes that may not be compilation errors but are unlikely to be what the programmer intended.</li>\n<li>Don't accept a <code>&amp;String</code> — <a href=\"http://stackoverflow.com/q/40006219/155423\">Why is it discouraged to accept a reference to a String (&amp;String) or Vec (&amp;Vec) as a function argument?</a></li>\n<li>Don't use explicit <code>return</code> keywords at the end of blocks.</li>\n<li><p>Instead of </p>\n\n<pre><code>if let Some(_) = max {\n max.unwrap()\n</code></pre>\n\n<p>bind the variable:</p>\n\n<pre><code>if let Some(x) = max {\n x\n</code></pre></li>\n<li><p>Your whole last conditional can be simplified to <code>max.unwrap_or_default()</code>.</p></li>\n<li><p>Add some automated tests.</p>\n\n<pre><code>#[test]\nfn example_1() {\n assert_eq!(longest_con_seq(\"ABAZDC\", \"BACBAD\"), \"ABAD\");\n}\n\n#[test]\nfn example_2() {\n assert_eq!(longest_con_seq(\"AGGTAB\", \"GXTKAYB\"), \"GTAB\");\n}\n\n#[test]\nfn example_3() {\n assert_eq!(longest_con_seq(\"aaaa\", \"aa\"), \"aa\");\n}\n\n#[test]\nfn example_4() {\n assert_eq!(longest_con_seq(\"ABBA\", \"ABJABA\"), \"ABBA\");\n}\n</code></pre></li>\n<li><p>As before, don't match on <code>Some</code> and then <code>unwrap</code>, bind the variable. We can also avoid the clone by matching on a reference:</p>\n\n<pre><code>match max {\n Some(_) =&gt; {\n let max_str = max.clone();\n let max_str = max_str.unwrap();\n</code></pre>\n\n<pre><code>match &amp;max {\n Some(max_str) =&gt; {\n</code></pre></li>\n<li><p><code>current.clear()</code> is used in both match arms; extract it.</p></li>\n<li><p><code>max = Some(current.clone())</code> is the same; extract it and use a boolean.</p>\n\n<pre><code>let do_it = match &amp;max {\n Some(max_str) =&gt; {\n max_str.len() &lt; current.len()\n }\n None =&gt; {\n true\n }\n};\n\nif do_it {\n max = Some(current.clone());\n}\n</code></pre></li>\n<li><p>This construct can be replaced by <code>as_ref</code> and <code>map_or</code>:</p>\n\n<pre><code>if max.as_ref().map_or(true, |s| s.len() &lt; current.len()) {\n max = Some(current.clone());\n}\n</code></pre></li>\n</ol>\n\n<h3>End result</h3>\n\n<pre><code>#[macro_use]\nextern crate criterion;\n\nuse criterion::Criterion;\n\nfn longest_con_seq(s1: &amp;str, s2: &amp;str) -&gt; String {\n let mut max: Option&lt;String&gt; = None; // Holds value of string with maximum length\n let mut current = String::new(); // String container to hold current longest value\n let mut s1_iter = s1.chars().peekable(); // Peekable iterator for string s1\n let mut s2_iter = s2.chars(); //Iterator for string s2\n let mut s2_prev_pos = s2_iter.clone(); // Iterator that holds position of previous location of first iterator\n let mut s1_prev_pos = s1_iter.clone(); // Peekable iterator used to make sure all possible combinations are located.\n\n loop {\n let s1_char = s1_iter.next(); // Get character in s1\n\n if current.is_empty() {\n // If no consecutive string found yet store location of iterator\n s1_prev_pos = s1_iter.clone()\n }\n\n match s1_char {\n Some(s1_char) =&gt; loop {\n match s2_iter.next() {\n Some(s2_char) if s1_char == s2_char =&gt; {\n current.push(s1_char);\n s2_prev_pos = s2_iter.clone();\n break;\n }\n Some(_) =&gt; continue,\n None =&gt; {\n s2_iter = s2_prev_pos.clone();\n break;\n }\n }\n },\n None =&gt; match s1_prev_pos.peek() {\n Some(_) =&gt; {\n if max.as_ref().map_or(true, |s| s.len() &lt; current.len()) {\n max = Some(current.clone());\n }\n current.clear();\n\n s1_iter = s1_prev_pos.clone();\n s2_iter = s2.chars();\n }\n None =&gt; break,\n },\n }\n }\n\n max.unwrap_or_default()\n}\n\nfn criterion_benchmark(c: &amp;mut Criterion) {\n let s1 = \"GXTKAYB\";\n let s2 = \"AGGTAB\";\n c.bench_function(\"Benchmark\", move |b| b.iter(|| longest_con_seq(s1, s2)));\n}\n\ncriterion_group!(benches, criterion_benchmark);\ncriterion_main!(benches);\n\n#[test]\nfn example_1() {\n assert_eq!(longest_con_seq(\"ABAZDC\", \"BACBAD\"), \"ABAD\");\n}\n\n#[test]\nfn example_2() {\n assert_eq!(longest_con_seq(\"AGGTAB\", \"GXTKAYB\"), \"GTAB\");\n}\n\n#[test]\nfn example_3() {\n assert_eq!(longest_con_seq(\"aaaa\", \"aa\"), \"aa\");\n}\n\n#[test]\nfn example_4() {\n assert_eq!(longest_con_seq(\"ABBA\", \"ABJABA\"), \"ABBA\");\n}\n</code></pre>\n\n<blockquote>\n <p>With numerous copies of iterators made and copies of Strings being made</p>\n</blockquote>\n\n<p>Copies of iterators are <em>generally</em> going to be extremely lightweight. In many cases, they are equivalent to a pointer and and offset.</p>\n\n<p>Cloning a <code>String</code> is slightly less ideal, but that may just be a restriction of the algorithm.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T16:06:42.077", "Id": "212704", "ParentId": "212568", "Score": "5" } } ]
{ "AcceptedAnswerId": "212704", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:23:04.507", "Id": "212568", "Score": "7", "Tags": [ "beginner", "algorithm", "strings", "rust" ], "Title": "Find the longest common sequence of two strings in Rust" }
212568
<p>I started learning Python 2 about a week ago, using Codecademy and Stack Overflow answers to help me learn. I wrote a code to calculate the user's free time based on user sleep and work time. It also lets the user decide whether to see percentage of free time. It's not fancy; I never intend to actually use it. It works the way I want it to.</p> <p>I'm looking for feedback on how I wrote this code. What should I have done differently?</p> <pre><code>print "The program is operating." def sleep(time): sleep_hours = float(raw_input("How many hours do you sleep a night?: ")) return time - sleep_hours def work(time): work_hours = float(raw_input("How many hours do you work each weekday?: ")) time -= work_hours return time def see_percent(): reply = raw_input("Would you like to know the percent of your waking time is free time? (Y/N): ").lower() if reply == "y": print percent_round + "%." elif reply == "n": print "Okay" else: print "Y/N means enter a 'Y' for yes or a 'N' for no." time = 24. time_minus_sleep = sleep(time) time_minus_work = work(time_minus_sleep) waking_time = time_minus_sleep percent_free = str(time_minus_work / waking_time * 100) percent_round = percent_free[:5] print"" print "You have %.2f hours of freetime." % time_minus_work waking_time = time_minus_sleep print "Of the %.0f hours in a day, you are awake for %.2f of them." % (time, waking_time) </code></pre>
[]
[ { "body": "<p>My implementation of the program: (Comments, explanation of changes below).</p>\n\n<pre><code>print \"The program is operating.\"\n\ndef sleep(time):\n sleep_hours = float(raw_input(\"How many hours do you sleep a night?: \"))\n return time - sleep_hours\n\ndef work(time):\n work_hours = float(raw_input(\"How many hours do you work each weekday?: \"))\n return time - work_hours\n\ndef see_percent():\n reply = raw_input(\"Would you like to know the percent of your waking time is free time? (Y/N): \").lower()\n if reply == \"y\":\n print percent_round + \"%.\"\n elif reply == \"n\":\n print \"Okay\"\n else:\n print \"Y/N means enter a 'Y' for yes or a 'N' for no.\"\n\n\ntime = 24.\ntime = sleep(time)\nwaking_time = time\ntime = work(time)\npercent_free = str(time / waking_time * 100)\npercent_round = percent_free[:5]\n\nprint \"\\nYou have %.2f hours of freetime.\" % time\nprint \"Of the 24 hours in a day, you are awake for %.2f of them.\" % waking_time\n\nsee_percent()\n</code></pre>\n\n<p><strong>Additions</strong></p>\n\n<ol>\n<li>I added a call for the \"see_percent()\" function at the bottom of the code.</li>\n</ol>\n\n<p><strong>Subtractions (Top to bottom)</strong></p>\n\n<ol>\n<li>I removed the time assignment in the \"work()\" function, as I could perform the operation in the return statement, saving a line.</li>\n<li>I removed the \"time_minus_sleep\" variable, as I was able to achieve the output of the original program just by changing the \"time\" variable.</li>\n<li>I removed the first print statement, and added an escape sequence \"\\n\" to create a newline instead of using the separate print statement.</li>\n<li>I removed the second redundant waking_time assignment, as it was no longer needed.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T22:19:19.007", "Id": "212588", "ParentId": "212570", "Score": "0" } }, { "body": "<p>There is no need for <code>sleep</code> and <code>work</code> to take the time as an argument. Just return what the user enters and calculate in the main function. The main part of the code should be guarded by a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a>, which ensures that that code is only executed when running the script but not when importing from it.</p>\n\n<p><a href=\"https://pythonclock.org/\" rel=\"nofollow noreferrer\">Python 2 will soon be no longer supported</a>. If you are starting to learn Python now, learn Python 3 straight away. In the code below the main differences are that <code>raw_input</code> is now <code>input</code> (and the Python 2 <code>input</code> no longer exists), <code>print</code> is no longer a statement, but a function (so surround it with <code>()</code>, instead of <code></code>), division is now float division by default (use <code>//</code> for integer division) and finally string formatting has become a lot easier <a href=\"https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498\" rel=\"nofollow noreferrer\">in Python 3.6 with <code>f-string</code>s</a>.</p>\n\n<pre><code>def ask_time(message):\n while True:\n try:\n hours = float(input(message))\n if 0 &lt;= hours &lt;= 24:\n return hours\n except ValueError:\n pass\n print(\"Please enter a number between 0 and 24\")\n\ndef see_percent():\n reply = input(\"Would you like to know the percent of your waking time is free time? (Y/N): \").lower()\n return reply == \"y\"\n\n\nif __name__ == \"__main__\":\n total_time = 24. # hours\n sleep_time = ask_time(\"How many hours do you sleep a night?: \")\n work_time = ask_time(\"How many hours do you work each weekday?: \")\n\n waking_time = total_time - sleep_time\n free_time = waking_time - work_time\n print(f\"You have {free_time:.2f} hours of free time.\")\n print(f\"Of the 24 hours in a day, you are awake for {waking_time:.2f} of them.\")\n\n if see_percent():\n percent_free = free_time / total_time\n print(f\"{percent_free:.2%}.\")\n</code></pre>\n\n<p>I also made a more general <code>ask_time</code> function which ensures that the user enters a valid number between 0 and 24 and keeps on asking if they didn't and used four spaces throughout, as recommended by Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T15:18:11.053", "Id": "212631", "ParentId": "212570", "Score": "2" } }, { "body": "<p>I think calling those functions <code>work</code> and <code>sleep</code> is confusing. <code>sleep</code> doesn't actually \"sleep\" anything, it's asking for the number of hours slept. I would change the names to something like <code>ask_sleep_time</code> to make it clearer what the purpose is.</p>\n\n<p><code>sleep</code> will also cause conflicts if you happen to do <code>from time import sleep</code> in the future.</p>\n\n<hr>\n\n<p>And I completely agree with @Graipher's <code>ask_time</code> function. That is what immediately jumped into my head when I saw your <code>sleep</code> and <code>work</code> functions. They have two big problems.</p>\n\n<ul>\n<li><p>They're both nearly the same code (ask for an input, subtract from <code>time</code>).</p></li>\n<li><p>They're doing too much.</p></li>\n</ul>\n\n<p>For the second point, why are the functions subtracting from <code>time</code>? This means that you have them doing two jobs.</p>\n\n<ul>\n<li><p>Getting user input.</p></li>\n<li><p>Calculating and returning the time remaining.</p></li>\n</ul>\n\n<p>In this particular case this isn't a huge deal, but it should be kept in mind. When you start writing larger, more complicated functions, you need to make sure you don't have single functions doing multiple, unrelated tasks when possible. Such functions make testing harder and code more difficult to understand.</p>\n\n<hr>\n\n<p>I also disagree with the name <code>time</code>. 1. <code>time</code> is the name of a standard python module. You don't want to run into conflicts with it, or allow for confusion. I think it would make more sense to have a <code>hours_in_day = 24</code> variable, then do something like:</p>\n\n<pre><code>sleep_hours = ask_time(\"How many hours do you sleep a night?: \")\nwork_hours = ask_time(\"How many hours do you work each weekday?: \")\n\nfree_hours = hours_in_day - sleep_hours - work_hours\n</code></pre>\n\n<p>Similar to what @Graipher has.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T20:24:33.787", "Id": "212650", "ParentId": "212570", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:44:11.777", "Id": "212570", "Score": "2", "Tags": [ "python", "beginner", "python-2.x", "calculator" ], "Title": "Free time calculator" }
212570
<p>I made a password generator class in C++. I am not as familiar with C++ as I am with C, so I am looking for ways to move to a C++ mindset.</p> <p>I am also trying to use embedded practices like avoiding allocating memory on the fly and other non-deterministic stuff.</p> <p>I'll include the source file first, followed by the header, followed by the command line tool that is powered by this class.</p> <p><strong>passSingleton.cpp</strong></p> <pre><code>#include &lt;stdlib.h&gt; // atoi, rand #include &lt;iostream&gt; // cout, endl #include &lt;random&gt; // default_random_engine, uniform_int_distribution #include &lt;time.h&gt; // time #include "passSingleton.h" // class header passSingleton::passSingleton() { std::default_random_engine generator(time(NULL)); } passSingleton::passSingleton(unsigned int passLength) { passSingleton(); setPasswordLength(passLength); } void passSingleton::generatePass() /* Generates an ASCII password */ { int i; std::uniform_int_distribution&lt;int&gt; distribution(33,126); for(i = 0; i &lt; passwordLength; i++) { password[i] = distribution(generator); // ASCII chars between 33 - 126 } password[i] = '\0'; } int passSingleton::generatePass(unsigned int passLen) { if(setPasswordLength(passLen)) return -1; generatePass(); return 0; } char* passSingleton::getPass() { return password; } /* Sets password length to a positive int between 1 and MAX_PASS_LEN */ int passSingleton::setPasswordLength(unsigned int n) { if (n &lt; 8 || n &gt; MAX_PASS_LEN) { std::cerr &lt;&lt; "Password length must be between 8 and " &lt;&lt; MAX_PASS_LEN &lt;&lt; std::endl; exit(1); } passwordLength = n; return 0; } </code></pre> <p><strong>passSinglton.h</strong></p> <pre><code>#ifndef PASS_SINGLE_H #define PASS_SINGLE_H #include &lt;random&gt; // default_random_engine class passSingleton { public: passSingleton(); passSingleton(unsigned int passLength); void generatePass(); int generatePass(unsigned int passLen); char* getPass(); int setPasswordLength(unsigned int n); private: static const unsigned int MAX_PASS_LEN = 128; char password[MAX_PASS_LEN]; unsigned int passwordLength; std::default_random_engine generator; }; #endif </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; // cout, endl, cerr #include &lt;stdlib.h&gt; // atoi #include &lt;unistd.h&gt; // getopt #include &lt;fstream&gt; // ofstream #include "passSingleton.h" // passSingleton class void help(); void version(); int main(int argc, char** argv) { char* myPass = NULL; char* filePath = NULL; passSingleton myPassFact; int c; unsigned int passLen = 8; unsigned int qty = 0; std::ofstream myFile; if (1 == argc) { std::cout &lt;&lt; "Try `passgen -h' for more information" &lt;&lt; std::endl; std::cout &lt;&lt; "Usage: passgen -l PASSWORD_LENGTH" &lt;&lt; std::endl; return 0; } /* Get command line options */ while (-1 != (c = getopt(argc, argv, "hvl:f:q:"))) { int this_option_optind = optind ? optind : 1; switch (c) { case 'h': help(); break; case 'l': passLen = atoi(optarg); if (0 == qty) qty = 1; if (myPassFact.generatePass(passLen)) return -1; break; case 'v': version(); break; case 'f': filePath = optarg; break; case 'q': qty = atoi(optarg); break; case '?': break; default: break; } } /* Output block */ if (NULL != filePath) { myFile.open(filePath); } while (0 != qty--) { myPassFact.generatePass(); myPass = myPassFact.getPass(); if (NULL != filePath) myFile &lt;&lt; myPass &lt;&lt; std::endl; else { std::cout &lt;&lt; myPass &lt;&lt; std::endl; } } if (NULL != filePath) { myFile.close(); } return 0; } void help() { std::cout &lt;&lt; \ "Usage: passgen [OPTIONS] \n\ Generates an ASCII password PASSWORD_LENGTH characters long\n\ Example: passgen -l 32\n\ \n\ OPTIONS:\n\ -l PASSWORD_LENGTH specifies length of generated password\n\ -f FILE outputs password to specified file\n\ -h displays this help text\n\ -v displays version\n\ -q QTY generates QTY passwords" \ &lt;&lt; std::endl; } void version() { } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T21:48:45.193", "Id": "411213", "Score": "1", "body": "Welcome to Code Review. It seems like you're a beginner to C++ so you probably want to add [tag:beginner] to the tags. Also, you seem to know some OOP from other languages, feel free to add your background into your question. However, please keep in mind that the code should not get changed, now that a review has been posted." } ]
[ { "body": "<p>I would not make this to complicated. Your <code>passSingleton::generatePass()</code> method could simply return the password as a <code>std::string</code> with the password length as a parameter. Initialization of the random engine should be done from <code>main.cpp</code> and could also be passed as a parameter. Remove the class, keep the <code>generatePass()</code> method in main.</p>\n\n<p>The check of the password length should generate an exception. If you cannot use exceptions, because of your embedded context, return a <code>std::optional&lt;std::string&gt;</code> if you're on C++17 or a <code>std::tuple&lt;bool, std::string&gt;</code> where the <code>bool</code> indicates success and the <code>std::string</code> contains the result.</p>\n\n<p>When compiling, use at least <code>-Wall</code> it gives usefull hints on how to improve your code:</p>\n\n<pre><code>main.cpp:29:13: warning: unused variable 'this_option_optind'\n [-Wunused-variable]\n int this_option_optind = optind ? optind : 1;\n ^\n</code></pre>\n\n<p>Your application requires a minimum length of 8 characters, but if I run</p>\n\n<pre><code>sjank@WSDEBE16040-LXL&gt; ./main -q 3 \n!\n-\nh\n</code></pre>\n\n<p>the length defaults to <code>1</code>. Is a minimum length really reasonable? You could give a warning instead. Use a sensible default length and make the <code>-l</code> parameter optional. </p>\n\n<ul>\n<li><p>prefer <code>#include &lt;ctime&gt;</code> over <code>#include &lt;time.h&gt;</code>, remove <code>&lt;iostream&gt;</code> (see above) and <code>&lt;stdlib.h&gt;</code> (use <code>&lt;cstdlib&gt;</code> in c++).</p></li>\n<li><p>Is writing passwords to a file is required? Is it best practice of storing passwords? Could the user achieve the same functionality otherwise (redirect)? </p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T21:34:00.427", "Id": "212586", "ParentId": "212581", "Score": "1" } }, { "body": "<h3>I don't know where you are learning <code>C++</code> from, but this what you posted is basically <code>C</code> with classes.</h3>\n<hr />\n<p>That being said, I am just going to point out in a list what you can improve. You can find enough material on the internet for each of the points.</p>\n<ul>\n<li><p>Naming</p>\n<ul>\n<li>Name your classes starting with an uppercase, e.g. <code>passSingleton</code> should be <code>PassSingleton</code>, otherwise it might look like a function call to the reader.</li>\n<li>Name your classes, variables, etc. correctly, meaningfully, and written out, e.g. rename <code>passSingleton</code> to <strong><code>PasswordGenerator</code></strong></li>\n<li>Naming your generate function <code>generatePass()</code> is ambiguous (<em>pass</em> could be understood differently) and obsolete. Just name it <code>generate()</code> since your class is named <code>PasswordGenerator</code>.</li>\n</ul>\n</li>\n<li><p><strong>Use STL containers!!!</strong></p>\n<ul>\n<li>instead of <code>char password[MAX_PASS_LEN]</code> use <code>std::string password</code>. With <code>std::string</code> you can still access each character with <code>operator[]</code>.</li>\n<li>You are not using any other containers here, but for future, use <code>std::vector</code> instead of raw C arrays.</li>\n</ul>\n</li>\n<li><p>In <code>setPasswordLength()</code> you are calling <code>exit(1)</code> if some requirements are not set. Don't <code>exit</code> from a function, rather return a <code>bool</code> or <code>throw</code>. This way, the caller of the function can still react.</p>\n</li>\n<li><p><a href=\"https://stackoverflow.com/questions/13865842/does-static-constexpr-variable-make-sense\"><strong>constexpr</strong></a></p>\n<ul>\n<li>you can rewrite <code>static const unsigned int MAX_PASS_LEN = 128;</code> to <code>static constexpr unsigned int MAX_PASS_LEN = 128;</code></li>\n</ul>\n</li>\n<li><p>just return the generated password in <code>generate()</code>. You don't need to save the password since you are not using it anywhere else.\n<code>auto mypass = myPassFact.generatePass();</code> Doesn't this look way better?</p>\n</li>\n<li><p>In your <code>passSingleton</code> constructor, you are creating a local variable <code>generator</code> shadowing your member variable. Put the initialization of <code>generator</code> into the initializer list of the constructor.\n<code>passSingleton() : generator(time(nullptr)) {}</code></p>\n</li>\n<li><p><code>nullptr</code> instead of <code>NULL</code></p>\n</li>\n<li><p>consider using <a href=\"https://www.boost.org/doc/libs/1_63_0/doc/html/program_options.html\" rel=\"nofollow noreferrer\">Boost.Program Options</a> instead of manually trying to parse the command line arguments</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T22:31:05.947", "Id": "212589", "ParentId": "212581", "Score": "0" } }, { "body": "<ul>\n<li><p>Option handling is questionable.</p>\n\n<p>First, do not hardcode the program name (<code>passgen</code>) in the message. Use <code>argv[0]</code> (if the executable gets renamed, the original message would lie).</p>\n\n<p>Second, give help immediately. Forcing the user to invoke the program one more time just to see the help is a nuisance. Consider</p>\n\n<pre><code> if (1 == argc) {\n help();\n return 1;\n }\n</code></pre>\n\n<p>Notice <code>1</code>. Don't <code>return 0</code> on error. Your program could be invoked from the script, and the script should be informed that something undesirable happened.</p>\n\n<p>Third, it is reasonable to expect that unrelated options could be given in any order. Your code behaves differently depending on the order of <code>-l</code> and <code>-q</code>. If <code>-l</code> is given first, the latter <code>-q</code> is ignored.</p>\n\n<p>Finally, the default case shall tell what option seems wrong, and <em>also</em> print the help.</p></li>\n<li><p>File handling is scattered. Testing for <code>NULL != filePath</code> at three different points gives me shivers. Consider consolidating them either like</p>\n\n<pre><code> if (NULL != filePath) {\n myFile.open(filePath, iOS_base::app);\n myFile &lt;&lt; myPass &lt;&lt; std::endl;\n myFile.close();\n } else {\n std::cout &lt;&lt; myPass &lt;&lt; std::endl;\n }\n</code></pre>\n\n<p>(there is nothing wrong with opening the file multiple times), or <a href=\"https://en.cppreference.com/w/cpp/io/c/freopen\" rel=\"nofollow noreferrer\"><code>freopen</code></a> <code>stdout</code>. Don't forget to test the the file has been opened successfully.</p>\n\n<p>Better yet, always output to <code>stdout</code>, and let the user redirect as needed.</p></li>\n<li><p>Don't use magic numbers (<code>33,126</code>). BTW, why you don't allow a space?</p></li>\n<li><p>I understand the desire to avoid dynamic allocation. Just let the client provide the space for password(s).</p></li>\n<li><p>C++ is not Java. Don't strive to put everything in a class. I see no reason for <code>class passSingleton</code> to exist.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T04:49:11.450", "Id": "212600", "ParentId": "212581", "Score": "1" } } ]
{ "AcceptedAnswerId": "212586", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T21:06:20.047", "Id": "212581", "Score": "1", "Tags": [ "c++", "beginner", "object-oriented", "c++11" ], "Title": "Password generator class and CLI" }
212581
<p>At work, I find myself frequently crunching CSVs with headers prone to change names and location. I have a solution, but with no opportunity for code review I was hoping SE could offer a look</p> <p>header_indexer was built to allow me to us the same parsing code among spreadsheets where the data is known, but it's location prone to change. </p> <p>The indexer parses the header row and creates an index_calculated dictionary based on the below user generated dict, effectively translating the headers to find into their column indexes:</p> <pre><code>headers_dict = { # "reference": "header to find" "hostname": "DNSHostname", "track": "TrackingID", "OS": "OperatingSystem" } </code></pre> <p>(Adjusting "header to find" values ensures adaptability when spreadsheet format changes)</p> <p>Assuming we're using a header row like so...</p> <pre><code>spreadsheet[0] = ["Date", "Status", "TrackingID", "Title", "DNSHostname", "OperatingSystem"] </code></pre> <p>Feeding the header row and headers_dict to the below code, as arguments: sheet_headers=spreadsheet[0], head_names=headers_dict...</p> <pre><code>from typing import List, Dict def index_headers(sheet_headers: List[str], head_names: Dict[str, str], ignore_duplicates=False, ignore_nonindexed=False) -&gt; Dict[str, int]: """Builds and returns an Index calc dict based on the provided header row\n Provide headers row and head names dictionary""" # A dictionary of all header names from given CSV # For each column header, ndx_all[header] = header's index ndx_all = {} index = 0 for header in sheet_headers: ndx_all[header] = index index += 1 # Create new NEW_NDX entries based on HEAD_NAMES entries, using indexes stored in ndx_all ndx_calc = {} for key, val in head_names.items(): try: ndx_calc[key] = ndx_all[val] # Missing or unfound header. Address in later checks except (IndexError, KeyError): ndx_calc[key] = None # Check for non indexed headers, if allowed error_string = "\n" nonindexed = [] if not ignore_nonindexed: for key, val in ndx_calc.items(): if val is None: nonindexed.append([key, val]) # Prepare string out to display missing headers if nonindexed: error_string += "\nNon indexed headers!\n" + '\n'.join(str(x) for x in nonindexed) # Check for duplicate indexes, if allowed duplicates = [] dup_check = {} if not ignore_duplicates: for key, val in ndx_calc.items(): dup_check.setdefault(val, set()).add(key) for val in dup_check.values(): if len(val) &gt; 1: for k in val: duplicates.append([k, ndx_calc[k]]) # Prepare string out to display problem headers if duplicates: error_string += "\nDuplcate header indexes!\n" + '\n'.join(str(x) for x in duplicates) # Raise ValueError, if duplicates or nonindexed: raise ValueError(error_string) return ndx_calc </code></pre> <p>...creates and returns the following dict, corresponding to headers_dict above:</p> <pre><code>ndx_calc = { "hostname": 4, "track": 2, "OS": 5 } </code></pre> <p>I have some ideas of improvement, namely to prompt a query against all non-indexed headers when given values aren't found, but wanted to get some sort of feedback before I proceeded</p> <p>Thank you</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T03:19:02.497", "Id": "411235", "Score": "0", "body": "Some quick thoughts:\n\n ndx_all = {}\n index = 0\n for header in sheet_headers:\n ndx_all[header] = index\n index += 1`\n\ncan be replaced with\n\n ndx_all = {}\n for index, header in enumerate(sheet_headers):\n ndx_all[header] = index\n\nI'd recommend, if you're planning on extending this code out, splitting up the `index_header` function - have one function for new_ndx entries, checking for non-indexed headers, etc. I also am not sure if the dupe-check makes sense as is - at least, there's an easier way to de-dupe than that." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T21:19:05.890", "Id": "212582", "Score": "1", "Tags": [ "python", "csv" ], "Title": "Python Spreadsheet Header Indexer" }
212582
<p>Just had this as a practice test problem and I'm curious how to optimize for performance. Thanks!</p> <p>The greatest common divisor (GCD), also called the highest common factor (HCF) of N numbers is the largest positive integer that divides all numbers without giving a remainder.</p> <p>Write an algorithm to determin the GCD of N positive integers.</p> <pre><code>function generalizedGCD(num, arr) { // find the factors of lowest member of arr and then check if every other number is divisible arr.sort( function( a, b ) { return a-b; }); const lowest = arr[0]; const factors = []; for ( let i = 1; i &lt;= lowest; i++) { if ( lowest % i === 0 ) { factors.push(i); } } // now check to see if each member of the factors array divides into each member of the original numbers array. If not, remove it from the array. for ( let j = 1; j &lt; num; j++) { for ( let k = 0; k &lt; factors.length; k++) { if ( arr[j] % factors[k] != 0 ) { factors.splice( k, 1); } } } return factors[factors.length-1]; } </code></pre>
[]
[ { "body": "<p>As I am not a native in Javascript, I'll try to review your algorithm:</p>\n\n<ul>\n<li>start from the lowest value and its factor is a good idea to improve speed</li>\n<li>for your second loop I suggest you to start not from the lowest factor but start from the biggest factor. GCD is trying to find the biggest factor, So if you start from the biggest number, after you find a number that can divide all number in <code>arr</code> you can break your loop, it's more efficient.</li>\n<li>I've tested it with <code>generalizedGCD(2,[27,8])</code> and it returns <code>4</code> instead of 1, why? the problem is in your second loop, the size of <code>factors</code> changed after you delete its element and you accidentally \"skip\" some elements. If we try to simulate this with the example above:</li>\n</ul>\n\n<pre><code> generalizedGCD(2,[8,27])\n ...\n k=0 factors=[1,2,4,8] arr[j]=27 {27 is divisible with factors[k]=1}\n k=1 factors=[1,2,4,8] arr[1]=27 {27 is not divisible with factors[k]=2}\n k=2 factors=[1,4,8] arr[1]=27 {27 is not divisible with factors[k]=8} // you skipped 4\n ...\n factors=[1,4]\n</code></pre>\n\n<ul>\n<li>The solution that I can think is subtract <code>k</code> by 1 so it doesn't \"move\" when you are deleting an element in <code>factors</code>:</li>\n</ul>\n\n<pre><code> if ( arr[j] % factors[k] != 0 ) {\n factors.splice( k, 1);\n k--;\n }\n</code></pre>\n\n<hr>\n\n<p><strong>Suggestion for another algorithm</strong></p>\n\n<p>I think it'll be better if you use faster algorithm: <a href=\"https://www.geeksforgeeks.org/euclidean-algorithms-basic-and-extended/\" rel=\"nofollow noreferrer\">Euclid Algorithm</a>. You can find GCD of every number in array by find GCD each two of them.</p>\n\n<pre><code>GCD( GCD( GCD(a[0], a[1]), a[2]), ...)\n</code></pre>\n\n<p>It's simple recursion:</p>\n\n<pre><code>function gcd(a, b) {\n if(b === 0) {\n return a;\n }\n\n return gcd(b, a%b);\n}\n\nfunction generalizedGCD(num, arr)\n{\n factors = arr[0];\n\n for ( let i = 1; i &lt; num; i++) {\n factors = gcd(factors, arr[i])\n }\n\n return factors;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T00:34:48.493", "Id": "411226", "Score": "1", "body": "Did you run your code? You should, as there is endless recursion and throws a call stack overflow. Don't know how you got a +1 for it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T00:54:34.663", "Id": "411227", "Score": "0", "body": "@Blindman67 Thank you, sorry I made a mistake to not run it first, fixed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T01:15:54.020", "Id": "411228", "Score": "2", "body": "Yes always pays to test run first. Your code looks like you're a C or C++ coder. In JavaScript is very bad to not declare variables. `factors` is undeclared and thus becomes a global (or would throw in some contexts). Besides the point, code review is not about providing different solutions, you need to review the op's code, (it has a lot of problems you did not address) Pointing the OP to a alternative solution does not help them improve \"their\" code and coding skills." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T01:32:11.637", "Id": "411229", "Score": "1", "body": "@Blindman67 that's true, I'm used to code in C/C++, I only used Javascript once in a web project a few years ago, thank you so much for the suggestions. And I'm sorry, I'm new in this SE, actually I've felt I have given the wrong answer after I see how do people answer here. let this be a lesson for me. Thank you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T02:05:48.493", "Id": "411231", "Score": "1", "body": "Hi all, thanks for the feedback. @Malioboro, thanks for the solution -- it is in fact much more elegant than mine and I'm sure much faster. but like blindman67 said, it would in fact be much more helpful to get feedback on my code -- I'm a self-taught programmer and I have never done a formal code review at my job, ever. I'm simply trying to improve my fundamentals. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T02:59:16.073", "Id": "411233", "Score": "1", "body": "Another question: if the largest common divisor is 1 between the two numbers, it returns a instead of 1. How would you code that into the function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T06:55:14.963", "Id": "411243", "Score": "1", "body": "@qotsa42 I've updated my answer" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T00:00:55.323", "Id": "212593", "ParentId": "212591", "Score": "3" } }, { "body": "<p>I'll stick with your brute-force approach. Your code is doing more work than necessary:</p>\n\n<ul>\n<li><p>You sort the input array. This has multiple issues.</p>\n\n<ol>\n<li>Performance-wise, you seem to sort only to get the minimum element. Just use <code>Math.min</code>.</li>\n<li>From an API perspective, the user of your function may be surprised to find that their input array gets sorted. Thus if you wanted to sort the array internally, you should either do a <code>.slice()</code> to copy the array, or at least document the mutation very explicity.</li>\n<li>The combination of <code>num</code> and <code>.sort()</code> is buggy (I presume). The <code>num</code> parameter seems to be there so that the user can get GCD of only a portion of the array. However, you sort the <em>entire</em> array, so your code is taking GCD of only the least <code>num</code> elements. (If this is the intended behaviour, document it.)</li>\n</ol></li>\n<li><p>You collect an array of all the common factors, only to get the greatest. You may dispense of the <code>factors</code> array altogether by looping over the possible factors reversely, and immediately returning as soon as you find a suitable one. (That also avoids the potentially not-so-fast <code>splice</code> operation.)</p></li>\n</ul>\n\n<p>Here is an updated code:</p>\n\n<pre><code>function generalizedGCD(num, arr) {\n // Use spread syntax to get minimum of array\n const lowest = Math.min(...arr);\n\n for (let factor = lowest; factor &gt; 1; factor--) {\n let isCommonDivisor = true;\n\n for (let j = 0; j &lt; num; j++) {\n if (arr[j] % factor !== 0) {\n isCommonDivisor = false;\n break;\n }\n }\n\n if (isCommonDivisor) {\n return factor;\n }\n }\n\n return 1;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T09:21:16.777", "Id": "212678", "ParentId": "212591", "Score": "3" } } ]
{ "AcceptedAnswerId": "212678", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T23:44:05.520", "Id": "212591", "Score": "4", "Tags": [ "javascript", "algorithm" ], "Title": "Find the greatest common divisor of n numbers" }
212591
<p>I've tried implementing <a href="https://en.wikipedia.org/wiki/Locality-sensitive_hashing" rel="nofollow noreferrer">Locality Sensitive Hash</a>, the algorithm that helps recommendation engines, and powers apps like Shazzam that can identify songs you heard at restaurants.</p> <p>LSH is supposed to run far quicker than vanilla Nearest Neighbor, but alas mine is 10x slower. Can I get a hand?</p> <pre><code>Times: nearest neighbor: 0.0012996239820495248 lsh : 0.012921262998133898 </code></pre> <p>I've kept things clean, and marginally documented, and it includes a test for timing as well as to compare the results:</p> <pre><code>import numpy as np from scipy.spatial.distance import cosine import timeit np.random.seed(0) np.set_printoptions(precision=3, suppress=True) # ---------- # vanilla Nearest Neighbor def nearest_neighbor(X, q, n=1): ''' Nearest Neighbor, uses euclidean distance X :: data; ndarray(samples, dimensions) q :: query point; ndarray(dimensions) n :: number of neighbors to return ''' dist = np.sqrt(np.sum((X - q) ** 2, axis=1)) return X[dist.argsort()[:n]] # ---------- # Cosine similarity of a matrix row-wise compared to a query vector def cosine_mat1(X, q): return np.apply_along_axis(lambda x: cosine(x, q), 1, X) def cosine_mat2(X, q): out = np.zeros(X.shape[0]) for ix, x in enumerate(X): out[ix] = cosine(x, q) return out def cosine_mat3(X, q): Xq = np.sum(X * q, axis=1) XX = np.sum(X ** 2, axis=1) qq = np.sum(q ** 2) return 1.0 - Xq / np.sqrt(XX * qq) # ---------- # Locality Sensitive Hash def nearest_neighbor_lsh(X, q, hash_len, n=1): ''' Locality Sensitive Hashing X :: data points; ndarray(data point, dimension) q :: query ''' hyperslope = np.random.normal(size=(hash_len, X.shape[1])) hyperbias = np.random.normal(size=hash_len) hashes = ((np.einsum('hd,nd-&gt;nh', hyperslope, X) + hyperbias) &gt; 0) q_hash = ((np.einsum('hd,d-&gt;h', hyperslope, q) + hyperbias) &gt; 0) cosine_similarity = cosine_mat3(hashes, q_hash) return X[cosine_similarity.argsort()[:n]] # ---------- # Timing samples = 10000 dims = 5 nearest_k = 10 hash_len = 100 X = np.random.normal(size=(samples, dims)) # 100 5D samples q = np.ones(dims) * 0 print() t1 = timeit.Timer('nearest_neighbor(X, q, n=nearest_k)', 'from __main__ import nearest_neighbor, X, q, nearest_k') print('nearest neighbor: ', t1.timeit(number=1)) t2 = timeit.Timer('nearest_neighbor_lsh(X, q, hash_len=hash_len, n=nearest_k)', 'from __main__ import nearest_neighbor_lsh, X, q, nearest_k, hash_len') print('lsh : ', t2.timeit(number=1)) # ---------- # Check accuracy c1 = nearest_neighbor(X, q, n=nearest_k) c2 = nearest_neighbor_lsh(X, q, hash_len=hash_len, n=nearest_k) print() print('avg distance to neighbors: ', np.mean(np.sqrt(np.sum((c1 - q) ** 2, axis=1)))) print('avg distance using lsh : ', np.mean(np.sqrt(np.sum((c2 - q) ** 2, axis=1)))) rs = X[np.random.randint(samples, size=nearest_k*100)] # random samples print('avg distance to random : ', np.mean(np.sqrt(np.sum((rs - q) ** 2, axis=1)))) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T23:50:58.077", "Id": "212592", "Score": "3", "Tags": [ "python", "algorithm", "numpy", "clustering", "hashcode" ], "Title": "Locality Sensitive Hash (similar to k-Nearest Neighbor), in Python+Numpy" }
212592
<p>I have coded a web-based Excel file builder and sender, that serves the file over Http(example links in code). I would like to see improvements and any suggestions you might have.</p> <pre><code>using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading; //goals //reduce overall complexity. //refine code to take the least amount of execution steps to process a command. //write a more functional server that can handle multiple clients namespace ServeReports { public class ServeReports { public static DataSet reports = new DataSet("Reports"); private const int PORT = 8183; private const int MAX_THREADS = 4; private const int DATA_READ_TIMEOUT = 2_000_000; private const int STORAGE_SIZE = 1024; private static WaitHandle[] waitHandles; private static HttpListener listener; private struct ThreadParams { public AutoResetEvent ThreadHandle; public HttpListenerContext ClientSocket; public int ThreadIndex; } [Serializable] public class TemplateObject { public string NameOfReport { get; set; } public string[] Format { get; set; } public string[,] Content { get; set; } } [Serializable] public class TemplateContainer { public TemplateObject TObject = new TemplateObject(); public string[] ContentArray { get; set; } public int FormatLength { get; set; } public int ContentLength { get; set; } } public static void Config() { if (!Directory.Exists(Directory.GetCurrentDirectory() + "\\Configs")) { Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\Configs"); } if (!Directory.Exists(Directory.GetCurrentDirectory() + "\\Worksheets")) { Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\Worksheets"); } } public static bool TemplateInit(string reportName, string[] header, bool createNew, HttpListenerContext socket) { if (TemplateInit(reportName, header, createNew)) { socket.Response.OutputStream.Write(Encoding.UTF8.GetBytes("Successfully Initialized " + reportName), 0, ("Successfully Initialized " + reportName).Length); return true; } socket.Response.OutputStream.Write(Encoding.UTF8.GetBytes("Failed Initialization " + reportName), 0, ("Failed Initialization " + reportName).Length); return false; } //initializes Excel Template //&lt;Parameter&gt; ReportName: Names the Sheet and Excel //&lt;Parameter&gt; Header : array of values //&lt;Parameter&gt; CreateNew : boolean indicating if the template needs to be created or updated. public static bool TemplateInit(string reportName, string[] header, bool createNew) { string reportString = reportName; BinaryFormatter binFormatter = new BinaryFormatter(); if (header.Length != 0) { //Handle Creation of new template if (createNew) { try { //build and store template TemplateContainer Template = new TemplateContainer(); //name the report Template.TObject.NameOfReport = reportName; //StoreLength Template.FormatLength = header.Length; //initialize the format string Template.TObject.Format = new string[Template.FormatLength]; //fill out the Format header.CopyTo(Template.TObject.Format, 0); //serialize Template to remember the reports we have setup. FileStream fs = new FileStream(Directory.GetCurrentDirectory() + "\\Configs\\" + reportString, FileMode.Create, FileAccess.Write, FileShare.None); binFormatter.Serialize(fs, Template); fs.Close(); return true; } //write all exceptions to console window on server catch (Exception ex) { throw ex; } //clean up finally { binFormatter = null; } } //UPDATE Template else { try { //check if report config exists if (File.Exists(Directory.GetCurrentDirectory() + "\\Configs\\" + reportString)) { //Deserialize TemplateObject FileStream fs = new FileStream(Directory.GetCurrentDirectory() + "\\Configs\\" + reportString, FileMode.Open, FileAccess.Read, FileShare.None); TemplateContainer Template = (TemplateContainer)binFormatter.Deserialize(fs); fs.Close(); //write out the header Template.TObject.Format = new string[header.Length]; header.CopyTo(Template.TObject.Format, 0); //realign content if possible if (Template.ContentLength &gt; 0 &amp;&amp; Template.ContentLength % Template.FormatLength == 0) { TemplateFill(reportName, Template.ContentArray); } fs = new FileStream(Directory.GetCurrentDirectory() + "\\Configs\\" + reportString, FileMode.Open, FileAccess.Write, FileShare.None); binFormatter.Serialize(fs, Template); fs.Close(); return true; } else { Console.Write("Configuration does not exist, can not update what does not exist."); return false; } } catch (Exception ex) { throw ex; } finally { binFormatter = null; } } } return false; } public static bool TemplateFill(string reportName, string[] content, HttpListenerContext socket) { if (TemplateFill(reportName, content)) { socket.Response.OutputStream.Write(Encoding.UTF8.GetBytes(reportName + " successfully filled"), 0, (reportName + " successfully filled").Length); return true; } socket.Response.OutputStream.Write(Encoding.UTF8.GetBytes(reportName + " fill failed"),0, (reportName + " fill failed").Length); return false; } //Fill in Template content //&lt;Parameter&gt; ReportName: Names the Sheet and Excel //&lt;Parameter&gt; Content : array of values public static bool TemplateFill(string reportName, string[] content) { if (content == null) { throw new ArgumentNullException(nameof(content)); } string reportString = reportName; BinaryFormatter binFormatter = new BinaryFormatter(); TemplateContainer Template = new TemplateContainer(); try { //check if report config exists if (File.Exists(Directory.GetCurrentDirectory() + "\\Configs\\" + reportString)) { FileStream fs = new FileStream(Directory.GetCurrentDirectory() + "\\Configs\\" + reportString, FileMode.Open, FileAccess.Read, FileShare.None); Template = (TemplateContainer)binFormatter.Deserialize(fs); fs.Close(); if (content.Length % Template.FormatLength == 0) { int NumberOfRowsToAdd = content.Length / Template.FormatLength; int row = 0; int Column = 0, pColumn = 0; Template.TObject.Content = new string[NumberOfRowsToAdd, Template.FormatLength]; do { Template.TObject.Content[row, pColumn] = content[Column]; Column = Column + 1; pColumn = pColumn + 1; if (pColumn == Template.FormatLength) { row = row + 1; pColumn = 0; } } while (Column &lt; (Template.FormatLength * NumberOfRowsToAdd)); Template.ContentArray = content; Template.ContentLength = content.Length; FileStream fe = new FileStream(Directory.GetCurrentDirectory() + "\\Configs\\" + reportString, FileMode.Open, FileAccess.Write, FileShare.None); binFormatter.Serialize(fe, Template); fe.Close(); return true; } } return false; } catch (Exception ex) { throw ex; } finally { binFormatter = null; } } //Build the Excel File from TemplateObject public static DataSet AddSheet(string reportName, ref DataSet ds) { string reportString = reportName; DataTable dt = new DataTable(reportName) { Locale = CultureInfo.CurrentCulture }; //init serializer BinaryFormatter binFormatter = new BinaryFormatter(); try { //check if report config exists if (File.Exists(Directory.GetCurrentDirectory() + "\\Configs\\" + reportString)) { //Deserialize it FileStream fs = new FileStream(Directory.GetCurrentDirectory() + "\\Configs\\" + reportString, FileMode.Open, FileAccess.Read, FileShare.None); TemplateContainer template = (TemplateContainer)binFormatter.Deserialize(fs); fs.Close(); //write out the format for (int i = 1; i &lt; template.TObject.Format.Length + 1; i++) { dt.Columns.Add(template.TObject.Format[i - 1]); } //get the numer of rows to add int NumberOfRowsToAdd = template.TObject.Content.Length / template.TObject.Format.Length; //get the working row for (int rows = 0; rows &lt; NumberOfRowsToAdd; rows++) { string[] array = new string[template.TObject.Format.Length]; for (int columns = 0; columns &lt; template.TObject.Format.Length; columns++) { array[columns] = template.TObject.Content[rows, columns]; } object[] dr = dt.NewRow().ItemArray = array; dt.Rows.Add(dr); } ds.Tables.Add(dt); return ds; //handle error } else { //log.Error("No Configuration file setup for this action."); return ds; } } catch (Exception ex) { throw ex; } } public static void DataSetToExcel(DataSet ds, string destination) { try { using (SpreadsheetDocument workbook = SpreadsheetDocument.Create(Directory.GetCurrentDirectory() + "\\Worksheets\\" + destination + ".xlsx", SpreadsheetDocumentType.Workbook, true)) { workbook.AddWorkbookPart(); workbook.WorkbookPart.Workbook = new Workbook { Sheets = new Sheets() }; uint sheetId = 1; foreach (DataTable table in ds.Tables) { // workbook.WorkbookPart.Workbook.ExcelNamedRange(table.TableName, table.TableName, "A", "1", "I", "1"); WorksheetPart sheetPart = workbook.WorkbookPart.AddNewPart&lt;WorksheetPart&gt;(); SheetData sheetData = new SheetData(); sheetPart.Worksheet = new Worksheet(sheetData); Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild&lt;Sheets&gt;(); string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart); if (sheets.Elements&lt;Sheet&gt;().Count() &gt; 0) { sheetId = sheets.Elements&lt;Sheet&gt;().Select(s =&gt; s.SheetId.Value).Max() + 1; } Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName }; sheets.Append(sheet); Row headerRow = new Row(); List&lt;string&gt; columns = new List&lt;string&gt;(); foreach (DataColumn column in table.Columns) { columns.Add(column.ColumnName); Cell cell = new Cell { DataType = CellValues.String, CellValue = new CellValue(column.ColumnName) }; headerRow.AppendChild(cell); } sheetData.AppendChild(headerRow); foreach (DataRow dsrow in table.Rows) { Row newRow = new Row(); foreach (string col in columns) { Cell cell = new Cell { DataType = CellValues.String, CellValue = new CellValue(dsrow[col].ToString()) // }; newRow.AppendChild(cell); } sheetData.AppendChild(newRow); } } } } catch (Exception ex) { throw ex; } } public static void CreateServer() { Config(); waitHandles = new WaitHandle[MAX_THREADS]; for (int i = 0; i &lt; MAX_THREADS; ++i) { waitHandles[i] = new AutoResetEvent(true); } listener = new HttpListener(); listener.Prefixes.Add("http://127.0.0.1:8183/"); listener.Start(); while (true) { //Console.WriteLine("Waiting for a connection"); HttpListenerContext sock = listener.GetContext(); // Console.WriteLine("Got a connection"); //Console.WriteLine("Waiting for idle thread"); int index = WaitHandle.WaitAny(waitHandles); //Console.WriteLine("Starting new thread to process client"); ThreadParams context = new ThreadParams() { ThreadHandle = (AutoResetEvent)waitHandles[index], ClientSocket = sock, ThreadIndex = index }; ThreadPool.QueueUserWorkItem(ProcessSocketConnection, context); } } private static void ProcessSocketConnection(object threadState) { ThreadParams state = (ThreadParams)threadState; //Console.WriteLine($"Thread {state.ThreadIndex} is processing connection{state.ClientSocket.RemoteEndPoint}"); // This should be an extra method. In general this code should be more modular! byte[] recievBuffer = Encoding.UTF8.GetBytes(state.ClientSocket.Request.RawUrl); // Do your data Processing in this Method. DoWork(state.ClientSocket, recievBuffer); Cleanup(); // This is a local Function introduced in c#7 void Cleanup() { //Console.WriteLine("Doing clean up tasks"); state.ClientSocket.Response.Close(); recievBuffer = new byte[STORAGE_SIZE]; state.ThreadHandle.Set(); } } private static void DoWork(HttpListenerContext client, byte[] data) { byte[] amp = Encoding.UTF8.GetBytes("&amp;"); //Controller For API ReadOnlySpan&lt;byte&gt; sdata = data.AsSpan&lt;byte&gt;(); //API Build report template Columns //&lt;Parameter&gt; reportname: name of report to create or update //&lt;Parameter&gt; header: comma delimenated column names. //&lt;Parameter&gt; createnew: true/false to create or update the report //the below example will create a new Template Object with the format set to values passed to the header parameter //http://127.0.0.1:8183/?reportname=DynamicReport&amp;header=field1,field2,field3,field4&amp;createnew=true //the next example matches the existing report by name and updates the header to the new values passed //http://127.0.0.1:8183/?reportname=DynamicReport&amp;header=column1,column2,column3,column4&amp;createnew=false if (sdata.StartsWith(Encoding.UTF8.GetBytes("/?reportname=")) &amp;&amp; sdata.IndexOf(Encoding.UTF8.GetBytes("&amp;header=")) &gt; 0 &amp;&amp; sdata.IndexOf(Encoding.UTF8.GetBytes("&amp;createnew=")) &gt; 0) { //string testing = Encoding.UTF8.GetString(sdata.ToArray()); ReadOnlySpan&lt;byte&gt; name = sdata.Slice(13); name = name.Slice(0, name.IndexOf(amp)); ReadOnlySpan&lt;byte&gt; header = sdata.Slice(13 + name.Length + 8); header = header.Slice(0, header.IndexOf(amp)); bool screate = sdata.Slice(sdata.LastIndexOf(amp) + 11).SequenceEqual(Encoding.UTF8.GetBytes("true")) ? true : false; //Must Overload this method TemplateInit(Encoding.UTF8.GetString(name.ToArray()), Encoding.UTF8.GetString(header.ToArray()).Split(','), screate, client); } //API Add report data //&lt;Parameter SET&gt; /?reportname=nameOfReport: name of report to add content to //&lt;Parameter SET&gt; &amp;content=: comma delimenated column values //example //http://127.0.0.1:8183/?reportname=DynamicReport&amp;content=1,2,3,4,a,b,c,d else if (sdata.StartsWith(Encoding.UTF8.GetBytes("/?reportname=")) &amp;&amp; sdata.IndexOf(Encoding.UTF8.GetBytes("&amp;content=")) &gt; 0) { ReadOnlySpan&lt;byte&gt; name = sdata.Slice(13); name = name.Slice(0, name.IndexOf(amp)); ReadOnlySpan&lt;byte&gt; content = sdata.Slice(13 + name.Length + 9); //Must Overload this method TemplateFill(Encoding.UTF8.GetString(name.ToArray()), Encoding.UTF8.GetString(content.ToArray()).Split(','), client); AddSheet(Encoding.UTF8.GetString(name.ToArray()), ref reports); } //API GET resulting report by name //&lt;Parameter SET&gt; /?getreport=nameOfReport //example //http://127.0.0.1:8183/?getreport=DynamicReeport else if (sdata.StartsWith(Encoding.UTF8.GetBytes("/?getreport="))) { ReadOnlySpan&lt;byte&gt; name = sdata.Slice(12); DataSetToExcel(reports, Encoding.UTF8.GetString(name.ToArray())); long len = new FileInfo(Directory.GetCurrentDirectory() + "\\Worksheets\\" + Encoding.UTF8.GetString(name.ToArray()) + ".xlsx").Length; DeliverFile(client, Encoding.UTF8.GetString(name.ToArray()) + ".xlsx", int.Parse(len.ToString())); } //API Query available reports //&lt;Parameter&gt; "/?reports" : basic request to list available reports //example //http://127.0.0.1:8183/?reports else if (sdata.StartsWith(Encoding.UTF8.GetBytes("/?report"))) { string sbdata = "&lt;center&gt;&lt;p&gt;Available Reports&lt;/p&gt;&lt;table&gt;"; foreach (string file in Directory.EnumerateFiles(Directory.GetCurrentDirectory() + "\\Worksheets\\", "*.xlsx")) { sbdata += "&lt;tr&gt;&lt;td&gt;" + Path.GetFileName(file) + "&lt;/td&gt;&lt;/tr&gt;"; } sbdata += "&lt;/table&gt;&lt;/center&gt;"; client.Response.OutputStream.Write(Encoding.UTF8.GetBytes(sbdata), 0, sbdata.Length); } } public static void DeliverFile(HttpListenerContext client, string fileName, int contentLength, string mimeHeader = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", int statusCode = 200) { HttpListenerResponse response = client.Response; try { string prevDirectory = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory(prevDirectory + "\\Worksheets\\"); response.StatusCode = statusCode; response.StatusDescription = "OK"; response.ContentType = mimeHeader; response.ContentLength64 = contentLength; response.AddHeader("Content-disposition", "attachment; filename=" + fileName); response.SendChunked = false; using (BinaryWriter bw = new BinaryWriter(response.OutputStream)) { byte[] bContent = File.ReadAllBytes(fileName); bw.Write(bContent, 0, bContent.Length); bw.Flush(); bw.Close(); } Directory.SetCurrentDirectory(prevDirectory); //Console.WriteLine("Total Bytes : " + ContentLength.ToString()); } catch (Exception ex) { //Console.WriteLine(ex.Message); } } } internal static class Program { /// &lt;summary&gt; /// The main entry point for the application. /// &lt;/summary&gt; [STAThread] private static void Main() { ServeReports.CreateServer(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T09:47:29.330", "Id": "411262", "Score": "1", "body": "Few quick points (I don't have time to write a full reply at the moment) - don't put 2 classes in one file, don't have your classes so big (see 'SRP'), why are you so heavy on the statics? There is a time and place for them. Never `throw ex;`, just `throw;` (you lose valuable data e.g. stacktrace when 'rethrowing' like this). It's safe to call `Directory.CreateDirectory` even if the directory already exists (in your `Config()` method)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T12:31:32.023", "Id": "411284", "Score": "0", "body": "Thank you for the tips I have taken what you said, and implemented some of the changes. I localized all static variables, but I am unsure how best to attack all my static functions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T03:45:42.927", "Id": "412557", "Score": "0", "body": "took you tips and made changes . :) code located here https://github.com/BanalityOfSeeking/ServeExcel" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T00:24:06.747", "Id": "212594", "Score": "1", "Tags": [ "c#", "excel", "http", "server" ], "Title": "HttpListener Server for building reports in Excel" }
212594
<p>I wrote a <code>updater_thread()</code> and a <code>reader_thread()</code>, and used <code>lock_guard</code> to protect a global instance.</p> <h2>Question</h2> <ol> <li><p>I've never used <code>lock_guard</code>. In this code, is <code>lock_guard</code> used properly?</p> </li> <li><p>Is this code thread-safe?</p> </li> </ol> <h2>Code</h2> <pre><code>#include &lt;iostream&gt; #include &lt;thread&gt; #include &lt;mutex&gt; #include &lt;iterator&gt; #include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;initializer_list&gt; #include &lt;unistd.h&gt; class C { std::vector&lt;int&gt; v; std::mutex mutex_; public: C() {} void Update(const std::vector&lt;int&gt; &amp;new_v) { std::lock_guard&lt;std::mutex&gt; lock(mutex_); v = new_v; } bool Check(const int x){ std::lock_guard&lt;std::mutex&gt; lock(mutex_); return std::find(v.begin(), v.end(), x) != v.end(); } /* dump() is not essential */ void dump() { std::lock_guard&lt;std::mutex&gt; lock(mutex_); std::cout &lt;&lt; &quot;dump: &quot;; std::copy(v.begin(), v.end(), std::ostream_iterator&lt;int&gt;(std::cout, &quot; &quot;)); std::cout &lt;&lt; &quot;\n&quot;; } }; // create an instance gloablly C g_c; void updater_thread() { std::cout &lt;&lt; &quot;start updater_thread\n&quot;; while (true) { std::vector&lt;int&gt; v; for (int i = 0; i &lt; 10; i++) { v.push_back(rand() % 10 + 1); } std::sort(v.begin(), v.end()); g_c.Update(v); std::cout &lt;&lt; &quot;updated!!!\n&quot;; std::copy(v.begin(), v.end(), std::ostream_iterator&lt;int&gt;(std::cout, &quot; &quot;)); std::cout &lt;&lt; &quot;\n&quot;; sleep(5); } } void reader_thread() { std::vector&lt;int&gt; v {1,2,3,5}; while (true) { std::cout &lt;&lt; &quot;check: non-exist item: &quot;; for (int i = 0; i &lt; v.size(); i++) { if (!g_c.Check(v[i])){ std::cout &lt;&lt; v[i] &lt;&lt; &quot; &quot;; } } std::cout &lt;&lt; &quot;\n&quot;; sleep(1); } } int main() { std::thread t_up(updater_thread); std::thread t_r(reader_thread); t_up.join(); t_r.join(); } </code></pre>
[]
[ { "body": "<p>Yes, that all looks correct to me!</p>\n\n<p>You don't use anything from <code>&lt;unistd.h&gt;</code> (non-standard) or <code>&lt;initializer_list&gt;</code> (obscure), so I recommend removing those includes.</p>\n\n<hr>\n\n<p>You sigil the <code>mutex_</code> data member with an underscore, but you don't sigil the <code>v</code> member. I recommend being consistent:</p>\n\n<pre><code>std::mutex mutex_;\nstd::vector&lt;int&gt; v_;\n</code></pre>\n\n<p>Personally I would spell the member's name <code>mtx_</code>, but that's just a personal habit; I don't know if that naming convention is widespread. (<code>cv_</code> for a condition variable certainly is, though!)</p>\n\n<hr>\n\n<p>Consider that your <code>Check</code> and <code>dump</code> methods don't need to mutate the object, so they should be declared <code>const</code>. This means that your <code>mutex_</code> data member will need to be declared <code>mutable</code> so that you can still lock and unlock it inside your <code>const</code> member functions.</p>\n\n<p>Also, consider picking a capitalization rule and sticking to it. Why <code>Check</code> and <code>Update</code> but <code>dump</code> (not <code>Dump</code>)?</p>\n\n<p><code>Check</code>'s parameter <code>x</code> is marked <code>const</code> but that marking serves no purpose: eliminate it. (<a href=\"https://quuxplusone.github.io/blog/2019/01/03/const-is-a-contract/\" rel=\"nofollow noreferrer\">Const is a contract.</a>)</p>\n\n<hr>\n\n<pre><code>for (int i = 0; i &lt; v.size(); i++) {\n if (!g_c.Check(v[i])){\n std::cout &lt;&lt; v[i] &lt;&lt; \" \";\n }\n}\n</code></pre>\n\n<p>This could be rewritten more concisely as</p>\n\n<pre><code>for (int vi : v) {\n if (!g_c.Check(vi)) {\n std::cout &lt;&lt; vi &lt;&lt; \" \";\n }\n}\n</code></pre>\n\n<p>Your multithreading stuff all looks great!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T02:06:09.127", "Id": "212598", "ParentId": "212597", "Score": "2" } } ]
{ "AcceptedAnswerId": "212598", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T01:46:29.273", "Id": "212597", "Score": "2", "Tags": [ "c++", "beginner", "multithreading" ], "Title": "Sharing data with another thread using lock_guard" }
212597
<p>This is built with Python 2.7.15.</p> <p>The goal of this script is to count the number of words spoken by each Senator on the floor of Congress between given dates.</p> <p>It pulls from the Congressional Record, cuts out the sections not spoken on the floor (eg lists of Amendments) and returns a count of words by senator. The current list of senators is from the 115th Congress, from 2017 to 2018</p> <pre><code># -*- coding: utf-8 -*- from requests import get # to make GET request import time from datetime import date, timedelta import os.path import textract import re import csv import sys #download URLs def downloadPDF(url, file_name): #get request response = get(url) content_type = response.headers.get('content-type') if content_type == "application/pdf": # open in binary mode save_path = '/Users/One/Document/Workspace/Projects/Senate/Congressional_Record/' path = os.path.join(save_path, file_name) with open(path, "wb") as file: #write to file file.write(response.content) return 'SUCCESS' #download congressional records and extract text def downloadConRecords(startDate, endDate): #YYYYMMDD #initialize lists congressionalRecords = [] dates = [] #convert args to date-type startDate = str(startDate) endDate = str(endDate) startDate = date(int(startDate[0:4]),int(startDate[4:6]),int(startDate[6:8])) endDate = date(int(endDate[0:4]),int(endDate[4:6]),int(endDate[6:8])) #list all the days to check range = endDate - startDate i=0 while i &lt;= range.days: dates += [str(startDate + timedelta(days=i))] i+=1 #try URL, download PDF, add to list object for i in dates: YYYY = i[0:4] MM = i[5:7] DD = i[8:10] url = ('https://www.congress.gov/crec/' + YYYY + '/'+ MM + '/' + DD + '/CREC-' + YYYY + '-' + MM + '-' + DD + '-senate.pdf') filename = (YYYY+MM+DD+".pdf") time.sleep(20) if downloadPDF(url,filename) == "SUCCESS": print(url) textExtract = [] textExtract = textract.process('/Users/One/Document/Workspace/Projects/Senate/Congressional_Record/' + filename) #makes a list with the filename and the text entry = [url, filename[:-4].strip(), textExtract] congressionalRecords += [entry] return congressionalRecords #process the congressional records def cleanRecords(congressionalRecords, phraseDelete, segmentStart, segmentEnd): #eliminate n/, phrases, segments for record in congressionalRecords: clean = [] dump = [] clean = record[2].split('\n') clean = " ".join(clean) for i in phraseDelete: clean = clean.replace(i,'') for start in enumerate(segmentStart): erase = re.findall('{}.*?{}'.format(start[1], segmentEnd), clean) clean = re.sub('{}.*?{}'.format(start[1], segmentEnd), ' ', clean) dump += [erase] record += [clean] record += [dump] return congressionalRecords #split the text into sections based on the speaker def multiDelimStringSplitter(aString, separators): # separators is an array of strings that are being used to split the the string. # sort separators in order of descending length separators.sort(key=len) listToReturn = [] rows = [] l = [] i = 0 while i &lt; len(aString): theSeparator = "" for current in separators: if current == aString[i:i+len(current)]: #if this section is the separateor, then set the variable to that separator theSeparator = current if theSeparator != "": listToReturn += [theSeparator] i = i + len(theSeparator) else: if listToReturn == []: listToReturn = [""] if(listToReturn[-1] in separators): listToReturn += [""] #adds the text one character at a time listToReturn[-1] += aString[i] i += 1 i = 0 listToReturn = listToReturn[1:len(listToReturn)] while (i+1) &lt; len(listToReturn): #initialize entry with speaker and text entry = listToReturn[i:i+2] #get word count and add it to the entry text = listToReturn[i+1] #strip punctuation out of the string text = re.sub(r'[^\w\s]','',text) wordcount = str(len(text.split())) entry += [wordcount] #add the entry as its own list rows.append(entry) i += 2 return rows #get information on the records, speakers and word counts def writeAnalytics(congressionalRecords, senators): textExport = [['url','date','extractRaw','extractClean']] textDump = [['date','extractDump']] speechExport = [['date','speaker','text','wordCount']] speakerExport = [['date','speaker','wordCount']] speakerAnalytics = [['startDate', 'endDate', 'speaker', 'wordCount']] perSpeakerTotal = [] recordDates = [] for i in senators: # wordsperSpeech += [i,0] perSpeakerTotal += [i,0] #add delimiter separated text extracts for record in congressionalRecords: splitLines = [] wordsperSpeaker = [] #initialize the lists for i in senators: # wordsperSpeech += [i,0] wordsperSpeaker += [i,0] #split the extracts into each speech splitLines = multiDelimStringSplitter(record[3],senators) record += [splitLines] #prep the dump export for i in record[4]: if len(i) &gt; 0: textDump += [[record[1], i]] #add the words per speaker for speech in record[5]: speechExport += [[record[1],speech[0],speech[1],speech[2]]] #find the speaker -&gt; pull that person's wordsperSpeaker and add the speech's word count wordsperSpeaker[wordsperSpeaker.index(speech[0])+1] += int(speech[2]) record += [wordsperSpeaker] textExport += [[record[0],record[1],record[2],record[3]]] recordDates += [record[1]] #prepare export for the words per speaker for i in senators: speakerExport += [[record[1],i, wordsperSpeaker[wordsperSpeaker.index(i)+1]]] #add word counts for senators who spoke #find senator's index in perSpeaker total -&gt; add the words spoken in that session (record) perSpeakerTotal[perSpeakerTotal.index(i)+1] += record[6][record[6].index(i)+1] for i in senators: speakerAnalytics += [[min(recordDates), max(recordDates), i, perSpeakerTotal[perSpeakerTotal.index(i)+1]]] return textExport, textDump, speechExport, speakerExport, speakerAnalytics #export to CSV def exportCSV(flatList, filename): with open(filename+".csv", "wb") as f: writer = csv.writer(f) writer.writerows(flatList) phraseDelete = [ ',', 'This ‘‘bullet’’ symbol identifies statements or insertions which are not spoken by a Member of the Senate on the floor.' ] segmentStart = [ ' PRAYER ', ' PLEDGE OF ALLEGIANCE ', ' APPOINTMENT OF ACTING PRESIDENT PRO TEMPORE ', ' CERTIFICATES OF ELECTION ', ' MESSAGE FROM THE HOUSE ', ' MESSAGES FROM THE PRESIDENT ', ' EXECUTIVE MESSAGES REFERRED ', ' LIST OF SENATORS BY STATES ', ' PRESIDENTIAL MESSAGES ', ' ENROLLED BILLS PRESENTED ', ' MEASURES REFERRED ', ' EXECUTIVE AND OTHER COMMUNICATIONS ', ' REPORTS OF COMMITTEES ', ' EXECUTIVE REPORTS OF COMMITTEES ', ' AMENDMENTS SUBMITTED AND PROPOSED ', ' INTRODUCTION OF BILLS AND JOINT RESOLUTIONS ', ' ADDITIONAL COSPONSORS ', ' SUBMITTED RESOLUTIONS ', ' SUBMISSION OF CONCURRENT AND SENATE RESOLUTIONS ', ' SENATE RESOLUTION ', ' TEXT OF AMENDMENTS ', ' APPOINTMENT ', ' AUTHORITY FOR COMMITTEES TO MEET ', ' CONFIRMATION ', ' NOMINATION ' ] segmentEnd = ' f ' senators = ['Mr. SESSIONS', 'Mr. STRANGE', 'Mr. JONES', 'Mr. SHELBY', 'Mr. SULLIVAN', 'Ms. MURKOWSKI', 'Mr. FLAKE', 'Mr. MCCAIN', 'Mr. KYL', 'Mr. COTTON', 'Mr. BOOZMAN', 'Mrs. FEINSTEIN', 'Ms. HARRIS', 'Mr. GARDNER', 'Mr. BENNET', 'Mr. MURPHY', 'Mr. BLUMENTHAL', 'Mr. CARPER', 'Mr. COONS', 'Mr. NELSON', 'Mr. RUBIO', 'Mr. PERDUE', 'Mr. ISAKSON', 'Ms. HIRONO', 'Mr. SCHATZ', 'Mr. RISCH', 'Mr. CRAPO', 'Mr. DURBIN', 'Ms. DUCKWORTH', 'Mr. DONNELLY', 'Mr. YOUNG', 'Mrs. ERNST', 'Mr. GRASSLEY', 'Mr. ROBERTS', 'Mr. MORAN', 'Mr. MCCONNELL', 'Mr. PAUL', 'Mr. CASSIDY', 'Mr. KENNEDY', 'Mr. KING', 'Ms. COLLINS', 'Mr. CARDIN', 'Mr. VAN HOLLEN', 'Ms. WARREN', 'Mr. MARKEY', 'Ms. STABENOW', 'Mr. PETERS', 'Ms. KLOBUCHAR', 'Mr. FRANKEN', 'Ms. SMITH', 'Mr. WICKER', 'Mr. COCHRAN', 'Mrs. HYDE-SMITH', 'Mrs. MCCASKILL', 'Mr. BLUNT', 'Mr. TESTER', 'Mr. DAINES', 'Mrs. FISCHER', 'Mr. SASSE', 'Mr. HELLER', 'Ms. CORTEZ MASTO', 'Mrs. SHAHEEN', 'Ms. HASSAN', 'Mr. MENENDEZ', 'Mr. BOOKER', 'Mr. HEINRICH', 'Mr. UDALL', 'Mrs. GILLIBRAND', 'Mr. SCHUMER', 'Mr. TILLIS', 'Mr. BURR', 'Ms. HEITKAMP', 'Mr. HOEVEN', 'Mr. BROWN', 'Mr. PORTMAN', 'Mr. INHOFE', 'Mr. LANKFORD', 'Mr. MERKLEY', 'Mr. WYDEN', 'Mr. CASEY', 'Mr. TOOMEY', 'Mr. WHITEHOUSE', 'Mr. REED', 'Mr. GRAHAM', 'Mr. SCOTT', 'Mr. ROUNDS', 'Mr. THUNE', 'Mr. CORKER', 'Mr. ALEXANDER', 'Mr. CRUZ', 'Mr. CORNYN', 'Mr. HATCH', 'Mr. LEE', 'Mr. SANDERS', 'Mr. LEAHY', 'Mr. KAINE', 'Mr. WARNER', 'Ms. CANTWELL', 'Mrs. MURRAY', 'Mr. MANCHIN', 'Mrs. CAPITO', 'Ms. BALDWIN', 'Mr. JOHNSON', 'Mr. BARRASSO', 'Mr. ENZI', 'The ACTING PRESIDENT', 'The PRESIDING OFFICER', 'The VICE PRESIDENT' 'Executive nominations confirmed by'] startDate = '20170106' endDate = '20170130' conRecords = downloadConRecords(startDate, endDate) cleanConRecords = cleanRecords(conRecords, phraseDelete, segmentStart, segmentEnd) textExport, textDump, speechExport, speakerExport, speakerAnalytics = writeAnalytics(conRecords, senators) exportCSV(textExport,'textExport') exportCSV(textDump,'textDump') exportCSV(speechExport,'speechExport') exportCSV(speakerExport,'speakerExport') exportCSV(speakerAnalytics,'speakerAnalytics') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-06T18:51:56.880", "Id": "411976", "Score": "0", "body": "Anyone have suggestions on better ways to write this?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T03:18:28.977", "Id": "212599", "Score": "4", "Tags": [ "python", "beginner", "statistics", "natural-language-processing", "pdf" ], "Title": "Download and analyze PDFs of Congressional records" }
212599
<p>I was solving this problem at Pramp and I have trouble figuring out the algorithm for this problem. I'll paste the problem description and how I kind of solved it. It's the correct solution. It is similar to the edit distance algorithm and I used the same approach. I just wanted to see what are other ways to solve this problem.</p> <blockquote> <p>The deletion distance of two strings is the minimum number of characters you need to delete in the two strings in order to get the same string. For instance, the deletion distance between "heat" and "hit" is 3:</p> <p>By deleting 'e' and 'a' in "heat", and 'i' in "hit", we get the string "ht" in both cases. We cannot get the same string from both strings by deleting 2 letters or fewer. Given the strings str1 and str2, write an efficient function deletionDistance that returns the deletion distance between them. Explain how your function works, and analyze its time and space complexities.</p> <p>Examples:<br> input: str1 = "dog", str2 = "frog"<br> output: 3<br> input: str1 = "some", str2 = "some"<br> output: 0<br> input: str1 = "some", str2 = "thing"<br> output: 9<br> input: str1 = "", str2 = ""<br> output: 0 </p> </blockquote> <p>What I want to do in this solution, is to use dynamic programming in order to build a function that calculates opt(str1Len, str2Len). Notice the following: I use dynamic programming methods to calculate opt(str1Len, str2Len), i.e. the deletion distance for the two strings, by calculating opt(i,j) for all 0 ≤ i ≤ str1Len, 0 ≤ j ≤ str2Len, and saving previous values </p> <pre><code> def deletion_distance(s1, s2): m = [[0 for j in range(len(s2) +1)] for i in range(len(s1)+1)] for i in range(len(s1)+1): for j in range(len(s2)+1): if i == 0: m[i][j] = j elif j == 0: m[i][j] = i elif s1[i-1] == s2[j-1]: m[i][j] = m[i-1][j-1] else: m[i][j] = 1 + min(m[i-1][j], m[i][j-1]) return m[len(s1)][len(s2)] </code></pre>
[]
[ { "body": "<p>Your code looks alright but if I may offer a different approach that is more \"pythonic\".</p>\n\n<p>One way to address the problem is to think of it as how many chars are in the two words combined minus the repeating chars.\nSay S = len(s1 + s2) and X = repeating_chars(s1, s2) then the result is S - X.</p>\n\n<p>To do so I've used Counter class from python <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\">collections</a>.</p>\n\n<p>the Counter is used to count the appearances of a char in the two strings combined, you can build your own Counter with a simple line but it wont have the same properties as the Class obviously, here is how you write a counter:</p>\n\n<pre><code>def counter(string):\n return {ch: string.count(ch) for ch in set(string)}\n</code></pre>\n\n<hr>\n\n<p>Back to the problem, here is the code for that approach:</p>\n\n<pre><code>from collections import Counter\n\ndef deletion_distance(s1, s2):\n return sum(v % 2 for v in Counter(s1 + s2).values())\n</code></pre>\n\n<p>Hope it helps!</p>\n\n<p>Hod</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-06T22:13:30.247", "Id": "411995", "Score": "1", "body": "First - your function is missing a return. Second - consider `deletion_distance(\"aaa\", \"\")`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T09:20:28.770", "Id": "412045", "Score": "1", "body": "Also, by merely counting letters, you lose all ordering informations. `deletion_distance('ab', 'ba')` should be 2 but if you only count letters, you will never be able to find this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T14:38:50.113", "Id": "415905", "Score": "0", "body": "Mathias is correct; the problem given is total length minus twice the length of the *longest common subsequence*, not the total number of characters in common. The total number of characters in common can be larger." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T10:28:54.827", "Id": "212618", "ParentId": "212607", "Score": "1" } }, { "body": "<blockquote>\n <p>I was solving this problem at Pramp and I have trouble figuring out the algorithm for this problem.</p>\n</blockquote>\n\n<p>On the contrary, you've done a very good job of coming up with a solution. There are ways to improve it though.</p>\n\n<p>As you note, this is just the Longest Common Subsequence problem in a thin disguise. The \"deletion distance\" between two strings is just the total length of the strings minus twice the length of the LCS.</p>\n\n<p>That is, the LCS of <code>dogs</code> (4 characters) and <code>frogs</code> (5 characters) is <code>ogs</code> (3 characters), so the deletion distance is (4 + 5) - 2 * 3 = 3.</p>\n\n<p>Therefore, all you need to do to solve the problem is to get the length of the LCS, so let's solve that problem.</p>\n\n<p>Your solution is pretty good but the primary problem is that it takes O(mn) time and memory if the strings are of length m and n. You can improve this. </p>\n\n<p>The first thing to notice is that <em>if the strings have a common prefix or suffix then you can automatically eliminate it</em>. That is, the deletion distance for <code>Who let the big dogs out?</code> and <code>Who let the little frogs out?</code> is the same as the deletion distance for <code>big d</code> and <code>little fr</code>. <strong>It is very cheap and easy to determine if two strings have a common prefix and suffix</strong>, and you go from having an array with 25*29 elements to an array with 5*9 elements, a huge win.</p>\n\n<p>The next thing to notice is: you build the entire <code>m*n</code> array up front, but while you are filling in the array, <code>m[i][j]</code> only ever looks at <code>m[i-1][j-1]</code> or <code>m[i-1][j]</code> or <code>m[i][j-1]</code>. Since you never look at an array line that is <em>two away</em>, you don't ever need more than two lines! That is, you can:</p>\n\n<ul>\n<li>allocate and compute the first line</li>\n<li>allocate and compute the second line given the first line</li>\n<li>throw away the first line; we'll never use it again</li>\n<li>allocate and compute the third line from the second line</li>\n<li>throw away the second line</li>\n<li>… and so on</li>\n</ul>\n\n<p>You still do O(mn) operations, and you still allocate <em>in total</em> the same amount of memory, but you only have a small amount of it in memory <em>at the same time</em>. If the strings are large, that's a considerable savings.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-09T14:56:48.403", "Id": "215099", "ParentId": "212607", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T06:44:24.490", "Id": "212607", "Score": "7", "Tags": [ "python" ], "Title": "Deletion Distance between 2 strings" }
212607
<p>i attempted to create a way (not sure if already implemented by someone) by which when i update a property of an object. it returns a new reference of the object with the new value. i have a usecase in my mind for that purpose you can say i want to use it. </p> <p>for some example reference you can consider redux reducer where you have to return a new reference everytime store is updated.</p> <p>here is my small code which attempts to do it. </p> <p>kindly ignore the <code>setIn</code> implementation its the first attempt.</p> <pre><code>function NewRef(jsObj) { Object.keys(jsObj).forEach((key) =&gt; { this[key] = jsObj[key]; }); } NewRef.prototype.set = function set(key, value) { let copyValue = null; if (Array.isArray(value)) copyValue = [...value]; else if (typeof value === 'object') copyValue = { ...value }; else copyValue = value; if (this[key] || ['object', 'boolean', 'number'].includes(typeof this[key])) { return Object.assign(Object.create(Object.getPrototypeOf(this)), { ...this, [key]: copyValue, }); } throw new Error(`invalide key ${key} in object`); }; NewRef.prototype.setIn = function set(nested, value) { let copyValue = null; if (Array.isArray(value)) copyValue = [...value]; else if (typeof value === 'object') copyValue = { ...value }; else copyValue = value; if (!Array.isArray(nested)) { throw new Error('setIn requires array of strings as first argument'); } else { if (this[nested[0]] || ['object', 'boolean', 'number'].includes(typeof this[nested[0]])) { if (this[nested[0]][nested[1]] || ['object', 'boolean', 'number'].includes(typeof this[nested[0]][nested[1]])) { return Object.assign(Object.create(Object.getPrototypeOf(this)), { ...this, [nested[0]]: { ...this[nested[0]], [nested[1]]: copyValue, }, }); } } throw new Error(`invalid properties maybe ${nested.join(',')}`); } }; NewRef.prototype.get = function get(key) { return this[key]; }; export default function NObject(jsObj) { const store = new NewRef(jsObj); return store; } </code></pre> <p>with this piece of code i am able to do this. </p> <pre><code>const d1 = NObject({ type: 'bool', data: {key:'value'} meta: { user: 'john doe' } }) const n1 = d1.set('type','mutated').set('data',[1,2]) const n2 = n1.setIn(['meta','user'],'foo bar'); </code></pre> <p>both n1,n2 and d1 have different references. it works and is tested well.</p> <p>please feel free to review it and give your suggestions. i am open to everything</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T07:19:30.457", "Id": "411245", "Score": "0", "body": "`if (typeof value === 'object')` will always be true for Arrays (the typeof an Array is 'object') so your `else if (Array.isArray(value))` will never get hit. I personally find it really confusing to read code that uses if/else if/else if with no indentation at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T10:23:21.527", "Id": "411265", "Score": "0", "body": "great catch. then i will move array validation above.@jfriend00" } ]
[ { "body": "<h1>Mutants are not evil.</h1>\n\n<p>I am not going to give a line by line review as I do not see this code as having any useful value. Rather is see it as dangerous as it gives a air of safety when none is present, thus much worse than the supposed monsters you wish to banash, as now you say there are none to worry about (in fact there are more).</p>\n\n<p>First some basics..</p>\n\n<h1>Mutation</h1>\n\n<p>Object mutation is not a bad thing. In javascript it is a fundamental part of the language and contributes much to what makes it such an enjoyable language to use.</p>\n\n<p>Mutation has turned into a cover all term referring to any change to an object, its structure, or content of its properties. The term is synonymous with bad practice, even assigning a variable is considered mutation and bad these days.</p>\n\n<p>The term \"Mutation\" should be used to only when changes are made in such a way as to result in a state that can not be trusted to work.</p>\n\n<h2>Good and bad mutants</h2>\n\n<p>Consider the following simple object</p>\n\n<pre><code>var myNum = {\n valueOf : 0,\n add(num) { this.valueOf += num.valueOf; return this },\n toString() { return Number(this.valueOf).toFixed(2) } \n};\n\n// created as follows\nvar numA = {...myNum, valueOf: 1};\nvar numB = {...myNum, valueOf: 2};\n\n// use it \nconsole.log(numB.add(numA).valueOf); // &gt;&gt; 3\nelement.textContent = numB; // &gt;&gt; 3.00 \n</code></pre>\n\n<h3>Good mutants</h3>\n\n<p>We can mutate it in a variety of ways that do not effect its operational quality. These mutations must be consciously implemented and as long as all involved are aware of the mutation there is no problem</p>\n\n<pre><code>numA.message = \"Foobar\"; // add a property\nnumA.toString = function() { return Number(this.valueOf).toFixed(4) }; //instance output format\nmyNum.toString = function() { return Number(this.valueOf).toFixed(3) }; //default output format\nmyNum.value = 2; // change its default state\n</code></pre>\n\n<h3>Bad mutants</h3>\n\n<p>However there are mutations that are not deliberate, or there is error in understanding that make the object or template untrustable. </p>\n\n<pre><code>numA = 1; // reassignment\nnumA.add(1); // improper use\nnumA.value = \"2\"; // improper type\nnumA.add = (num) =&gt; { this.valueOf += num; return this }; // ambiguous closure use\nmyNum.toString = function() { return this.valueOf.toFixed(3) }; // missing procedural logic\n</code></pre>\n\n<hr>\n\n<h2>Does your code protect against mutants?</h2>\n\n<pre><code>const numAO = NObject(numA); // original instance remains\nconst numA = NObject({...myNum, value: \"3\"}); // already mutated\n// next assigns a mutant property\nconst numAA = numAO.set(\"toString\",function() { return this.valueOf.toFixed(3) });\n// There are many more\n</code></pre>\n\n<p>So... Does your code protect against mutants? No it does not. </p>\n\n<ul>\n<li>The original reference still remains and can be used. Duplication does not stop mutation</li>\n<li>The internal state is not protected and manipulated without using the wrappers methods.</li>\n<li>Using the wrappers does not stop mutant assignment that can result in untrusted state.</li>\n<li>Each wrapper call creates a new instance, yet does not delete old and likely in use references. </li>\n</ul>\n\n<p>And quite franckly you have added another level of procedure that will have a very negative effect on the source code quality and the coders workload. You will stop using it within a few hundred lines of a project as it is cumbersome. </p>\n\n<ul>\n<li>In terms of readability, massive bloat in source size</li>\n<li>In terms of comprehension as it does not provide a clear semantic understanding via its naming and how it is used.</li>\n<li>Striking at the heart of a coders need to be lazy (AKA succinct, efficient, and elegant) to much overhead and typing.</li>\n</ul>\n\n<h3>Trust is not an option.</h3>\n\n<p>To protect against bad mutation you can not rely on trust (trust that the object is used correctly). One mistake at any point in using your wrapper and the whole house of cards falls.</p>\n\n<p>Protection MUST be enforceable. Protection against mutation means that you simply can not create bad mutations.</p>\n\n<h2>How to protect against mutants</h2>\n\n<p>JavaScript is particularly prone to mutation, it is neither type nor object (class) safe.</p>\n\n<p>Mutation has long been a problem in programming, and there are many ways devized to protect against them. Some good some not so good.</p>\n\n<ol>\n<li>Not so good, Functional programing, relies on trust and is next to useless in my view.</li>\n<li><p>Good, Encapsulation. The best ever as it is enforced by fundamental language constructs.</p>\n\n<p>JavaScript provides a strong encapsulation mechanism that can ensure state safety no matter how much the coder wishes to break the rules.</p>\n\n<ul>\n<li>Closure, encapsulates private properties safe from outside mutation.</li>\n<li>Constants <code>const</code> as declared variables are immutable</li>\n<li>Object methods to help protected properties eg <code>myNum.toString</code> protect against mutation <code>Object.defineProperty(myNum,\"tostring\",{value : function() { return Number(this.valueOf).toFixed(2) }})</code></li>\n<li>Getters and Setters create read and write only properties, and define a method of vetting state changes to prevent bad mutation.</li>\n</ul></li>\n</ol>\n\n<h2>Example</h2>\n\n<p>Taking the <code>myNum</code> example from above and turn it into an immutable object with enforced state safety and trust</p>\n\n<pre><code>const MyNum = (value) =&gt; {\n const error = () =&gt; { throw new ReferenceError(\"value is not a number\") }\n const vet = (v, suppressError = true) =&gt; // vet state\n typeof (v = Number(v)) === \"number\" ? v : (\n suppressError ? \n 0/0 : // creates trusted NaN\n error()\n );\n value = vet(value, false); // vet new internal state\n const add = num =&gt; value += num; // encapsulated method safe from mutation \n // and can run in trust (no vetting)\n return Object.freeze({ // Frozen object ensures no tampering\n set valueOf(num) { value = vet(num) },\n get valueOf() { return value },\n toString() { return value.toFixed(2) },\n add(myNum) { \n add(vet(myNum.valueOf, false))\n return this;\n },\n });\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T12:44:20.883", "Id": "212624", "ParentId": "212608", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T06:45:05.153", "Id": "212608", "Score": "0", "Tags": [ "javascript", "ecmascript-6", "redux" ], "Title": "Returning a new object reference when mutation happens" }
212608
<p>Let's assume I have a class <code>PhoneNumber</code> which accepts phone numbers in the format "123-456-789" (3 groups with 3 digits each, split by dashes). Now, I want to extend the class <code>PhoneNumber</code> with a static <code>Parse</code> and <code>TryParse</code> method. What is the best way to do so while keeping following requirements:</p> <ul> <li>Code reuse between <code>Parse</code> and <code>TryParse</code></li> <li>Well-known API (see <code>DateTime.TryParse</code>)</li> </ul> <p>Following code shows the first attempt of how I would implement such <code>Parse</code>/<code>TryParse</code> methods. <code>TryParseInternal</code> collects a list of exceptions/anomalies for the given codeline input string. Static method <code>Parse</code> throws an exception if anything is wrong with the given codeline while <code>TryParse</code> just returns <code>true</code>/<code>false</code> to indicate parsing success.</p> <pre><code>public class PhoneNumber { public string Part1 { get; } public string Part2 { get; } public string Part3 { get; } public PhoneNumber(string part1, string part2, string part3) { Part1 = part1; Part2 = part2; Part3 = part3; } // Example implementation for TryParse public static bool TryParse(string codeline, out PhoneNumber value) { if (!TryParseInternal(codeline, out value).Any()) { return true; } return false; } // Example implementation for Parse public static PhoneNumber Parse(string codeline) { var exceptions = TryParseInternal(codeline, out var esr); if (!exceptions.Any()) { return esr; } throw new ParseException(exceptions); } private static List&lt;Exception&gt; TryParseInternal(string codeline, out PhoneNumber value) { var exceptions = new List&lt;Exception&gt;(); if (codeline == null) { exceptions.Add(new ArgumentNullException(nameof(codeline))); } else if (codeline == "") { exceptions.Add(new ArgumentException(nameof(codeline))); } var match = Regex.Match(codeline, @"^(\d{3})-(\d{3})-(\d{3})$"); if (match.Success == false) { exceptions.Add(new ArgumentException("Format is invalid", nameof(codeline))); } if (exceptions.Any()) { value = null; } else { value = new PhoneNumber(match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value); } return exceptions; } public class ParseException : AggregateException { public ParseException(string message) : base(message) { } public ParseException(IEnumerable&lt;Exception&gt; exceptions) : base(exceptions) { } } } </code></pre> <p>Following XUnit tests demonstrate failing/succeeding <code>Parse</code> and <code>TryParse</code> scenarios:</p> <pre><code>public class PhoneNumberTests { [Fact] public void ParseTest_Success() { // Arrange var codeline = "123-456-789"; // Act var esr = PhoneNumber.Parse(codeline); // Assert esr.Part1.Should().Be("123"); esr.Part2.Should().Be("456"); esr.Part3.Should().Be("789"); } [Fact] public void ParseTest_InvalidFormat() { // Arrange var codeline = "X-X-X"; // Act Action action = () =&gt; PhoneNumber.Parse(codeline); // Assert action.Should().Throw&lt;PhoneNumber.ParseException&gt;().Which.InnerExceptions[0].Message.Should().Contain("Format is invalid"); } [Fact] public void TryParseTest_Success() { // Arrange var codeline = "123-456-789"; // Act var success = PhoneNumber.TryParse(codeline, out var esr); // Assert success.Should().BeTrue(); esr.Part1.Should().Be("123"); esr.Part2.Should().Be("456"); esr.Part3.Should().Be("789"); } [Fact] public void TryParseTest_InvalidFormat() { // Arrange var codeline = "X-X-X"; // Act var success = PhoneNumber.TryParse(codeline, out var esr); // Assert success.Should().BeFalse(); esr.Should().BeNull(); } } </code></pre> <p>Is there anything in the given approach you would do differently? Do you see any potential problems? What about performance? Would it be better to collect strings instead of exceptions in terms of memory overhead?</p> <p>Any recommendation/hint is welcome.</p> <p><strong>Update 2019-02-01:</strong> Thanks for the discussion so far. The focus should not lay on the phone number and the 3x3 digits I chose. This format does not even exist in my home country. It's just about <strong>how you would implement <code>Parse</code> and <code>TryParse</code> as static methods</strong> of a class.</p> <p><strong>Update 2019-02-08:</strong> I found a proper solution for this, but I guess it's not relevant anymore as some people here are more concerned about collecting rewards than finding solutions. Thanks for those who contributed.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T13:17:25.717", "Id": "411288", "Score": "5", "body": "Be careful with `\\d` in your regex. `\"๑๒๓-๔๕๖-๗๘๙\"` will be accepted as a valid phone number. Doesn't have to be a problem, but depending on what is done next with the data, it might just be ... `[0-9]` is probably closer to what you intended." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T15:09:53.697", "Id": "411300", "Score": "4", "body": "Phone numbers aren't amenable to parsing. Your entire premise is wrong. See https://github.com/googlei18n/libphonenumber/blob/master/FALSEHOODS.md" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T16:20:35.877", "Id": "411312", "Score": "1", "body": "Came here to share libphonenumber too. Parsing phone number is hard. Please avoid doing it for any serious work. Whenever you can, use libphonenumber. [official C# port](https://github.com/twcclegg/libphonenumber-csharp)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T23:53:40.723", "Id": "411364", "Score": "0", "body": "@RogerLipscombe, phone numbers *in general* may not be amenable to parsing, but in a restricted case, they parse just fine. For example, a United States phone number written in standard format can be parsed successfully with a one-line regex." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T09:00:44.487", "Id": "411380", "Score": "2", "body": "I vote to close this question as off-topic because OP posted code that has no purpose and thus lacks context, consequently isn't interested in a review but a discussion about the design of the two methods. OP should have asked it on [Software Engineering](https://softwareengineering.stackexchange.com/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T07:36:24.183", "Id": "412182", "Score": "2", "body": "_found a proper solution for this, but I guess it's not relevant anymore as some people here are more concerned about collecting rewards than finding solutions._ - this is not true - each community has its special rules and this one requires real and working code which you have not provided so consequently it got closed because reviewing and improving code that virtually does not exist is pointless. Would you have asked this question on Software Engineering where it perfectly fits their rules the outcome would have been quite different." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T08:32:33.320", "Id": "412195", "Score": "0", "body": "@t3chb0t does it make sense to migrate this post there?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T08:37:06.100", "Id": "412196", "Score": "1", "body": "@SᴀᴍOnᴇᴌᴀ this is a tough one because while the question would now be on-topic there the answers wouldn't... the information provided by OP later makes it a nasty mix of various yes/no arguments. I think it would be best to leave it as is and ask a new question there." } ]
[ { "body": "<blockquote>\n<pre><code> public PhoneNumber(string part1, string part2, string part3)\n {\n Part1 = part1;\n Part2 = part2;\n Part3 = part3;\n }\n</code></pre>\n</blockquote>\n\n<p>I'm confused. The existence of <code>TryParse</code> tells me that there are important validity constraints on the number, but there's a public constructor which doesn't validate its arguments. It seems that I could easily make an instance of <code>PhoneNumber</code> for which <code>Parse(phoneNumber.ToString())</code> doesn't round-trip.</p>\n\n<p>In fact, I'm even more confused: <code>PhoneNumber</code> doesn't override <code>ToString()</code> or any of the identity methods (<code>GetHashcode</code>, <code>Equals</code>, <code>operator==</code>, etc). Why not?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public static bool TryParse(string codeline, out PhoneNumber value)\n {\n if (!TryParseInternal(codeline, out value).Any())\n {\n return true;\n }\n\n return false;\n }\n</code></pre>\n</blockquote>\n\n<p>IMO this is a failure to properly use the Boolean type. I would prefer</p>\n\n<pre><code> public static bool TryParse(string codeline, out PhoneNumber value)\n {\n return !TryParseInternal(codeline, out value).Any();\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> private static List&lt;Exception&gt; TryParseInternal(string codeline, out PhoneNumber value)\n {\n var exceptions = new List&lt;Exception&gt;();\n if (codeline == null)\n {\n exceptions.Add(new ArgumentNullException(nameof(codeline)));\n }\n\n else if (codeline == \"\")\n {\n exceptions.Add(new ArgumentException(nameof(codeline)));\n }\n\n var match = Regex.Match(codeline, @\"^(\\d{3})-(\\d{3})-(\\d{3})$\");\n</code></pre>\n</blockquote>\n\n<p>This aggregation strategy lets you down (and so does your test suite) when I pass <code>null</code> for <code>codeline</code>. Instead of the <code>ArgumentNullException</code> or <code>ParseException</code> which I would expect, I get a <code>NullReferenceException</code> from <code>Regex.Match</code>.</p>\n\n<hr>\n\n<p>Another issue I see with the aggregation strategy is that the code repeats itself a bit: <code>TryParseInternal</code> checks <code>exceptions.Any()</code> to decide how to handle the <code>out</code> parameter, and then its caller checks <code>esr.Any()</code> to decide how to handle the <code>out</code> parameter. If you are attached to the aggregation (I personally don't see the point) then this might be simpler if the inner method returned <code>ParseException</code> instead of <code>List&lt;Exception&gt;</code>.</p>\n\n<hr>\n\n<p>Which prompts me to say: code to the interface, not the implementation. If a method can return <code>IList&lt;T&gt;</code> then that's preferable to returning <code>List&lt;T&gt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T11:41:17.533", "Id": "411279", "Score": "0", "body": "Mhmm... the last statement is questionable as arrays are also of type `IList<T>`. I'd say it's better to use the interface as it gives you more options especially during testing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T11:57:48.233", "Id": "411282", "Score": "0", "body": "@t3chb0t, I don't understand. What's the problem with using a type which arrays implement? And why do you say that the statement is questionable and then agree with it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T12:00:38.827", "Id": "411283", "Score": "1", "body": "Oh, crappy-crap, I misread the _then that's preferable to returning_ as _then it's preferable to return_ --- sorry!!! ;-]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T15:47:24.820", "Id": "411303", "Score": "0", "body": "@Peter Array is probably the worst example to use here. Array should never have implemented `IList` in the first place, since it can't correctly implement the interface (Add doesn't make sense for a fixed-size array). Certainly a mistake on Microsoft's part, but I'd strongly advise against returning arrays when the static type says `IList`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T15:51:02.513", "Id": "411305", "Score": "0", "body": "@Voo, if you're arguing that `IList<T>` should never be used then please be direct. If you aren't arguing that, then this is completely off topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T16:02:23.723", "Id": "411306", "Score": "2", "body": "@Peter I'm arguing that your claim \"code to the interface, not the implementation\" is wrong for some very prominent classes of the standard library due to errors in their implementation. It's a good idea in principle but shouldn't be stated too generally without mentioning the caveats. Seemed fitting considering that t3chb0t already brought it up unintentionally." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T16:15:42.997", "Id": "411309", "Score": "1", "body": "@Voo since `IList<T>` implements the `ICollection<T>` interface and this one provides the `IsReadOnly` property it's perfectly suited for arrays too thus a list does not necessarily has to support `Add`, it's then a read-only-list/collection." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T21:30:06.520", "Id": "411461", "Score": "0", "body": "@t3chb0t Wasn't aware that property existed, interesting. But yes that technically would make it compliant. I don't think I've ever actually *seen* any code make such a check in practice though - still bad API design imo, but at least LSP compliant." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T10:03:40.657", "Id": "212615", "ParentId": "212614", "Score": "11" } }, { "body": "<h3>Class design</h3>\n<p>Apart from the parsing logic I find the <code>PhoneNumber</code> class should not have its three <code>PartX</code> properties but a single property <code>Value</code> that stores all digits.</p>\n<p>How many parts a phone number has it's purely a visual representation and should be implemented either by the UI or alternatively by <code>ToString(format)</code>.</p>\n<h3>Parsing</h3>\n<p>I wouldn't say that restricting phone numbers to exact three equally long parts is a good idea as there is no standard format for them. I sugesst to just match the digits and other allowed separators and capture only digts:</p>\n<pre><code>var digits =\n Regex\n .Matches(&quot;123-456-789&quot;, @&quot;(?:(\\d)|[-])&quot;)\n .Cast&lt;Match&gt;()\n .Where(m =&gt; m.Groups[1].Success)\n .Select(m =&gt; m.Value);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T19:18:59.160", "Id": "411335", "Score": "1", "body": "Worse case if he keeps 3 parts, they should be named properly such as AreaCode, Prefix, and LineNumber." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T07:07:56.967", "Id": "412181", "Score": "0", "body": "Agree. The question however was how Parse/TryParse can be implemented in a proper and safe way. The phone number example is just fictive." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T16:37:52.617", "Id": "212637", "ParentId": "212614", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T09:43:20.347", "Id": "212614", "Score": "9", "Tags": [ "c#", "parsing" ], "Title": "Parse and TryParse methods for phone numbers" }
212614
<p>I'm not much familiar with Task Api programming in C#. Can anyone review my following code?</p> <p>The following is a <code>ElapsedEventHandler</code> of a <code>System.Timers.Timer</code>. In this event, I'm getting pending notifications from database and sending them. After I send the notification, I update that notification in database by setting <code>HasSent = true</code>. We require our notifications to be sent as soon as possible. This is the reason, I'm updating <code>HAsSent</code> in a separate thread by using Task Api. I would like to know if this is a bad practise? Should I use this? If not then why?</p> <pre><code>protected void ProcessNotifications(object source, ElapsedEventArgs e) { UtilityMethods.StopTimer(_notificationTimer); try { var notificationService = new NotificationService(); var pendingNotifications = notificationService.GetPendingNotifications(); if (pendingNotifications.Count &gt; 0 &amp;&amp; LoadConfigurations()) { foreach (var notification in pendingNotifications) { try { var notificationType = (NotificationType)notification.NotificationTypeId; notification.NotificationTemplate = new NotificationTemplateService().GetById(notification.NotificationTemplateId); notification.NotificationAttachments = notificationType == NotificationType.Email ? new NotificationAttachmentService().GetByNotificationId(notification.NotificationId) : null; using (var sender = NotificationSenderFactory.Create(notificationType)) { if (sender.Send(notification)) { Task.Factory.StartNew(() =&gt; { notificationService.MarkNotificationsAsSent(notification.NotificationId);// A database Hit }); } } } catch (Exception ex) { AppLogger.LogException(ex); } } } } catch (Exception ex) { AppLogger.LogException(ex); } finally { UtilityMethods.StartTimer(_notificationTimer); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T11:57:27.260", "Id": "411281", "Score": "1", "body": "Can you please post the rest of the code?" } ]
[ { "body": "<blockquote>\n<p>Should I use this?</p>\n</blockquote>\n<p><strong>NO</strong></p>\n<blockquote>\n<p>If not then why?</p>\n</blockquote>\n<p>Reference <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskfactory.startnew?view=netframework-4.7.2\" rel=\"nofollow noreferrer\">TaskFactory.StartNew Method</a></p>\n<blockquote>\n<h2><a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskfactory.startnew?view=netframework-4.7.2#remarks\" rel=\"nofollow noreferrer\">Remarks</a></h2>\n<p>Starting with the .NET Framework 4.5, the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.run?view=netframework-4.7.2\" rel=\"nofollow noreferrer\"><code>Task.Run</code></a> method is the recommended way to launch a compute-bound task. Use the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskfactory.startnew?view=netframework-4.7.2\" rel=\"nofollow noreferrer\"><code>StartNew</code></a> method only when you require fine-grained control for a long-running, compute-bound task. <strong>.......</strong></p>\n</blockquote>\n<p>Which would end up as</p>\n<pre><code>//...omitted for brevity\n\nTask.Run(() =&gt; {\n notificationService.MarkNotificationsAsSent(notification.NotificationId);// A database Hit\n});\n\n//...omitted for brevity\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-04T07:39:38.807", "Id": "411626", "Score": "0", "body": "Is it good to run a task in loop? Or I should hit the database without task? Would it really a good way to achieve performance or it can degrade performance?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T01:41:13.687", "Id": "212729", "ParentId": "212620", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T11:44:00.677", "Id": "212620", "Score": "1", "Tags": [ "c#", "multithreading", "task-parallel-library" ], "Title": "Receiving and sending notifications from database" }
212620
<p>Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. </p> <p><strong>How can i improve the below solution?</strong></p> <pre><code> package com.alpha; import java.util.HashMap; import java.util.Map; public class DailyCodingProblem1 { public static void main(String args[]) { int[] arr = { 10, 15, 3, 7 }; int k = 17; Boolean ans = solution(arr, k); System.out.println(ans); } private static Boolean solution(int[] arr, int k) { final Map&lt;Integer, Boolean&gt; map = new HashMap&lt;&gt;(); for (int x : arr) { map.put(k - x, true); } for (int x : arr) { if (Boolean.TRUE.equals(map.get(Integer.valueOf(x)))) { return true; } } return false; } } </code></pre>
[]
[ { "body": "<p>Your solution doesn't take into consideration and array that k equals x*2,\nfor example if arr = {10, 17, 3} and k == 20, k - x = 10 and 10 -> true will be placed in map. In the second iteration the value 10 will get you the value true, so you must make sure that you don't iterate over two integers twice.</p>\n\n<p>One way to improve the algorithm is to put the integers in the map but also check if the integer is already in map, if we return to my example while k-v == 3 when v == 17 and k-v == 17 when v == 3, \nso if you check if the integer is already in the map it could be more efficient and avoid iterating over the array again.</p>\n\n<p>If we go back to your code:</p>\n\n<pre><code> private static Boolean solution(int[] arr, int k) {\n final Map&lt;Integer, Boolean&gt; map = new HashMap&lt;&gt;();\n for (int x : arr) {\n map.put(k - x, true);\n if (Boolean.TRUE.equals(map.get(Integer.valueOf(x)))) \n return true;\n\n }\n return false;}\n</code></pre>\n\n<hr>\n\n<p>Let me know if you need any other clarifications,</p>\n\n<p>Hod</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T22:53:33.373", "Id": "411359", "Score": "0", "body": "And you've duplicated the mistake you caught. With `arr={10}, k=20`, you `map.put(20-10,true)`, then pull out `map.get(10)`, and find that two values from a list of only a single 10 can sum to 20. You need to test for `x` before adding `k-x`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T13:53:21.653", "Id": "212626", "ParentId": "212621", "Score": "0" } }, { "body": "<h2>Boolean -vs- boolean</h2>\n\n<p>Java provides both a <code>Boolean</code> and a <code>boolean</code> type; the difference being the first type is an <code>Object</code> where as the second is just a value. Wherever possible, you should use a value type, for efficiency. Since you return a simple <code>true</code> or <code>false</code> result, <code>boolean</code> is the correct return type to use:</p>\n\n<pre><code>...\n boolean ans = solution(arr, k);\n...\nprivate static boolean solution(int[] arr, int k) {\n...\n</code></pre>\n\n<h2>Autoboxing</h2>\n\n<p>The java Collections need <code>Object</code>s as keys and values. The Java language will automatically \"box\" and \"unbox\" values as required. You take advantage of autoboxing in <code>map.put(k-v,true)</code> ... The value <code>k-v</code> is autoboxed as an <code>Integer</code> and <code>true</code> is autoboxed as <code>Boolean.TRUE</code>.</p>\n\n<p>Yet, when you retrieve the value from <code>map</code>, you explicitly do the autoboxing yourself: <code>map.get(Integer.valueOf(x))</code>. You could simply write <code>map.get(x)</code>.</p>\n\n<h2>Map -vs- Set</h2>\n\n<p>When you have a <code>Map&lt;K,V&gt;</code>, it is expected that different values will be stored in the map (under one or more keys).</p>\n\n<p>In this case, you are only ever storing <code>Boolean.TRUE</code> (autoboxed from <code>true</code>). Your <code>map.get()</code> either returns <code>Boolean.TRUE</code>, or it returns <code>null</code> if no value was stored under that key. You explicitly test if it is equal to the former value, but you could have tested the value was not <code>null</code> instead. Or more directly, you could test whether a value was stored under that key, and replace the complicated statement with simply:</p>\n\n<pre><code>if (map.containsKey(x)) { ... }\n</code></pre>\n\n<p>At this point, it should be clear we don't need a <code>HashMap</code>. Simply a <code>Set</code> of <code>Integer</code> values.</p>\n\n<pre><code>final Set&lt;Integer&gt; set = new HashSet&lt;&gt;();\n...\n set.add(k-x);\n...\n if (set.contains(x)) {\n...\n</code></pre>\n\n<h2>Algorithm</h2>\n\n<p>As mentioned by hodisr, you need to take into account that the list of numbers may contain only one copy of the value <code>x</code> which is exactly half of the target value (<code>k/2</code>). With your code, you add <code>k-x</code> to your container, and later successfully pull out the flag corresponding to <code>x</code>, and declare <code>true</code>.</p>\n\n<p>Then, hodisr proceeds to demonstrate how to do it in one pass, and goes ahead and <em>repeats the same error</em>, by adding <code>k-x</code> to the container before testing whether <code>x</code> can be pulled out. To obtain the correct result, the check for <code>x</code> must be made before putting <code>k-x</code> into the container.</p>\n\n<pre><code>private static Boolean solution(int[] arr, int k) {\n Set&lt;Integer&gt; set = new HashSet&lt;&gt;();\n\n for (int x : arr) {\n if (set.contains(x))\n return true;\n set.add(k-x);\n }\n return false;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T22:50:18.507", "Id": "212660", "ParentId": "212621", "Score": "2" } } ]
{ "AcceptedAnswerId": "212660", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T11:56:16.780", "Id": "212621", "Score": "0", "Tags": [ "java", "algorithm" ], "Title": "Given a list of numbers and a number k, return whether any two numbers from the list add up to k" }
212621
<p>I registered a <code>CustomMapAnnotationView</code> and a <code>ClusterView</code>: the first one simply extends <code>MKMarkerAnnotationView</code> and overrides <code>annotation</code> this way:</p> <pre><code>override var annotation: MKAnnotation? { willSet { // CustomMapAnnotation is based on MKPointAnnotation if let c = value as? CustomMapAnnotation { clusteringIdentifier = "c" markerTintColor = UIColor.orange displayPriority = .defaultLow } } } </code></pre> <p><code>ClusterView</code> is a <code>MKAnnotationView</code> that is used when annotations can be grouped.</p> <pre><code> mapView.register(CustomMapAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier) mapView.register(ClusterView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier) </code></pre> <p>Now the code review part.</p> <p>I use <code>CustomMapAnnotationView</code> and <code>ClusterView</code> this way:</p> <pre><code>func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -&gt; MKAnnotationView? { guard !(annotation is MKUserLocation) else { return nil } if(annotation is CustomMapAnnotation){ let annotationID = "c" var annotationView: CustomMapAnnotationView? if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationID) as? CustomMapAnnotationView { annotationView = dequeuedAnnotationView annotationView!.annotation = annotation } else { annotationView = CustomMapAnnotationView(annotation: annotation, reuseIdentifier: annotationID) annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) } if let annotationView = annotationView { annotationView.canShowCallout = true } return annotationView }else{ let clusterID = "Cluster" var clusterView = mapView.dequeueReusableAnnotationView(withIdentifier: clusterID) if clusterView == nil { clusterView = ClusterView(annotation: annotation, reuseIdentifier: clusterID) } else { clusterView?.annotation = annotation } return clusterView } } </code></pre> <p>This code perfectly works or at least it does what I wanted it to do. But I'm not sure this is correct way to perform this action inside the body of this function. Any suggestion is appreciated.</p>
[]
[ { "body": "<p>A couple of observations:</p>\n\n<ol>\n<li><p>You have code that says:</p>\n\n<pre><code>var annotationView: CustomMapAnnotationView?\n\nif let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationID) as? CustomMapAnnotationView {\n annotationView = dequeuedAnnotationView\n annotationView!.annotation = annotation\n}\nelse\n{\n annotationView = CustomMapAnnotationView(annotation: annotation, reuseIdentifier: annotationID)\n ...\n}\n</code></pre>\n\n<p>In iOS 11 and later, the <a href=\"https://developer.apple.com/documentation/mapkit/mkmapview/2887123-dequeuereusableannotationview\" rel=\"nofollow noreferrer\"><code>mapView.dequeueReusableAnnotationView(withIdentifier:for:)</code></a> can reduce that to a single line:</p>\n\n<pre><code>let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationID, for: annotation)\n</code></pre></li>\n<li><p>Your <code>mapView(_:viewFor:)</code> is configuring the annotation views. I’d move that configuration code into the <code>MKAnnotationView</code> implementations for better separation of responsibilities and eliminating cruft from your view controller. For example:</p>\n\n<pre><code>class CustomMapAnnotationView: MKMarkerAnnotationView {\n static let clusteringIdentifier = Bundle.main.bundleIdentifier! + \".c\"\n\n override init(annotation: MKAnnotation?, reuseIdentifier: String?) {\n super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)\n\n clusteringIdentifier = CustomMapAnnotationView.clusteringIdentifier\n markerTintColor = .orange\n displayPriority = .defaultLow\n collisionMode = .circle\n rightCalloutAccessoryView = UIButton(type: .detailDisclosure)\n }\n\n required init?(coder aDecoder: NSCoder) {\n fatalError(\"init(coder:) has not been implemented\")\n }\n\n override var annotation: MKAnnotation? {\n willSet {\n clusteringIdentifier = CustomMapAnnotationView.clusteringIdentifier\n }\n }\n}\n</code></pre>\n\n<p>And</p>\n\n<pre><code>class ClusterView: MKMarkerAnnotationView {\n override init(annotation: MKAnnotation?, reuseIdentifier: String?) {\n super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)\n displayPriority = .required\n collisionMode = .circle\n markerTintColor = .purple\n }\n\n required init?(coder aDecoder: NSCoder) {\n fatalError(\"init(coder:) has not been implemented\")\n }\n}\n</code></pre>\n\n<p>This cleans up your <code>mapView(_:viewFor:)</code> and keeps the annotation view configuration code where it belongs.</p></li>\n<li><p>Consider your registration of these classes:</p>\n\n<pre><code>mapView.register(CustomMapAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)\nmapView.register(ClusterView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier)\n</code></pre>\n\n<p>Note, you’re registering these identifiers, so your <code>mapView(_:viewFor:)</code> shouldn’t then use its own reuse identifiers of <code>c</code> and <code>Cluster</code>, respectively.</p></li>\n<li><p>But the whole point of <code>MKMapViewDefaultAnnotationViewReuseIdentifier</code>, etc., in iOS 11 and later is so that you don’t have to implement <code>mapView(_:viewFor:)</code> at all. So you can comment out that whole routine (now that you’ve moved the annotation view configuration code to the annotation views, themselves, where it belongs).</p>\n\n<p>That having been said, sometimes you need a <code>mapView(_:viewFor:)</code>. For example, maybe you need to support iOS versions prior to 11. Or perhaps you have more than three types of annotation types (your main custom annotation, your cluster annotation, and <code>MKUserLocation</code>). But then you wouldn’t register <code>MKMapViewDefaultAnnotationViewReuseIdentifier</code> as the reuse identifier. You’d register your own reuse identifier.</p>\n\n<p>If you do use your own reused identifier, I would have a <code>static</code> property in my annotation view with the preferred reuse identifier, rather than sprinkling hardcoded strings throughout my codebase. E.g.</p>\n\n<pre><code>class CustomMapAnnotationView: MKMarkerAnnotationView {\n static let preferredReuseIdentifier = Bundle.main.bundleIdentifier! + \".customMapAnnotationView”\n\n ...\n}\n</code></pre>\n\n<p>And </p>\n\n<pre><code>mapView.register(CustomMapAnnotationView.self, forAnnotationViewWithReuseIdentifier: CustomMapAnnotationView.preferredReuseIdentifier)\n</code></pre>\n\n<p>And</p>\n\n<pre><code>extension ViewController: MKMapViewDelegate {\n func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -&gt; MKAnnotationView? {\n switch annotation {\n case let annotation as CustomMapAnnotation:\n return mapView.dequeueReusableAnnotationView(withIdentifier: CustomMapAnnotationView.preferredReuseIdentifier, for: annotation)\n\n ...\n }\n }\n}\n</code></pre>\n\n<p>But that’s not needed in your case. You can remove <code>mapView(_:viewFor:)</code> entirely.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-01T18:43:45.593", "Id": "214565", "ParentId": "212628", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T14:37:44.513", "Id": "212628", "Score": "3", "Tags": [ "swift" ], "Title": "Custom map annotations and clusters" }
212628
<blockquote> <p>What am I doing?</p> </blockquote> <p>UDP/TCP server in Python (2.7 / 3.7)</p> <blockquote> <p>How am I doing?</p> </blockquote> <p>Using threads</p> <blockquote> <p>Where am I going to execute it?</p> </blockquote> <p>In a virtual machine running linux in AWS or Google Cloud or Azure ()</p> <blockquote> <p>What is going to received?</p> </blockquote> <p>Streaming data simultaneously from many devices (we could say a few thousand devices) </p> <blockquote> <p>What contains the incoming data?</p> </blockquote> <p>A JSON or CSV line of text (no more than 50 fields / 3000 characters)</p> <blockquote> <p>What this server need?</p> </blockquote> <p>Low latency to process all the incoming data in the minimum possible time</p> <blockquote> <p>What am I going to do with the data?</p> </blockquote> <p>Send one by one (just receive it) to a streaming module in cloud to analyze it </p> <blockquote> <p>Will I need to communicate to the device? </p> </blockquote> <p>Yes. Is not implemented now, but for the future, each time a device send a message to the server, the server will check some parameters of the device </p> <hr> <p>I have read many articles and question about threads vs multiprocessing in python. It looks like multiprocessing is "better" in performance than threads, but I'm not sure if for this use of case with high IO, threads would be more appropriate</p> <hr> <p>The code (actually for Azure)</p> <pre><code>import json import threading import SocketServer from azure.eventhub import EventHubClient, EventData ADDRESS = "" USER = "" KEY = "" class ThreadedUDPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request[0].strip() current_thread = threading.current_thread() print("Thread: {} client: {}, wrote: {}".format(current_thread.name, self.client_address, data)) Split = threading.Thread(target=ParseIncomingData,args=(data,)) Split.start() class ThreadedUDPServer(SocketServer.ThreadingMixIn, SocketServer.UDPServer): pass def SendToEventHub(data): if not ADDRESS: raise ValueError("No EventHubs URL supplied.") client = EventHubClient(ADDRESS, debug=False, username=USER, password=KEY) sender = client.add_sender(partition="0") client.run() try: print("Thread: {}, Sending message: {}".format(threading.current_thread().name,data)) sender.send(EventData(data)) except: raise finally: client.stop() def ParseIncomingData(message): sender = threading.Thread(target=SendToEventHub, args=(json.dumps(message),)) sender.start() if __name__ == "__main__": HOST, PORT = "0.0.0.0", 6071 try: serverUDP = ThreadedUDPServer((HOST, PORT), ThreadedUDPRequestHandler) server_thread_UDP = threading.Thread(target=serverUDP.serve_forever) server_thread_UDP.daemon = True server_thread_UDP.start() serverUDP.serve_forever() except (KeyboardInterrupt, SystemExit): serverUDP.shutdown() serverUDP.server_close() exit() </code></pre> <hr> <p>With high input messages, this is an example of the output</p> <p><a href="https://i.stack.imgur.com/ubbZB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ubbZB.jpg" alt="enter image description here"></a></p> <hr> <blockquote> <p>Testing with asyncio</p> </blockquote> <p><strong>Test 1</strong></p> <p>I have never worked with asyncio so I am sure the code is not good, but I would like to know which would be the way to use it</p> <pre><code>def MDIParseIncomingDataAzure(message): print("Thread: {}, MDIParseIncomingDataAzure".format(current_thread().name)) SendToEventHub(payload) def SendToEventHub(data): print("Thread: {}, SendToEventHub".format(current_thread().name)) class EchoServerProtocol: def connection_made(self, transport): self.transport = transport def datagram_received(self, data, addr): print('Thread: {}. datagram_received '.format(current_thread().name)) MDIParseIncomingDataAzure(data) async def main(): print("Starting UDP server") loop = asyncio.get_running_loop() transport, protocol = await loop.create_datagram_endpoint( lambda: EchoServerProtocol(), local_addr=('0.0.0.0', 6071)) try: await asyncio.sleep(3600) # Serve for 1 hour. finally: transport.close() asyncio.run(main()) </code></pre> <p>The output of this code (which run slow step by step)</p> <p><a href="https://i.stack.imgur.com/sZ8l4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sZ8l4.jpg" alt="test1"></a></p> <hr> <p><strong>Test 2</strong></p> <pre><code>def MDIParseIncomingDataAzure(message,loop): asyncio.set_event_loop(loop) print("Thread: {}, MDIParseIncomingDataAzure".format(current_thread().name)) new_loop = asyncio.new_event_loop() t = Thread(target=SendToEventHub, args=(payload, new_loop,)) t.start() loop.run_forever() def SendToEventHub(data,loop): asyncio.set_event_loop(loop) print("Thread: {}, SendToEventHub".format(current_thread().name)) class EchoServerProtocol: def connection_made(self, transport): self.transport = transport def datagram_received(self, data, addr): print('Thread: {}. datagram_received '.format(current_thread().name)) new_loop = asyncio.new_event_loop() t = Thread(target=MDIParseIncomingDataAzure, args=(data,new_loop,)) t.start() async def main(): print("Starting UDP server") loop = asyncio.get_running_loop() transport, protocol = await loop.create_datagram_endpoint( lambda: EchoServerProtocol(), local_addr=('0.0.0.0', 6071)) try: await asyncio.sleep(3600) # Serve for 1 hour. finally: transport.close() asyncio.run(main()) </code></pre> <p>The output:</p> <p><a href="https://i.stack.imgur.com/xY22j.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xY22j.jpg" alt="test2"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T10:20:02.580", "Id": "411386", "Score": "0", "body": "asyncio + threading? https://hackernoon.com/threaded-asynchronous-magic-and-how-to-wield-it-bba9ed602c32" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-04T07:41:18.533", "Id": "411627", "Score": "0", "body": "something like [this](https://docs.python.org/3/library/asyncio-protocol.html#udp-echo-server)?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T14:52:50.953", "Id": "212630", "Score": "4", "Tags": [ "python", "server", "udp", "azure" ], "Title": "Python UDP server to relay CSV or JSON data to cloud for analysis" }
212630
<p>Coming from Python, JavaScript and PHP, I'd like to learn to write Ruby in the way it's "supposed to". Well-written Python code is called "Pythonic", so I'd like to know how idiomatic my Ruby code is.</p> <p>I've had great help from Rubocop, slapping my face if I didn't write properly, but I still feel some things can be done better.</p> <h1>Application</h1> <p>This set of scripts downloads a github/gitlab/bitbucket repository, removes the .git folder and moves it to the specified folder, so that the files are "de-git".</p> <p>Some commands:</p> <pre class="lang-sh prettyprint-override"><code># Run tests (for regexes) ./degit.rb --test # Extract repo to folder with repo name ./degit.rb zpqrtbnk/test-repo # Extract tag/branch of repo to folder with repo name ./degit.rb zpqrtbnk/test-repo#temp # Extract repo to specified folder ./degit.rb zpqrtbnk/test-repo some-folder </code></pre> <h1>Code</h1> <p>Ruby v2.4.5<br> Idea came from <a href="https://github.com/Rich-Harris/degit" rel="nofollow noreferrer">degit by Rich Harris</a></p> <h2>degit.rb</h2> <pre class="lang-rb prettyprint-override"><code>#!/usr/bin/env ruby require "tmpdir" require_relative "repo" require_relative "repo_type" REPO_TYPES = { github: RepoType.new("github", "https://github.com", "github.com"), gitlab: RepoType.new("gitlab", "https://gitlab.com", "gitlab.com"), bitbucket: RepoType.new("bitbucket", "https://bitbucket.org", "bitbucket.org"), custom: RepoType.new("custom", :custom, :custom), }.freeze # TODO: Error handling def main repo_name = ARGV[0] folder_name = ARGV[1] raise "Required parameter repo name not specified" if repo_name.nil? if repo_name == "--test" require_relative "tests" run_tests return end degit repo_name, folder_name end def temp_dir dir = Dir.mktmpdir("degit-", "/tmp") at_exit { FileUtils.remove_entry(dir) } dir end def degit(repo_name, folder_name) repo = Repo.new repo_name folder_name ||= repo.name dest_dir = File.join Dir.pwd, folder_name dir_exists = Dir.exist? dest_dir if dir_exists abort "Aborted" unless confirm_overwrite dest_dir end dir = temp_dir tmp_repo_path = File.join(dir, folder_name) cmd = repo.download_command tmp_repo_path puts `#{cmd}` FileUtils.remove_entry File.join(tmp_repo_path, ".git") FileUtils.remove_entry dest_dir if dir_exists FileUtils.mv(tmp_repo_path, Dir.pwd, force: true) end def confirm_overwrite(dest_dir) print "Destination folder #{dest_dir} already exists. Overwrite folder? [y/n] " # ARGV interferes with gets, so use STDIN.gets input = STDIN.gets.chomp.downcase return (input == "y") if %w[y n].include? input # Continue to ask until input is either y or n confirm_overwrite dest_dir end main if $PROGRAM_NAME == __FILE__ </code></pre> <h2>repo_type.rb</h2> <pre class="lang-rb prettyprint-override"><code>class RepoType attr_reader :name, :full_url def initialize(name, full_url, base_url, short_code=nil) @name = name @full_url = full_url @base_url = base_url @short_code = short_code || name.to_s.downcase end def id?(id) [@short_code, @base_url].include? id end end </code></pre> <h2>repo.rb</h2> <pre class="lang-rb prettyprint-override"><code>class Repo attr_reader :type, :tag, :name PREFIX_REGEX = %r{ \A ((?&lt;type&gt;github|gitlab|bitbucket):)? (?&lt;owner&gt;[\w-]+)/(?&lt;name&gt;[\w-]+) (\#(?&lt;tag&gt;[\w\-\.]+))? \z }xi.freeze SSH_REGEX = %r{ \A (?&lt;source_url&gt; git@(?&lt;type&gt;github\.com|gitlab\.com|bitbucket\.org): (?&lt;owner&gt;[\w-]+)/(?&lt;name&gt;[\w-]+) (\.git)? ) (\#(?&lt;tag&gt;[\w\-\.]+))? \z }xi.freeze HTTPS_REGEX = %r{ \A (?&lt;source_url&gt; https://(?&lt;type&gt;github\.com|gitlab\.com|bitbucket\.org)/ (?&lt;owner&gt;[\w-]+)/(?&lt;name&gt;[\w-]+) ) (\#(?&lt;tag&gt;[\w\-\.]+))? \z }xi.freeze def initialize(uri) @uri = uri raise "Required constant REPO_TYPES not defined" unless defined? REPO_TYPES parse_uri # debug unless @source_url.nil? end def valid_uri? @uri.end_with?(".git") || @uri.include?("/") end def parse_uri if @uri.end_with? ".git" @type = REPO_TYPES[:custom] return end repo = match_repo_info return nil if repo.nil? @owner = repo[:owner] @name = repo[:name] @tag = repo[:tag] @source_url = make_source_url repo end def match_repo_info [PREFIX_REGEX, SSH_REGEX, HTTPS_REGEX].each do |regex| repo_matches = regex.match @uri unless repo_matches.nil? @type = find_repo_type repo_matches[:type] return repo_matches end end nil end def find_repo_type(type) REPO_TYPES.each do |_, repo_type| return repo_type if repo_type.id? type end REPO_TYPES[:github] end def make_source_url(repo) return repo[:source_url] if repo.names.include? "source_url" source_url = @type.full_url || @uri "#{source_url}/#{@owner}/#{@name}" end def download_command(output_folder=nil) tag_spec = @tag.nil? ? "" : "--branch #{@tag}" parts = [ "git clone --quiet --depth 1", tag_spec, @source_url, output_folder || @name, ] parts.join " " end def debug puts "" puts "source_url: #{@source_url}" unless @source_url.nil? puts "owner: #{@owner}" unless @owner.nil? puts "name: #{@name}" unless @name.nil? puts "tag: #{@tag}" unless @tag.nil? puts "download cmd: #{download_command}" end end </code></pre> <h2>tests.rb</h2> <pre class="lang-rb prettyprint-override"><code>VALID = %w[ user1/repo1 github:user2/repo2 git@github.com:user3/repo3 https://github.com/rmccue/test-repository gitlab:user5/repo5 git@gitlab.com:user6/repo6 https://gitlab.com/user7/repo7 bitbucket:user8/repo8 git@bitbucket.org:user9/repo9 https://bitbucket.org/user0/repo0 ].freeze INVALID = %w[ http://github.com/user1/repo1 https://github.com/user2 https://github.comuser3/repo3 ].freeze WITH_TAG = %w[ user1/repo1#dev user2/repo2#v1.2.3 user3/repo3#1234abcd ].freeze WITH_GIT_SUFFIX = %w[ https://github.com/Rich-Harris/degit.git user@host:~/repos/website.nl.git ].freeze def pf(str) print str $stdout.flush end def run_tests pf " VALID: " VALID.each do |r| pf "." repo = Repo.new r raise "#{r} isn't valid" if repo.type.nil? end puts "" pf " INVALID: " INVALID.each do |r| pf "." repo = Repo.new r raise "#{r} isn't invalid" unless repo.type.nil? end puts "" pf " WITH_TAG: " WITH_TAG.each do |r| pf "." repo = Repo.new r raise "#{r} isn't valid" if repo.type.nil? raise "#{r} has no tag" if repo.tag.nil? end puts "" pf "WITH_GIT_SUFFIX: " WITH_GIT_SUFFIX.each do |r| pf "." repo = Repo.new r raise "#{r} isn't valid" if repo.type.nil? end puts "" end </code></pre>
[]
[ { "body": "<p>Ruby does not have an import system like python, so variables and methods at the top level like <code>REPO_TYPES</code> and <code>temp_dir</code> are effectively global variables and methods.</p>\n\n<p>Use modules to aggressively namespace, even for your <code>main</code>, especially when a small script begins to span more than one file:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>module Degit\n def self.main # define singleton method\n end\nend\n\nDegit.main # call singleton method\n</code></pre>\n\n<p>This is also true for methods as well. <code>def self.main</code> in the example defines a singleton method on <code>Degit</code> itself. (<code>Degit</code> is a singleton in the sense that it will be the only instance of <code>Module</code> named \"Degit\", and <code>main</code> is a method it will now have).</p>\n\n<p>Ruby classes operate in the same way:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>class Foo\n class &lt;&lt; self # opens singleton context\n def foo # also defines a singleton method\n end\n end\nend\n</code></pre>\n\n<p>On another note, I feel like <code>RepoType</code> should either be:</p>\n\n<ul>\n<li>completely removed and its responsibilities handled by <code>Repo</code></li>\n</ul>\n\n<p>Or</p>\n\n<ul>\n<li>named <code>Host</code> and be more cohesive by owning variables and methods <code>REPO_TYPE</code> and <code>find_repo_type</code> within it, along with the regex definitions associated with each <code>Host</code></li>\n</ul>\n\n<p>Here's an example combining what I've outlined above:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>class Host\n HOST_DEFN = {\n github: 'github.com',\n gitlab: 'gitlab.com',\n bitbucket: 'bitbucket.org',\n }\n\n attr_reader :name, :hostname\n\n def initialize(name, hostname)\n @name = name\n @hostname = hostname\n end\n\n def match?(uri)\n regexes.each_value.any? do |regex|\n regex.match?(uri)\n end\n end\n\n private\n\n def regexes\n {\n ssh: /ssh #{hostname} ssh/,\n https: /https #{hostname} https/,\n }\n end\n\n class &lt;&lt; self\n def hosts\n @hosts ||= HOST_DEFN.map { |name, hostname| [name, new(name, hostname)] }.to_h\n end\n\n def matching_uri(uri)\n hosts.each_value.detect { |host| host.match?(uri) }\n end\n end\nend\n\n# usage\n\nHost.hosts[:github] # =&gt; #&lt;Host:0x00007fd95c48b5d8 @hostname=\"github.com\", @name=:github&gt;\n\nuri = 'https gitlab.com https'\nHost.matching_uri(uri) # =&gt; #&lt;Host:0x00007fd95c462c00 @hostname=\"gitlab.com\", @name=:gitlab&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-03T09:28:39.237", "Id": "214633", "ParentId": "212632", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T15:28:19.093", "Id": "212632", "Score": "4", "Tags": [ "beginner", "ruby", "console", "git" ], "Title": "Download a Git repo without .git folder" }
212632
<p>I am currently working on a bigger project where I found a part of it which seems very ugly to me from the code.</p> <p>I stripped out the algorithm and made a working code, so it can be reviewed.</p> <p>I have a data structure which contains several containers with several different objects:</p> <pre><code>struct Data { std::vector&lt;TypeA&gt; a; std::vector&lt;TypeB&gt; b; std::vector&lt;TypeC&gt; c; } </code></pre> <p><code>TypeA</code>, <code>TypeB</code> and <code>TypeC</code> are all different objects with different sizes in the real programm. The comman part is they all have a <code>no</code>:</p> <pre><code>struct TypeA { std::size_t no; std::string data; std::string data2; // more data member etc... }; struct TypeB { std::size_t no; std::string data; std::string data2; // more data member etc... }; struct TypeC { std::size_t no; std::string data; std::string data2; // more data member etc... }; </code></pre> <p>All Containers are ordered by ascending <code>no</code>:</p> <pre><code>Data d; d.a.push_back(TypeA{ 1, &quot;1&quot; , &quot;11&quot; }); d.c.push_back(TypeC{ 2, &quot;2&quot;, &quot;12&quot; }); d.b.push_back(TypeB{ 3, &quot;3&quot;, &quot;13&quot; }); d.a.push_back(TypeA{ 4, &quot;4&quot;, &quot;14&quot; }); d.c.push_back(TypeC{ 5, &quot;5&quot;, &quot;15&quot; }); d.b.push_back(TypeB{ 6, &quot;6&quot;, &quot;16&quot; }); </code></pre> <p>All Numbers are unique, e.g. there's no <code>no==1</code> in <code>b</code> or <code>c</code>. The index numbers are consecutive and fill the data structures.</p> <p>I want to iterate over the whole <code>struct Data</code> by the <code>no</code> of the different data members and do something with the additional shared things the containers have.</p> <p>To emphasize the ugliness, I sometimes print <code>data1</code> and the other time <code>data2</code> but the iteration is exactly the same.</p> <p>How can the algorithm be improved?</p> <p>My idea would be writing an custom iterator for <code>Data</code> which iterates by the <code>no</code>. But I don't know what is the best approach.</p> <p>I'm open to any suggestions.</p> <p>The complete code:</p> <h3>example.cpp</h3> <pre><code>#include &lt;vector&gt; #include &lt;limits&gt; #include &lt;iostream&gt; #include &lt;string&gt; struct TypeA { std::size_t no; std::string data; std::string data2; // more data member etc... }; struct TypeB { std::size_t no; std::string data; std::string data2; // more data member etc... }; struct TypeC { std::size_t no; std::string data; std::string data2; // more data member etc... }; // In reality TypeA, TypeB and TypeC are not exactly the same struct Data { std::vector&lt;TypeA&gt; a; std::vector&lt;TypeB&gt; b; std::vector&lt;TypeC&gt; c; // In reality there are not only 3 values // but &gt; 20 to print consecutively by no void print_data_in_order_of_no(); void print_data2_in_order_of_no(); }; </code></pre> <pre><code>void Data::print_data_in_order_of_no() { enum class It_out { none, a, b, c, }; auto it_a = a.begin(); auto it_b = b.begin(); auto it_c = c.begin(); std::size_t current_no = 0; auto it_out = It_out::none; do { auto possible_new_no = std::numeric_limits&lt;size_t&gt;::max(); it_out = It_out::none; if (it_a != a.end() &amp;&amp; it_a-&gt;no &gt; current_no &amp;&amp; it_a-&gt;no &lt; possible_new_no) { possible_new_no = it_a-&gt;no; it_out = It_out::a; } if (it_b != b.end() &amp;&amp; it_b-&gt;no &gt; current_no &amp;&amp; it_b-&gt;no &lt; possible_new_no) { possible_new_no = it_b-&gt;no; it_out = It_out::b; } if (it_c != c.end() &amp;&amp; it_c-&gt;no &gt; current_no &amp;&amp; it_c-&gt;no &lt; possible_new_no) { possible_new_no = it_c-&gt;no; it_out = It_out::c; } current_no = possible_new_no; switch (it_out) { case It_out::a: std::cout &lt;&lt; it_a-&gt;data &lt;&lt; '\n'; ++it_a; break; case It_out::b: std::cout &lt;&lt; it_b-&gt;data &lt;&lt; '\n'; ++it_b; break; case It_out::c: std::cout &lt;&lt; it_c-&gt;data &lt;&lt; '\n'; ++it_c; break; case It_out::none: break; default: throw std::runtime_error( &quot;void print_data_in_order_of_no()&quot; &quot;impossible enum type&quot; ); } } while (it_out != It_out::none); } </code></pre> <pre><code>void Data::print_data2_in_order_of_no() { enum class It_out { none, a, b, c, }; auto it_a = a.begin(); auto it_b = b.begin(); auto it_c = c.begin(); std::size_t current_no = 0; auto it_out = It_out::none; do { auto possible_new_no = std::numeric_limits&lt;size_t&gt;::max(); it_out = It_out::none; if (it_a != a.end() &amp;&amp; it_a-&gt;no &gt; current_no &amp;&amp; it_a-&gt;no &lt; possible_new_no) { possible_new_no = it_a-&gt;no; it_out = It_out::a; } if (it_b != b.end() &amp;&amp; it_b-&gt;no &gt; current_no &amp;&amp; it_b-&gt;no &lt; possible_new_no) { possible_new_no = it_b-&gt;no; it_out = It_out::b; } if (it_c != c.end() &amp;&amp; it_c-&gt;no &gt; current_no &amp;&amp; it_c-&gt;no &lt; possible_new_no) { possible_new_no = it_c-&gt;no; it_out = It_out::c; } current_no = possible_new_no; switch (it_out) { case It_out::a: std::cout &lt;&lt; it_a-&gt;data2 &lt;&lt;'\n'; ++it_a; break; case It_out::b: std::cout &lt;&lt; it_b-&gt;data2 &lt;&lt; '\n'; ++it_b; break; case It_out::c: std::cout &lt;&lt; it_c-&gt;data2 &lt;&lt; '\n'; ++it_c; break; case It_out::none: break; default: throw std::runtime_error( &quot;void print_data2_in_order_of_no()&quot; &quot;impossible enum type&quot; ); } } while (it_out != It_out::none); } </code></pre> <pre><code>int main() { Data d; d.a.push_back(TypeA{1, &quot;1&quot; , &quot;11&quot;}); d.a.push_back(TypeA{ 4, &quot;4&quot;, &quot;14&quot; }); d.b.push_back(TypeB{ 3, &quot;3&quot;, &quot;13&quot; }); d.b.push_back(TypeB{ 6, &quot;6&quot;, &quot;16&quot; }); d.c.push_back(TypeC{ 2, &quot;2&quot;, &quot;12&quot; }); d.c.push_back(TypeC{ 5, &quot;5&quot;, &quot;15&quot; }); d.print_data_in_order_of_no(); d.print_data2_in_order_of_no(); std::cin.get(); } </code></pre> <p>The code for review is the <code>Data</code> struct and its members.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T16:05:16.863", "Id": "411308", "Score": "1", "body": "Is `no` used for something else or just for indexing/identification? If the latter, move `no` out of `TypeX` and join `TypeA`, `TypeB`, `TypeC` into a separate structure and use this structure in the container." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T16:28:18.070", "Id": "411316", "Score": "0", "body": "its only used for indexing. So you mean like a struct which have `TypeA` `TypeB` `TypeC` were only one member is occupied at the time?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T16:54:20.850", "Id": "411319", "Score": "2", "body": "I think Cornholio meant something like a `std::vector<std::variant<TypeA, TypeB, TypeC>>` (where those three types have no `no` member since they are all explicitly ordered inside the container)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T19:38:28.890", "Id": "411336", "Score": "0", "body": "I don't think he wants a `std::variant` here, since he needs all of the `TypeA, TypeB, TypeC` containers to be valid at the same time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T20:25:17.887", "Id": "411339", "Score": "0", "body": "`std::variant` was exactly what i was looking for the whole day. In combination with std::visit i can perform any operation necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T20:31:17.810", "Id": "411340", "Score": "0", "body": "i edited how the order of the elements come. in the real code the data comes consecutively with the index but as different data types. perfectly for the suggested `std::variant`" } ]
[ { "body": "<p>As mentioned in a comment, I found <code>std::variant</code> to be a good solution for my issue:</p>\n\n<p>I also added a template visitor it can save writing a lot of visitors if in all data structures the same thing needs to get accessed.</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;limits&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;variant&gt;\n\nstruct TypeA {\n std::size_t no;\n std::string data;\n std::string data2;\n // more data member etc...\n};\n\nstruct TypeB {\n std::size_t no;\n std::string data;\n std::string data2;\n // more data member etc...\n};\n\nstruct TypeC {\n std::size_t no;\n std::string data;\n std::string data2;\n // more data member etc...\n};\n\n// In reality TypeA, TypeB and TypeC are not exactly the same\n\nstruct Data {\n std::vector&lt;std::variant&lt; TypeA, TypeB, TypeC&gt;&gt; abc;\n\n std::vector&lt;TypeA&gt; a;\n std::vector&lt;TypeB&gt; b;\n std::vector&lt;TypeC&gt; c;\n\n // In reality there are not only 3 values \n // but &gt; 20 to print consecutively by no\n};\n\nstruct Visit_data\n{\n std::string operator()(TypeA&amp; a) const { return a.data; } \n std::string operator()(TypeB&amp; b) const { return b.data; }\n std::string operator()(TypeC&amp; c) const { return c.data; }\n};\n\nstruct Visit_data2\n{\n std::string operator()(TypeA&amp; a) const { return a.data2; }\n std::string operator()(TypeB&amp; b) const { return b.data2; }\n std::string operator()(TypeC&amp; c) const { return c.data2; }\n};\n\nstruct Visit_template_data\n{\n template&lt;typename T&gt;\n std::string operator()(T&amp; a) const { return a.data; }\n};\n\nint main()\n{\n Data d;\n\n d.abc.push_back(TypeA{ 1, \"1\" , \"11\"});\n d.abc.push_back(TypeC{ 2, \"2\", \"12\" });\n d.abc.push_back(TypeB{ 3, \"3\", \"13\" });\n d.abc.push_back(TypeA{ 4, \"4\", \"14\" });\n d.abc.push_back(TypeC{ 5, \"5\", \"15\" });\n d.abc.push_back(TypeB{ 6, \"6\", \"16\" });\n\n for (auto&amp; x : d.abc) {\n std::cout &lt;&lt; std::visit(Visit_data(), x);\n }\n for (auto&amp; x : d.abc) {\n std::cout &lt;&lt; std::visit(Visit_data2(), x);\n }\n\n for (auto&amp; x : d.abc) {\n std::cout &lt;&lt; std::visit(Visit_template_data(), x);\n }\n\n std::cin.get();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T08:37:49.143", "Id": "411377", "Score": "0", "body": "I was going to suggest using the Visitor pattern as well as Variant, but you totally beat me to it! See also the [`std::visit` example](https://en.cppreference.com/w/cpp/utility/variant/visit#Example) on CPP Reference for a way to create a an overloaded visitor, which might help you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T09:54:13.897", "Id": "411385", "Score": "0", "body": "You have no idea how I patted my head when i realized I could refactor many poorly and overly complicated parts in the code by switching to `std::variant`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T20:30:08.353", "Id": "212651", "ParentId": "212635", "Score": "2" } } ]
{ "AcceptedAnswerId": "212651", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T15:43:44.743", "Id": "212635", "Score": "2", "Tags": [ "c++", "iterator", "c++17" ], "Title": "Iterating over different Objects which are ordered by index number" }
212635
<p>Now that async generators are available in the platforms I care about, I figured I'd try porting Python's ingenious <code>with</code> construct to JS as a utility. My first stab looks like this:</p> <pre><code>type Index = string | symbol | number; function isIndex(obj: any): obj is Index { return ( typeof obj === 'string' || typeof obj === 'symbol' || typeof obj === 'number' ); } type Disposable&lt;TDisposerKey extends Index&gt; = { [k in TDisposerKey]: DisposerMethod }; type DisposerMethod = () =&gt; void | Promise&lt;void&gt;; type DisposerCallback&lt;TDisposable&gt; = (res: TDisposable) =&gt; void | Promise&lt;void&gt;; function using&lt; TDisposerKey extends Index, TDisposable extends Disposable&lt;TDisposerKey&gt; &gt;(resource: TDisposable, key: TDisposerKey): AsyncIterable&lt;TDisposable&gt;; function using&lt;TDisposable&gt;( resource: TDisposable, disposer: DisposerCallback&lt;TDisposable&gt; ): AsyncIterable&lt;TDisposable&gt;; async function* using&lt; TDisposerKey extends Index, TDisposable extends Disposable&lt;TDisposerKey&gt; &gt;( resource: TDisposable, keyOrDisposer: TDisposerKey | DisposerCallback&lt;TDisposable&gt; ): AsyncIterable&lt;TDisposable&gt; { try { yield resource; } finally { if (typeof keyOrDisposer === 'function') { await keyOrDisposer(resource); } else if (isIndex(keyOrDisposer)) { await resource[keyOrDisposer](); } } } async function main(): Promise&lt;any&gt; { for await (const db of using(new PouchDB('zz-data\\foo'), 'close')) { console.dir(await db.info()); return await db.get('qwertyuiop'); } } </code></pre> <p>Does anything jump out at anybody? A <code>for..await..of</code> loop with only one iteration is odd, but it's the only way to handle this lexically, and it saves me having to juggle types for a callback-based alternative which was fiddly to make generic. The overloads are also a mouthful, but that's TS for you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-03T19:03:57.483", "Id": "411589", "Score": "0", "body": "I can't decide if this is amazing or horrible... the iteration is clever, but quite confusing without knowing exactly how `using` works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-04T19:00:17.923", "Id": "411690", "Score": "0", "body": "It helps to know the link between iterators and coroutines and how the Python original works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-04T19:02:36.567", "Id": "411691", "Score": "0", "body": "Sadly this messes with type checking because TS doesn’t know that the loop will run (at least) once, so it insists on having `undefined` be in the return type." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T15:57:13.813", "Id": "212636", "Score": "2", "Tags": [ "async-await", "typescript" ], "Title": "Porting python's 'with' construct to TypeScript" }
212636
<p>I am trying to use aiohttp library in python to download information from url. I have about 300 000 urls. They are saved in file "my_file.txt". When I get web page, I extract pairs of a question and an answer from ask.fm. (it is a website where you can post an anonymous question to some user, and get an answer). And then I look for the next page of answers from the current user, and add it to the list new_urls to use it in the next iteration of a program.</p> <p>The problem is: the speed of my program is about 1000 pages/minute. Can I somehow speed it up? Do I do something wrong? If I change number of TCPConnections -- nothing changes. </p> <pre><code>from bs4 import BeautifulSoup import asyncio import aiohttp import time new_urls = [] k = [0] async def fetch_url(session, url): async with session.get(url, timeout=1000 * 60) as response: f = await response.text() quest_answ_user = [] try: soup = BeautifulSoup(f, 'html.parser') s = soup.find_all('article', attrs={'class': 'item streamItem streamItem-answer '}) for el in s: quest = el.find('header').find('h2').text list_ans = el.find_all('div', attrs={'class': ['streamItem_content']}) if len(list_ans) == 0: continue ans = list_ans[0].text quest_answ_user.append([quest, ans]) next_page = soup.select('.item-page-next') if len(next_page) != 0: new_urls.append(next_page[0].get('href')) print(url, len(quest_answ_user)) k[0] += 1 print(k) except Exception as e: print(url) print(e) return quest_answ_user async def fetch_all_urls(session, urls): results = await asyncio.gather(*[fetch_url(session, url) for url in urls], return_exceptions=True) return results async def get_htmls(urls, loop): connector = aiohttp.TCPConnector(limit=100) async with aiohttp.ClientSession(loop=loop, connector=connector) as session: list_dialogue = await fetch_all_urls(session, urls) return list_dialogue def main(): with open('./my_file.txt', 'r') as f: urls = f.readlines() cur_t = time.time() count = 0 while len(urls) &gt;= 100 and count &lt;= 50000000: urls = ['https://ask.fm' + url.strip('\n') for url in urls] loop = asyncio.get_event_loop() r = loop.run_until_complete(get_htmls(urls, loop)) mode = 'w' if count == 0 else 'a' with open('./dialogues4.txt', mode=mode, encoding='utf-8') as f: for item in r: try: count += len(item) for i in item: f.write(f'{i}\n') except Exception as e: print(e) print(len(new_urls)) urls = new_urls.copy() new_urls.clear() with open('./for_continuation2.txt', 'w') as f: for item in urls: f.write(f'{item}\n') print(count) print(time.time() - cur_t) main() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T17:11:38.090", "Id": "212639", "Score": "2", "Tags": [ "python", "web-scraping", "asynchronous" ], "Title": "Downloading multiple urls with aiohttp Python 3" }
212639
<p>I like Node.js and typescript a lot, but i'm still pretty much a newbie with streams. I know how to use them, but I have trouble understanding how the work, what are the consequences of using them, etc.</p> <p>I've made a wrapper (feel free to use it, it's on NPM) around the stream, using array like functions, while keeping types correct with TS (which, I think, event-stream doesn't do efficiently).</p> <p><a href="https://github.com/AGallouin/Node.ts-Streams" rel="nofollow noreferrer">https://github.com/AGallouin/Node.ts-Streams</a></p> <p>Thanks a lot for any advice !</p> <pre><code>import { Readable, Transform, Writable } from 'stream' export class Stream&lt;T&gt; { private readonly underlying: Readable constructor(stream: Readable) { this.underlying = stream } static fromArray&lt;T&gt;(input: Array&lt;T&gt;): Stream&lt;T&gt; { const readable = new Readable({ objectMode: true, read: () =&gt; {} }) for (let i = 0; i &lt; input.length; i++) { readable.push(input[i]) } readable.push(null) return new Stream&lt;T&gt;(readable) } map&lt;O&gt;(map: (value: T) =&gt; O | Promise&lt;O&gt;): Stream&lt;O&gt; { const stream = new Transform({ objectMode: true, transform: (data, encoding, callback) =&gt; { Promise.resolve(map(data)) .then((v) =&gt; callback(undefined, v)) } }) this.underlying.pipe(stream) return new Stream&lt;O&gt;(stream) } reduce&lt;O&gt;(reducer: (acc: O, curr: T) =&gt; O, initialValue: O): Stream&lt;O&gt; { let acc = initialValue const wStream = new Writable({ objectMode: true, write: (curr, encoding, next) =&gt; { acc = reducer(acc, curr) next() } }) const rStream = new Readable({ objectMode: true, read: () =&gt; {} }) this.underlying .pipe(wStream) .on('finish', () =&gt; { rStream.push(acc) rStream.push(null) }) return new Stream&lt;O&gt;(rStream) } filter(filter: (value: T) =&gt; boolean): Stream&lt;T&gt; { const stream = new Transform({ objectMode: true, transform: (data, encoding, callback) =&gt; { if (filter(data)) { callback(undefined, data) } else { callback() } } }) this.underlying.pipe(stream) return new Stream&lt;T&gt;(stream) } addWritingStream(write: (chunk: T, encoding: string, callback: (error?: Error | null) =&gt; void) =&gt; void): Promise&lt;boolean&gt; { return new Promise((resolve, reject) =&gt; { const stream = new Writable({ objectMode: true, write }) this.underlying .pipe(stream) .on('finish', () =&gt; { resolve(true) }) .on('error', () =&gt; { reject(false) }) }) } split(nbElements: number): Stream&lt;Array&lt;T&gt;&gt; { let acc: Array&lt;T&gt; = [] const rStream = new Readable({ objectMode: true, read: () =&gt; {} }) const wStream = new Writable({ objectMode: true, write: (curr, encoding, next) =&gt; { acc.push(curr) if (acc.length === nbElements) { rStream.push(acc) acc = [] } next() } }) this.underlying .pipe(wStream) .on('finish', () =&gt; { if (acc.length &gt; 0) { rStream.push(acc) } rStream.push(null) }) return new Stream&lt;Array&lt;T&gt;&gt;(rStream) } toArray(): Promise&lt;Array&lt;T&gt;&gt; { return new Promise((resolve) =&gt; { const acc: Array&lt;T&gt; = [] const wStream = new Writable({ objectMode: true, write: (curr, encoding, next) =&gt; { acc.push(curr) next() } }) this.underlying .pipe(wStream) .on('finish', () =&gt; { resolve(acc) }) }) } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T18:30:01.653", "Id": "212646", "Score": "1", "Tags": [ "node.js", "stream", "typescript" ], "Title": "Stream wrapper in node.ts" }
212646
<p>This program takes two numbers M(&lt;10k) and N (&lt;100) and finds the smallest number greater than M whose sum of digits = N. Additionally, as per the question's requirements, it prints the number of digits in the printed number. </p> <p>Example: M = 919 , N = 34</p> <p>Required number = 7999 as 7+9+9+9 = 34</p> <pre><code> /** *Takes M and N , finds the number greater than M whose sum of digits = N */ import java.util.*; class MtoN { static int sumOfdigits(int n) { int sum =0 ; while(n!=0) { sum = sum + n%10; n = n/10; } return sum; } static int numOfdigits(int n) { String str = Integer.toString(n); return str.length(); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter M (100 to 10000)"); int M = sc.nextInt(); System.out.println("Enter N (less than 100)"); int N = sc.nextInt(); if(N&gt; 100 || M&gt;10000 || M&lt;100) { System.out.println("INVALID INPUT"); } else { for(int i = M+1 ; ; i++) { if(sumOfdigits(i) == N) { System.out.println("Required Number is: "+ i); System.out.println("Number of digits in it "+ numOfdigits(i)); break; } } } } } </code></pre> <p>It works fine for smaller number but takes TOO much time for numbers like: M = 9181 and N = 99. (In fact, it doesn't even print the result on my screen...)</p> <p>How do I reduce this execution time? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T21:47:55.343", "Id": "411347", "Score": "0", "body": "For `M = 9181; N = 99`, note that the sum of `Long.MAX_VALUE`'s digits is only 88. `Integer/MAX_VALUE`'s is only 46. You're going to need `BigInteger` to be able to calculate this. `int`s, and even `long`s aren't big enough to hold the required numbers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T22:01:38.097", "Id": "411352", "Score": "0", "body": "For one thing, you can take advantage of the fact that the sum of digits increases by only one most of the time. Only when there is a carry out of the least significant digit do you have to recalculate." } ]
[ { "body": "<p>This is not a review, but an extended comment.</p>\n\n<p>Thou shalt not brute force. Instead of inspecting every number larger than M (it indeed takes too much time), consider partitioning N into a sum of single digit numbers, and use these partitions to form the answer.</p>\n\n<p>Notice that you don't have to inspect all the partitions. The digit composition of M gives enough leads to just construct the answer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T21:26:27.037", "Id": "212656", "ParentId": "212652", "Score": "3" } }, { "body": "<p>As you have observed, this is not a problem you should solve using integer data types. Instead, simply compute an array of digits, then emit that as a string.</p>\n\n<p>For the particular example you cite (M=9181, N=99) what <em>is</em> the lowest valued 'integer' that produces a sum-of-digits of 99? According to me, it's 11 digits 9 all in a row: 99_999_999_999. Now in your rules, M is required to be &lt; 10k, so I don't think you'll have to worry about overflowing that. Thus, make an array of 11 digits, initialize it to all zeroes, and solve your problems using this 11 element array instead of a single <code>int</code> or <code>long</code>.</p>\n\n<p>Next, consider this: why is 7999 the smallest integer with SOD = 34? Because 9's advance the SOD the most, and the remainder should be in the most-significant-digit to provide the greatest reduction in value: 7999 is lower than 9799, 9979, or 9997. </p>\n\n<p>For a given value of <strong>M</strong> you have two scenarios: M is less than the target number already (your first example, M=919, N=34) or M is greater than or equal to the target number (e.g., M=8000, N=34). </p>\n\n<p>I think the same solution works for both: start with M, and then \"fill in\" SOD values by incrementing the low digits. If you have to add a digit, start at 1 and work up.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T23:01:38.273", "Id": "212662", "ParentId": "212652", "Score": "3" } } ]
{ "AcceptedAnswerId": "212662", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T20:52:42.820", "Id": "212652", "Score": "3", "Tags": [ "java", "time-limit-exceeded" ], "Title": "Find next number whose sum of digits is N" }
212652
<p>I have modified my implementation of RFC 1951 "Deflate" compression to use two threads. One thread performs the LZ77 matching, looking for sequences of at least three bytes that occur earlier in the input bytes, the other thread does the rest - compression with Huffman coding.</p> <p>It works very well, giving a speed-up of about 30%. On the test I am running, it now out-performs ZLib, the standard implementation, obtaining superior compression without any speed penalty.</p> <p>I am using a combination of Lock, Monitor.Wait, Monitor.Pulse and Thread.MemoryBarrier().</p> <p>As I have not used C# threads before, I am slightly concerned whether I have got everything right, there are potential subtle issues where two threads are operating on shared data, so I'd be interested in reviews on that - is my threading code correct, could it be improved? [ Note: I do not use _ for private fields, please don't review that! ]</p> <p>Here's the modified code:</p> <pre><code>using Generic = System.Collections.Generic; using Monitor = System.Threading.Monitor; using ThreadPool = System.Threading.ThreadPool; using Thread = System.Threading.Thread; #if x32 using uword = System.UInt32; #else using uword = System.UInt64; #endif namespace Pdf { /* RFC 1951 compression ( https://www.ietf.org/rfc/rfc1951.txt ) aims to compress a stream of bytes using : (1) LZ77 matching, where if an input sequences of at least 3 bytes re-occurs, it may be coded as a &lt;length,distance&gt; pointer. (2) Huffman coding, where variable length codes are used, with more frequently used symbols encoded in less bits. The input may be split into blocks, a new block introduces a new set of Huffman codes. The choice of block boundaries can affect compression. The method used to determine the block size is as follows: (1) The size of the next block to be output is set to an initial value. (2) A comparison is made between encoding two blocks of this size, or a double-length block. (3) If the double-length encoding is better, that becomes the block size, and the process repeats. LZ77 compression is implemented as suggested in the standard, although no attempt is made to truncate searches ( except searches terminate when the distance limit of 32k bytes is reached ). Only dynamic huffman blocks are used, no attempt is made to use Fixed or Copy blocks. A second thread is used to perform the LZ77 compression, to allow the Huffman coding and LZ77 comrpression to be done in parallel. Deflator ( this code) typically achieves better compression than ZLib ( http://www.componentace.com/zlib_.NET.htm via https://zlib.net/ ) and while compressing at a similar speed( default options, after warmup ). For example, compressing a font file FreeSans.ttf ( 264,072 bytes ), Zlib output is 148,324 bytes in 19 milliseconds, whereas Deflator output is 143,666 bytes in the same time. Sample usage: byte [] data = { 1, 2, 3, 4 }; var mbs = new MemoryBitStream(); Deflator.Deflate( data, mbs ); byte [] deflated_data = mbs.ToArray(); The MemoryBitStream may alternatively be copied to a stream, this may be useful when writing PDF files ( the intended use case ). Auxiliary top level classes/structs ( included in this file ): * OutBitStream. * MemoryBitStream : an implementation of OutBitStream. * HuffmanCoding calculates Huffman codes. * UlongHeap : used to implement HuffmanCoding. */ sealed class Deflator { public static void Deflate( byte [] input, OutBitStream output ) // Deflate with default options. { Deflator d = new Deflator( input, output ); d.Go(); } // Options : to amend these use new Deflator( input, output ) and set before calling Go(). // Possible "fast" setting : StartBlockSize = 0x4000, LazyMatch = false, DynamicBlockSize = false. public int StartBlockSize = 0x1000; // Increase to go faster ( with less compression ), reduce to try for more compression. public int MaxBufferSize = 0x8000; // Must be power of 2. // Compression options - set false to go faster, with less compression. public bool LZ77 = true; public bool LazyMatch = true; public bool DynamicBlockSize = true; public bool TuneBlockSize = true; public bool RFC1950 = true; // Set false to suppress RFC 1950 fields. public Deflator( byte [] input, OutBitStream output ) { Input = input; Output = output; } public void Go() { if ( RFC1950 ) Output.WriteBits( 16, 0x9c78 ); if ( LZ77 ) { ThreadPool.QueueUserWorkItem( FindMatchesStart, this ); } else { Buffered = Input.Length; } while ( !OutputBlock() ) { if ( LZ77 ) lock( this ) { if ( BufferFull ) Monitor.Pulse( this ); } } if ( RFC1950 ) { Output.Pad( 8 ); Output.WriteBits( 32, Adler32( Input ) ); } } // Private constants. // RFC 1951 match ( LZ77 ) limits. private const int MinMatch = 3; // The smallest match eligible for LZ77 encoding. private const int MaxMatch = 258; // The largest match eligible for LZ77 encoding. private const int MaxDistance = 0x8000; // The largest distance backwards in input from current position that can be encoded. // Instead of initialising LZ77 hashTable and link arrays to -(MaxDistance+1), EncodePosition // is added when storing a value and subtracted when retrieving a value. // This means a default value of 0 will always be more distant than MaxDistance. private const int EncodePosition = MaxDistance + 1; // Private fields. private byte [] Input; private OutBitStream Output; private int Buffered; // How many Input bytes have been processed to intermediate buffer. private int Finished; // How many Input bytes have been written to Output. // Intermediate circular buffer for storing LZ77 matches. private int [] PositionBuffer; private byte [] LengthBuffer; private ushort [] DistanceBuffer; private int BufferMask; private int BufferWrite, BufferRead; // Indexes for writing and reading. // LZ77 hash table ( for MatchPossible function ). private int HashShift; private uint HashMask; private int [] HashTable; // Inter-thread signalling fields. private bool BufferFull = false; private bool InputWait = false; private int InputRequest; // Private functions and classes. private static int CalcBufferSize( int n, int max ) // Calculates a power of 2 &gt;= n, but not more than max. { if ( n &gt;= max ) return max; int result = 1; while ( result &lt; n ) result = result &lt;&lt; 1; return result; } private void FindMatches() // LZ77 compression. { byte [] input = Input; if ( input.Length &lt; MinMatch ) return; int bufferSize = CalcBufferSize( input.Length / 3, MaxBufferSize ); PositionBuffer = new int[ bufferSize ]; LengthBuffer = new byte[ bufferSize ]; DistanceBuffer = new ushort[ bufferSize ]; BufferMask = bufferSize - 1; int limit = input.Length - 2; int hashShift = CalcHashShift( limit * 2 ); uint hashMask = ( 1u &lt;&lt; ( MinMatch * hashShift ) ) - 1; int [] hashTable = new int[ hashMask + 1 ]; int [] link = new int[ limit ]; HashShift = hashShift; HashMask = hashMask; HashTable = hashTable; int position = 0; // position in input. // hash will be hash of three bytes starting at position. uint hash = ( (uint)input[ 0 ] &lt;&lt; hashShift ) + input[ 1 ]; while ( position &lt; limit ) { hash = ( ( hash &lt;&lt; hashShift ) + input[ position + 2 ] ) &amp; hashMask; int hashEntry = hashTable[ hash ]; hashTable[ hash ] = position + EncodePosition; if ( position &gt;= hashEntry ) // Equivalent to position - ( hashEntry - EncodePosition ) &gt; MaxDistance. { position += 1; continue; } link[ position ] = hashEntry; int distance, match = BestMatch( input, position, out distance, hashEntry - EncodePosition, link ); position += 1; if ( match &lt; MinMatch ) continue; // "Lazy matching" RFC 1951 p.15 : if there are overlapping matches, there is a choice over which of the match to use. // Example: "abc012bc345.... abc345". Here abc345 can be encoded as either [abc][345] or as a[bc345]. // Since a range typically needs more bits to encode than a single literal, choose the latter. while ( LazyMatch &amp;&amp; position &lt; limit ) { hash = ( ( hash &lt;&lt; hashShift ) + input[ position + 2 ] ) &amp; hashMask; hashEntry = hashTable[ hash ]; hashTable[ hash ] = position + EncodePosition; if ( position &gt;= hashEntry ) break; link[ position ] = hashEntry; int distance2, match2 = BestMatch( input, position, out distance2, hashEntry - EncodePosition, link ); if ( match2 &gt; match || match2 == match &amp;&amp; distance2 &lt; distance ) { match = match2; distance = distance2; position += 1; } else break; } int copyEnd = SaveMatch( position - 1, match, distance ); if ( copyEnd &gt; limit ) copyEnd = limit; position += 1; // Advance to end of copied section. while ( position &lt; copyEnd ) { hash = ( ( hash &lt;&lt; hashShift ) + input[ position + 2 ] ) &amp; hashMask; link[ position ] = hashTable[ hash ]; hashTable[ hash ] = position + EncodePosition; position += 1; } } HashTable = null; // To potentially free up memory. lock( this ) { Buffered = Input.Length; if ( InputWait ) Monitor.Pulse( this ); } } // BestMatch finds the best match starting at position. // oldPosition is from hash table, link [] is linked list of older positions. private int BestMatch( byte [] input, int position, out int bestDistance, int oldPosition, int [] link ) { int avail = input.Length - position; if ( avail &gt; MaxMatch ) avail = MaxMatch; int bestMatch = 0; bestDistance = 0; byte keyByte = input[ position + bestMatch ]; while ( true ) { if ( input[ oldPosition + bestMatch ] == keyByte ) { int match = 0; while ( match &lt; avail &amp;&amp; input[ position + match ] == input[ oldPosition + match ] ) { match += 1; } if ( match &gt; bestMatch ) { bestMatch = match; bestDistance = position - oldPosition; if ( bestMatch == avail || ! MatchPossible( position, bestMatch + 1 ) ) break; keyByte = input[ position + bestMatch ]; } } oldPosition = link[ oldPosition ]; if ( position &gt;= oldPosition ) break; oldPosition -= EncodePosition; } return bestMatch; } // MatchPossible is used to try and shorten the BestMatch search by checking whether // there is a hash entry for the last 3 bytes of the next longest possible match. private bool MatchPossible( int position, int matchLength ) { int end = position + matchLength - 3; uint hash = ( (uint)Input[ end + 0 ] &lt;&lt; HashShift ) + Input[ end + 1 ]; hash = ( ( hash &lt;&lt; HashShift ) + Input[ end + 2 ] ) &amp; HashMask; int hashEntry = HashTable[ hash ]; return end &lt; hashEntry; } private static int CalcHashShift( int n ) { int p = 1; int result = 0; while ( n &gt; p ) { p = p &lt;&lt; MinMatch; result += 1; if ( result == 6 ) break; } return result; } private static void FindMatchesStart( System.Object x ) { Deflator d = (Deflator) x; d.FindMatches(); } private int SaveMatch ( int position, int length, int distance ) // Called from FindMatches to save a &lt;length,distance&gt; match. Returns position + length. { int i = BufferWrite; PositionBuffer[ i ] = position; LengthBuffer[ i ] = (byte) (length - MinMatch); DistanceBuffer[ i ] = (ushort) distance; i = ( i + 1 ) &amp; BufferMask; while ( i == BufferRead ) lock ( this ) { BufferFull = true; if ( InputWait ) Monitor.Pulse( this ); Monitor.Wait( this ); BufferFull = false; } Thread.MemoryBarrier(); BufferWrite = i; position += length; Buffered = position; if ( InputWait &amp;&amp; position &gt;= InputRequest ) lock ( this ) Monitor.Pulse( this ); return position; } private int WaitForInput( int request ) { while ( true ) lock( this ) { if ( Buffered == Input.Length || BufferFull || Buffered &gt;= request ) return Buffered; else { InputRequest = request; InputWait = true; Monitor.Wait( this ); InputWait = false; } } } private bool OutputBlock() { int blockSize = WaitForInput( Finished + StartBlockSize ) - Finished; if ( blockSize &gt; StartBlockSize ) { blockSize = ( Buffered == Input.Length &amp;&amp; blockSize &lt; StartBlockSize * 2 ) ? blockSize &gt;&gt; 1 : StartBlockSize; } Block b = new Block( this, blockSize, null ); int bits = b.GetBits(); // Compressed size in bits. int tunedBlockSize = blockSize; // Investigate larger block size. while ( DynamicBlockSize ) { int avail = WaitForInput( b.End + blockSize ); if ( b.End + blockSize &gt; avail ) break; // b2 is a block which starts just after b. Block b2 = new Block( this, blockSize, b ); // b3 covers b and b2 exactly as one block. Block b3 = new Block( this, b2.End - b.Start, null ); int bits2 = b2.GetBits(); int bits3 = b3.GetBits(); int delta = TuneBlockSize ? b2.TuneBoundary( this, b, blockSize / 4, out tunedBlockSize ) : 0; if ( bits3 &gt; bits + bits2 + delta ) break; bits = bits3; b = b3; blockSize += blockSize; tunedBlockSize = blockSize; } if ( tunedBlockSize &gt; blockSize ) { b = new Block( this, tunedBlockSize, null ); b.GetBits(); } bool last = b.End == Input.Length; b.WriteBlock( this, last ); return last; } public static uint Adler32( byte [] b ) // Checksum function per RFC 1950. { uint s1 = 1, s2 = 0; for ( int i = 0; i &lt; b.Length; i += 1 ) { s1 = ( s1 + b[ i ] ) % 65521; s2 = ( s2 + s1 ) % 65521; } return s2 * 65536 + s1; } private class Block { public readonly int Start, End; // Range of input encoded. public Block( Deflator d, int blockSize, Block previous ) // The block is not immediately output, to allow caller to try different block sizes. // Instead, the number of bits neeed to encoded the block is returned by GetBits ( excluding "extra" bits ). { Output = d.Output; if ( previous == null ) { Start = d.Finished; BufferStart = d.BufferRead; } else { Start = previous.End; BufferStart = previous.BufferEnd; } int avail = d.Buffered - Start; if ( blockSize &gt; avail ) blockSize = avail; End = TallyFrequencies( d, blockSize ); Lit.Used[ 256 ] += 1; // End of block code. } public int GetBits() { Lit.ComputeCodes(); Dist.ComputeCodes(); if ( Dist.Count == 0 ) Dist.Count = 1; // Compute length encoding. DoLengthPass( 1 ); Len.ComputeCodes(); // The length codes are permuted before being stored ( so that # of trailing zeroes is likely to be more ). Len.Count = 19; while ( Len.Count &gt; 4 &amp;&amp; Len.Bits[ ClenAlphabet[ Len.Count - 1 ] ] == 0 ) Len.Count -= 1; return 17 + 3 * Len.Count + Len.Total() + Lit.Total() + Dist.Total(); } public void WriteBlock( Deflator d, bool last ) { OutBitStream output = Output; output.WriteBits( 1, last ? 1u : 0u ); output.WriteBits( 2, 2 ); output.WriteBits( 5, (uint)( Lit.Count - 257 ) ); output.WriteBits( 5, (uint)( Dist.Count - 1 ) ); output.WriteBits( 4, (uint)( Len.Count - 4 ) ); for ( int i = 0; i &lt; Len.Count; i += 1 ) output.WriteBits( 3, Len.Bits[ ClenAlphabet[ i ] ] ); DoLengthPass( 2 ); PutCodes( d ); output.WriteBits( Lit.Bits[ 256 ], Lit.Codes[ 256 ] ); // End of block code } // Block private fields and constants. private OutBitStream Output; private int BufferStart, BufferEnd; // Huffman codings : Lit = Literal or Match Code, Dist = Distance code, Len = Length code. HuffmanCoding Lit = new HuffmanCoding(15,288), Dist = new HuffmanCoding(15,32), Len = new HuffmanCoding(7,19); // Counts for code length encoding. private int LengthPass, PreviousLength, ZeroRun, Repeat; // RFC 1951 constants. private readonly static byte [] ClenAlphabet = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; private readonly static byte [] MatchExtra = { 0,0,0,0, 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3, 4,4,4,4, 5,5,5,5, 0 }; private readonly static ushort [] MatchOff = { 3,4,5,6, 7,8,9,10, 11,13,15,17, 19,23,27,31, 35,43,51,59, 67,83,99,115, 131,163,195,227, 258, 0xffff }; private readonly static byte [] DistExtra = { 0,0,0,0, 1,1,2,2, 3,3,4,4, 5,5,6,6, 7,7,8,8, 9,9,10,10, 11,11,12,12, 13,13 }; private readonly static ushort [] DistOff = { 1,2,3,4, 5,7,9,13, 17,25,33,49, 65,97,129,193, 257,385,513,769, 1025,1537,2049,3073, 4097,6145,8193,12289, 16385,24577 }; // Block private functions. private int TallyFrequencies( Deflator d, int blockSize ) { int position = Start; int end = position + blockSize; int bufferRead = BufferStart; while ( position &lt; end &amp;&amp; bufferRead != d.BufferWrite ) { int matchPosition = d.PositionBuffer[ bufferRead ]; if ( matchPosition &gt;= end ) break; int length = d.LengthBuffer[ bufferRead ] + MinMatch; int distance = d.DistanceBuffer[ bufferRead ]; bufferRead = ( bufferRead + 1 ) &amp; d.BufferMask; byte [] input = d.Input; while ( position &lt; matchPosition ) { Lit.Used[ input[ position ] ] += 1; position += 1; } position += length; // Compute match and distance codes. int mc = 0; while ( length &gt;= MatchOff[ mc ] ) mc += 1; mc -= 1; int dc = 29; while ( distance &lt; DistOff[ dc ] ) dc -= 1; Lit.Used[ 257 + mc ] += 1; Dist.Used[ dc ] += 1; } while ( position &lt; end ) { Lit.Used[ d.Input[ position ] ] += 1; position += 1; } BufferEnd = bufferRead; return position; } public int TuneBoundary( Deflator d, Block prev, int howfar, out int blockSize ) { // Investigate whether moving data into the previous block uses fewer bits, // using the current encodings. If a symbol with no encoding in the // previous block is found, terminate the search ( goto EndSearch ). int position = Start; int bufferRead = BufferStart; int end = position + howfar; if ( end &gt; End ) end = End; int delta = 0, bestDelta = 0, bestPosition = position; while ( position &lt; end &amp;&amp; bufferRead != d.BufferWrite ) { int matchPosition = d.PositionBuffer[ bufferRead ]; if ( matchPosition &gt;= end ) break; int length = d.LengthBuffer[ bufferRead ] + MinMatch; int distance = d.DistanceBuffer[ bufferRead ]; bufferRead = ( bufferRead + 1 ) &amp; d.BufferMask; while ( position &lt; matchPosition ) { byte b = d.Input[ position ]; if ( prev.Lit.Bits[ b ] == 0 ) goto EndSearch; delta += prev.Lit.Bits[ b ] - Lit.Bits[ b ]; if ( delta &lt; bestDelta ) { bestDelta = delta; bestPosition = position; } position += 1; } position += length; // Compute match and distance codes. int mc = 0; while ( length &gt;= MatchOff[ mc ] ) mc += 1; mc -= 1; int dc = 29; while ( distance &lt; DistOff[ dc ] ) dc -= 1; if ( prev.Lit.Bits[ 257 + mc ] == 0 || prev.Dist.Bits[ dc ] == 0 ) goto EndSearch; delta += prev.Lit.Bits[ 257 + mc ] - Lit.Bits[ 257 + mc ]; delta += prev.Dist.Bits[ dc ] - Dist.Bits[ dc ]; if ( delta &lt; bestDelta ) { bestDelta = delta; bestPosition = position; } position += 1; } while ( position &lt; end ) { byte b = d.Input[ position ]; if ( prev.Lit.Bits[ b ] == 0 ) goto EndSearch; delta += prev.Lit.Bits[ b ] - Lit.Bits[ b ]; if ( delta &lt; bestDelta ) { bestDelta = delta; bestPosition = position; } position += 1; } EndSearch: blockSize = bestPosition - prev.Start; return bestDelta; } private void PutCodes( Deflator d ) { byte [] input = d.Input; OutBitStream output = d.Output; int position = Start; int bufferRead = BufferStart; while ( position &lt; End &amp;&amp; bufferRead != d.BufferWrite ) { int matchPosition = d.PositionBuffer[ bufferRead ]; if ( matchPosition &gt;= End ) break; int length = d.LengthBuffer[ bufferRead ] + MinMatch; int distance = d.DistanceBuffer[ bufferRead ]; bufferRead = ( bufferRead + 1 ) &amp; d.BufferMask; while ( position &lt; matchPosition ) { byte b = d.Input[ position ]; output.WriteBits( Lit.Bits[ b ], Lit.Codes[ b ] ); position += 1; } position += length; // Compute match and distance codes. int mc = 0; while ( length &gt;= MatchOff[ mc ] ) mc += 1; mc -= 1; int dc = 29; while ( distance &lt; DistOff[ dc ] ) dc -= 1; output.WriteBits( Lit.Bits[ 257 + mc ], Lit.Codes[ 257 + mc ] ); output.WriteBits( MatchExtra[ mc ], (uint)(length-MatchOff[ mc ] ) ); output.WriteBits( Dist.Bits[ dc ], Dist.Codes[ dc ] ); output.WriteBits( DistExtra[ dc ], (uint)(distance-DistOff[ dc ] ) ); } while ( position &lt; End ) { byte b = input[ position ]; output.WriteBits( Lit.Bits[ b ], Lit.Codes[ b ] ); position += 1; } Thread.MemoryBarrier(); d.BufferRead = bufferRead; d.Finished = position; } // Run length encoding of code lengths - RFC 1951, page 13. private void DoLengthPass( int pass ) { LengthPass = pass; EncodeLengths( Lit.Count, Lit.Bits, true ); EncodeLengths( Dist.Count, Dist.Bits, false ); } private void PutLength( int code ) { if ( LengthPass == 1 ) Len.Used[ code ] += 1; else Output.WriteBits( Len.Bits[ code ], Len.Codes[ code ] ); } private void EncodeLengths( int n, byte [] lengths, bool isLit ) { if ( isLit ) { PreviousLength = 0; ZeroRun = 0; Repeat = 0; } for ( int i = 0; i &lt; n; i += 1 ) { int length = lengths[ i ]; if ( length == 0 ) { if ( Repeat &gt; 0 ) EncodeRepeat(); ZeroRun += 1; PreviousLength = 0; } else if ( length == PreviousLength ) { Repeat += 1; } else { if ( ZeroRun &gt; 0 ) EncodeZeroRun(); if ( Repeat &gt; 0 ) EncodeRepeat(); PutLength( length ); PreviousLength = length; } } if ( !isLit ) { EncodeZeroRun(); EncodeRepeat(); } } private void EncodeRepeat() { while ( Repeat &gt; 0 ) { if ( Repeat &lt; 3 ) { PutLength( PreviousLength ); Repeat -= 1; } else { int x = Repeat; if ( x &gt; 6 ) x = 6; PutLength( 16 ); if ( LengthPass == 2 ) { Output.WriteBits( 2, (uint)( x - 3 ) ); } Repeat -= x; } } } private void EncodeZeroRun() { while ( ZeroRun &gt; 0 ) { if ( ZeroRun &lt; 3 ) { PutLength( 0 ); ZeroRun -= 1; } else if ( ZeroRun &lt; 11 ) { PutLength( 17 ); if ( LengthPass == 2 ) Output.WriteBits( 3, (uint)( ZeroRun - 3 ) ); ZeroRun = 0; } else { int x = ZeroRun; if ( x &gt; 138 ) x = 138; PutLength( 18 ); if ( LengthPass == 2 ) Output.WriteBits( 7, (uint)( x - 11 ) ); ZeroRun -= x; } } } } // end class Block } // end class Deflator // ****************************************************************************** struct HuffmanCoding // Variable length coding. { public ushort Count; // Number of symbols. public byte [] Bits; // Number of bits used to encode a symbol ( code length ). public ushort [] Codes; // Huffman code for a symbol ( bit 0 is most significant ). public int [] Used; // Count of how many times a symbol is used in the block being encoded. private int Limit; // Limit on code length ( 15 or 7 for RFC 1951 ). private ushort [] Left, Right; // Tree storage. public HuffmanCoding( int limit, ushort symbols ) { Limit = limit; Count = symbols; Bits = new byte[ symbols ]; Codes = new ushort[ symbols ]; Used = new int[ symbols ]; Left = new ushort[ symbols ]; Right = new ushort[ symbols ]; } public int Total() { int result = 0; for ( int i = 0; i &lt; Count; i += 1 ) result += Used[i] * Bits[i]; return result; } public void ComputeCodes() // Compute Bits and Codes from Used. { // Tree nodes are encoded in a ulong using 16 bits for the id, 8 bits for the tree depth, 32 bits for Used. const int IdBits = 16, DepthBits = 8, UsedBits = 32; const uint IdMask = ( 1u &lt;&lt; IdBits ) - 1; const uint DepthOne = 1u &lt;&lt; IdBits; const uint DepthMask = ( ( 1u &lt;&lt; DepthBits ) - 1 ) &lt;&lt; IdBits; const ulong UsedMask = ( ( 1ul &lt;&lt; UsedBits ) - 1 ) &lt;&lt; ( IdBits + DepthBits ); // First compute the number of bits to encode each symbol (Bits). UlongHeap heap = new UlongHeap( Count ); for ( ushort i = 0; i &lt; Count; i += 1 ) { int used = Used[ i ]; if ( used &gt; 0 ) heap.Add( (ulong)used &lt;&lt; ( IdBits + DepthBits ) | i ); } heap.Make(); int nonZero = heap.Count; int maxBits = 0; if ( heap.Count == 1 ) { GetBits( unchecked( (ushort) heap.Remove() ), 1 ); maxBits = 1; } else if ( heap.Count &gt; 1 ) unchecked { ulong treeNode = Count; do // Keep pairing the lowest frequency TreeNodes. { ulong left = heap.Remove(); Left[ treeNode - Count ] = (ushort) left; ulong right = heap.Remove(); Right[ treeNode - Count ] = (ushort) right; // Extract depth of left and right nodes ( still shifted though ). uint depthLeft = (uint)left &amp; DepthMask, depthRight = (uint)right &amp; DepthMask; // New node depth is 1 + larger of depthLeft and depthRight. uint depth = ( depthLeft &gt; depthRight ? depthLeft : depthRight ) + DepthOne; heap.Insert( ( left + right ) &amp; UsedMask | depth | treeNode ); treeNode += 1; } while ( heap.Count &gt; 1 ); uint root = (uint) heap.Remove() &amp; ( DepthMask | IdMask ); maxBits = (int)( root &gt;&gt; IdBits ); if ( maxBits &lt;= Limit ) GetBits( (ushort)root, 0 ); else { maxBits = Limit; PackageMerge( nonZero ); } } // Computation of code lengths (Bits) is complete. // Now compute Codes, code below is from RFC 1951 page 7. int [] bl_count = new int[ maxBits + 1 ]; for ( int i = 0; i &lt; Count; i += 1 ) bl_count[ Bits[ i ] ] += 1; int [] next_code = new int[ maxBits + 1 ]; int code = 0; bl_count[ 0 ] = 0; for ( int i = 0; i &lt; maxBits; i += 1 ) { code = ( code + bl_count[ i ] ) &lt;&lt; 1; next_code[ i + 1 ] = code; } for ( int i = 0; i &lt; Count; i += 1 ) { int length = Bits[ i ]; if ( length != 0 ) { Codes[ i ] = (ushort) Reverse( next_code[ length ], length ); next_code[ length ] += 1; } } // Reduce Count if there are unused trailing symbols. while ( Count &gt; 0 &amp;&amp; Bits[ Count - 1 ] == 0 ) Count -= 1; } private void GetBits( ushort treeNode, int length ) { if ( treeNode &lt; Count ) // treeNode is a leaf. { Bits[ treeNode ] = (byte)length; } else { treeNode -= Count; length += 1; GetBits( Left[ treeNode ], length ); GetBits( Right[ treeNode ], length ); } } private static int Reverse( int x, int bits ) // Reverse a string of bits ( ready to be output as Huffman code ). { int result = 0; for ( int i = 0; i &lt; bits; i += 1 ) { result &lt;&lt;= 1; result |= x &amp; 1; x &gt;&gt;= 1; } return result; } // PackageMerge is used if the Limit is exceeded. // The result is technically not a Huffman code in this case. // See https://en.wikipedia.org/wiki/Package-merge_algorithm for a description of the algorithm. private void PackageMerge( int usedNonZero ) { // Tree nodes are encoded in a ulong using 16 bits for the id, 32 bits for Used. const int IdBits = 16, UsedBits = 32; const ulong UsedMask = ( ( 1ul &lt;&lt; UsedBits ) - 1 ) &lt;&lt; IdBits; Left = new ushort[ Count * Limit ]; Right = new ushort[ Count * Limit ]; // First create the leaf nodes and sort. ulong [] sorted = new ulong[ usedNonZero ]; for ( uint i = 0, j = 0; i &lt; Count; i += 1 ) { if ( Used[ i ] != 0 ) { sorted[ j++ ] = (ulong)Used[ i ] &lt;&lt; IdBits | i; } } System.Array.Sort( sorted ); // Sort is complete. // List class is from System.Collections.Generic. Generic.List&lt;ulong&gt; merged = new Generic.List&lt;ulong&gt;( Count ), next = new Generic.List&lt;ulong&gt;( Count ); uint package = (uint) Count; // Allocator for package ids. for ( int i = 0; i &lt; Limit; i += 1 ) { int j = 0, k = 0; // Indexes into the lists being merged. next.Clear(); for ( int total = ( sorted.Length + merged.Count ) / 2; total &gt; 0; total -= 1 ) { ulong left, right; // The tree nodes to be packaged. if ( k &lt; merged.Count ) { left = merged[ k ]; if ( j &lt; sorted.Length ) { ulong sj = sorted[ j ]; if ( left &lt; sj ) k += 1; else { left = sj; j += 1; } } else k += 1; } else left = sorted[ j++ ]; if ( k &lt; merged.Count ) { right = merged[ k ]; if ( j &lt; sorted.Length ) { ulong sj = sorted[ j ]; if ( right &lt; sj ) k += 1; else { right = sj; j += 1; } } else k += 1; } else right = sorted[ j++ ]; Left[ package ] = unchecked( (ushort) left ); Right[ package ] = unchecked( (ushort) right ); next.Add( ( left + right ) &amp; UsedMask | package ); package += 1; } // Swap merged and next. Generic.List&lt;ulong&gt; tmp = merged; merged = next; next = tmp; } for ( int i = 0; i &lt; merged.Count; i += 1 ) MergeGetBits( unchecked( (ushort) merged[i] ) ); } private void MergeGetBits( ushort node ) { if ( node &lt; Count ) Bits[ node ] += 1; else { MergeGetBits( Left[ node ] ); MergeGetBits( Right[ node ] ); } } } // end struct HuffmanCoding // ****************************************************************************** struct UlongHeap // An array organised so the smallest element can be efficiently removed. { public int Count { get{ return _Count; } } private int _Count; private ulong [] Array; public UlongHeap ( int capacity ) { _Count = 0; Array = new ulong[ capacity ]; } public void Insert( ulong e ) { int j = _Count++; while ( j &gt; 0 ) { int p = ( j - 1 ) &gt;&gt; 1; // Index of parent. ulong pe = Array[ p ]; if ( e &gt;= pe ) break; Array[ j ] = pe; // Demote parent. j = p; } Array[ j ] = e; } public ulong Remove() // Returns the smallest element. { ulong result = Array[ 0 ]; _Count -= 1; ulong e = Array[ _Count ]; int j = 0; while ( true ) { int c = j + j + 1; if ( c &gt;= _Count ) break; ulong ce = Array[ c ]; if ( c + 1 &lt; _Count ) { ulong ce2 = Array[ c + 1 ]; if ( ce2 &lt; ce ) { c += 1; ce = ce2; } } if ( ce &gt;= e ) break; Array[ j ] = ce; j = c; } Array[ j ] = e; return result; } // Add and Make allow the heap to be initialised faster ( in theory at least ). public void Add( ulong e ) { Array[ _Count++ ] = e; } /* Diagram showing numbering of tree elements. 0 1 2 3 4 5 6 */ public void Make() { // Initialise the heap by making every parent less than both it's children. int p = ( _Count - 2 ) / 2; // parent of last element. while ( p &gt;= 0 ) { // Bubble element at p down. int j = p; ulong e = Array[ j ]; while ( true ) { int c = j + j + 1; if ( c &gt;= _Count ) break; ulong ce = Array[ c ]; if ( c + 1 &lt; _Count ) { ulong ce2 = Array[ c + 1 ]; if ( ce2 &lt; ce ) { c += 1; ce = ce2; } } if ( ce &gt;= e ) break; Array[ j ] = ce; j = c; } Array[ j ] = e; p -= 1; } } } // end struct UlongHeap // ****************************************************************************** abstract class OutBitStream { public void WriteBits( int n, uword value ) // Write first n bits of value to stream, least significant bit is written first. // Unused bits of value must be zero, i.e. value must be in range 0 .. 2^n-1. { if ( n + BitsInWord &gt;= WordCapacity ) { Save( value &lt;&lt; BitsInWord | Word ); int space = WordCapacity - BitsInWord; value &gt;&gt;= space; n -= space; Word = 0; BitsInWord = 0; } Word |= value &lt;&lt; BitsInWord; BitsInWord += n; } public void Pad( int n ) // Pad with zero bits to n bit boundary where n is power of 2 in range 1,2,4..64, typically n=8. { int w = BitsInWord % n; if ( w &gt; 0 ) WriteBits( n - w, 0 ); } public abstract void Save( uword word ); protected const int WordCapacity = sizeof(uword) * 8; // Number of bits that can be stored in Word protected uword Word; // Bits are first stored in Word, when full, Word is saved. protected int BitsInWord; // Number of bits currently stored in Word. } // ****************************************************************************** class MemoryBitStream : OutBitStream { // An implementation of OutBitStream where the bits are stored in memory. // The storage is a linked list of Chunks. // ByteSize returns the current size in bytes. // CopyTo copies the contents to a Stream. // ToArray returns the contents as an array of bytes. public int ByteSize() { return CompleteChunks * Chunk.Capacity + BytesInCurrentChunk + ( BitsInWord + 7 ) / 8; } public void CopyTo( System.IO.Stream s ) { for ( Chunk c = FirstChunk; c != null; c = c.Next ) { int n = ( c == CurrentChunk ) ? BytesInCurrentChunk : Chunk.Capacity; s.Write( c.Bytes, 0, n ); } int biw = BitsInWord; uword word = Word; while ( biw &gt; 0 ) { s.WriteByte( unchecked( (byte) word ) ); word &gt;&gt;= 8; biw -= 8; } } public byte [] ToArray() { byte [] result = new byte[ ByteSize() ]; int i = 0; for ( Chunk c = FirstChunk; c != null; c = c.Next ) { int n = ( c == CurrentChunk ) ? BytesInCurrentChunk : Chunk.Capacity; System.Array.Copy( c.Bytes, 0, result, i, n ); i += n; } int biw = BitsInWord; uword word = Word; while ( biw &gt; 0 ) { result[ i++ ] = unchecked( (byte) word ); word &gt;&gt;= 8; biw -= 8; } return result; } public MemoryBitStream() { FirstChunk = new Chunk(); CurrentChunk = FirstChunk; } public override void Save( uword w ) { if ( BytesInCurrentChunk == Chunk.Capacity ) { Chunk nc = new Chunk(); CurrentChunk.Next = nc; CurrentChunk = nc; CompleteChunks += 1; BytesInCurrentChunk = 0; } int i = BytesInCurrentChunk; byte [] bytes = CurrentChunk.Bytes; unchecked { #if x32 bytes[ i++ ] = (byte) w; w &gt;&gt;= 8; bytes[ i++ ] = (byte) w; w &gt;&gt;= 8; bytes[ i++ ] = (byte) w; w &gt;&gt;= 8; bytes[ i++ ] = (byte) w; #else bytes[ i++ ] = (byte) w; w &gt;&gt;= 8; bytes[ i++ ] = (byte) w; w &gt;&gt;= 8; bytes[ i++ ] = (byte) w; w &gt;&gt;= 8; bytes[ i++ ] = (byte) w; w &gt;&gt;= 8; bytes[ i++ ] = (byte) w; w &gt;&gt;= 8; bytes[ i++ ] = (byte) w; w &gt;&gt;= 8; bytes[ i++ ] = (byte) w; w &gt;&gt;= 8; bytes[ i++ ] = (byte) w; #endif } BytesInCurrentChunk = i; } protected class Chunk { public const int Capacity = 0x800; public byte [] Bytes = new byte[ Capacity ]; public Chunk Next; } protected int BytesInCurrentChunk; protected int CompleteChunks; protected Chunk FirstChunk, CurrentChunk; } // end class MemoryBitStream } // end namespace Pdf </code></pre>
[]
[ { "body": "<p>In SaveMatch, I think that I need an extra <code>MemoryBarrier</code> in this code:</p>\n\n<pre><code>Thread.MemoryBarrier();\nBufferWrite = i;\nposition += length;\nBuffered = position;\n</code></pre>\n\n<p>If <code>BufferWrite = i</code> is re-ordered after <code>Buffered = position</code> the code doing the Huffman compression might not see the match ( or worse, might not see it when computing the codes, but see it when the block is written, and not have a code available to encode the match ). So I have changed this to:</p>\n\n<pre><code>Thread.MemoryBarrier();\nBufferWrite = i;\nposition += length;\nThread.MemoryBarrier();\nBuffered = position;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T07:10:06.540", "Id": "212670", "ParentId": "212653", "Score": "1" } }, { "body": "<p>Nothing too exciting to say, but having spent some time looking through the code, thought I might as well post something:</p>\n\n<h1>Code Separation</h1>\n\n<p>I'd be compelled to separate the LZ77 FindMatches logic from the other logic; I would want as little interface between these as possible (e.g. <code>HashTable</code> should not be available to the other thread).</p>\n\n<p>I'd also want to pull all of the communication between the 2 threads into a separate component, so that this logical interface is as clear as possible. As someone looking at your code for the first time, this logical interface is difficult to discern (without tooling), and that makes it very hard to try to verify the threading code.</p>\n\n<h1>Threading</h1>\n\n<p>It's generally advised that you don't lock on <code>this</code>, since someone else might do so and ruin your day (especially given you <code>Deflator</code> constructor and <code>Go()</code> methods are public); better to create a dedicated private lock-object so there can be no interference and it's clearer what the lock's job is (<code>this</code> alone is brittle, changing meaning if moved to a method in a different class).</p>\n\n<p>I think this code in <code>SaveMatch</code> can end up blocking longer than necessary when the buffer is filled... though it's probably never going to happen.</p>\n\n<pre><code>while ( i == BufferRead )\nlock ( this )\n{\n BufferFull = true;\n if ( InputWait ) Monitor.Pulse( this );\n Monitor.Wait( this );\n BufferFull = false;\n}\n</code></pre>\n\n<p>Sequence:</p>\n\n<ol>\n<li>On the match-finding thread (A) <code>BufferRead</code> is read such that it appears the buffer is full, then the thread is swapped out...</li>\n<li>The other thread (B) then resets <code>BufferRead</code> to something else in <code>PutCodes</code>, and manages to get out of <code>OutputBlock</code> before being swapped out</li>\n<li>The same thread (B) then checks <code>BufferFull</code> and finds it <code>false</code>. This thread is swapped out</li>\n<li>Thread (A) now enters the while-loop (having already read <code>BufferRead</code>), takes the lock, sets <code>BufferFull = true</code>, pulses, and waits</li>\n<li>Thread (B) in <code>WaitForInput</code> observes <code>BufferFull == true</code> and doesn't pulse the monitor again until it leaves <code>OutputBlock</code> - which might take a short while if decides to read a large dynamic block - during which time Thread (A) is stalled</li>\n</ol>\n\n<p>Checking <code>BufferRead</code> inside the lock would prevent any such possibility by ensuring a fresh read before waiting.</p>\n\n<p>If I'm understanding the checks against <code>BufferWrite</code> correctly, that first <code>MemoyBarrier</code> in <code>SaveMatch</code> has a somewhat unclear job in keeping <code>BufferWrite != BufferRead</code>. (It's probably redundant because of the lock, but I'd keep it for clarity and honour it with a comment explaining why it is necessary to defer assigning <code>BufferWrite</code> if it is)</p>\n\n<h1>Boring Misc</h1>\n\n<ul>\n<li><p>You might consider the generic overload of <code>QueueUserWorkItem</code>, just to remove the cast in <code>FindMatchesStart</code>.</p></li>\n<li><p>You are slightly inconsistent with your spacing before <code>(</code>, which makes it harder to quickly navigate the code (two instances of <code>lock(</code>). There are also a couple of lopsided things like <code>(uint)(length-MatchOff[ mc ] )</code></p></li>\n<li><p>The <code>HuffmanCoding</code>s in <code>Block</code> are missing an access modifier; do they want to be <code>private readonly</code>? <code>BufferStart</code> and <code>BufferEnd</code> also look like they want to be <code>readonly</code> to go along with <code>Start</code> and <code>End</code>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T16:48:38.577", "Id": "411440", "Score": "0", "body": "I don't think that thread (A) gets stalled for long, after PutCodes increments BufferRead, OutputBlock exits immediately ( it only outputs a single block once it has decided on the block size ), and then thread (A) gets the required Pulse from the while ( !OutputBlock() ) loop in Deflator.Go ?\n\nOn misc point (1) am not quite sure what you are referring to, it would be nice to get rid of the rather ugly \"Object\" method, but I don't know exactly how.\n\nOther points I agree, thanks for the review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T16:55:18.403", "Id": "411442", "Score": "0", "body": "@GeorgeBarwood I could be barking up the wrong tree, but the idea is that if `BufferRead` is set and it (doesn't) Pulse in the while loop between `BufferRead` being read and `Wait` in `SaveMatch`, then it will 'miss' the Pulse and have to wait for `OutputBlock` to exit again; checking `BufferRead` again inside the lock in `SaveMatch` precludes this (no doubt very unlikely and probably not significant) possibility. Misc point (1), I mean something like `ThreadPool.QueueUserWorkItem<Deflator>(FindMatchesStart, this, false );` with new signature `FindMatchesStart(Defalator d)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T19:21:45.423", "Id": "411455", "Score": "0", "body": "Ah, I think I see what you mean now. I need to test for `i == BufferRead` again inside the lock as well.\n\nOn QueueUserWorkItem the generic version doesn't seem to be in my version on .Net, and I am not sure of it's official status." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T19:37:32.317", "Id": "411458", "Score": "1", "body": "@GeorgeBarwood ah, looks like it is exclusive to .NET Core." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T21:52:54.870", "Id": "411537", "Score": "1", "body": "I have now made a `matcher` struct which addresses the Code Separation it handles the matching and also all the threading logic. Revised code is at https://github.com/georgebarwood/pdf/blob/master/Deflator.cs" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T22:34:16.237", "Id": "411540", "Score": "0", "body": "@GeorgeBarwood oh, that's much better that what I came up with... good idea putting `WaitForInput` in the struct; I was trying to keep that outside and kept getting myself in a tangle!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T13:48:10.327", "Id": "212689", "ParentId": "212653", "Score": "3" } } ]
{ "AcceptedAnswerId": "212689", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T20:57:47.997", "Id": "212653", "Score": "5", "Tags": [ "c#", "multithreading", "concurrency", "compression" ], "Title": "Using two threads to increase RFC1951 Deflate compression performance" }
212653
<p>The first function makes 2 players</p> <pre><code>const Player = (name,mark) =&gt; { return {name, mark} } let player1 = Player('Player 1', '&lt;div&gt;X&lt;/div&gt;'); let player2 = Player('Player 2', '&lt;div&gt;O&lt;/div&gt;'); </code></pre> <p>The rest of the code which runs the game</p> <pre><code>const gameBoard = (() =&gt; { board = [["","",""],["","",""],["","",""]]; let whichPlayer = getCurrentPlayer(); const AddEventListeners = (() =&gt; { $('.square').click(function(event) { if(win == false &amp;&amp; this.innerHTML == ''){ console.log(this) let a = addToBoard(whichPlayer()).bind(this); a(this.id)} }) $('.restart').click(function(e) { board = [["","",""],["","",""],["","",""]]; $('.square').empty() btnDiv.style.display = "none"; $('.winnermsg').hide(); win = false; }) })(); function getCurrentPlayer(){ let currentPlayer = player1 function getPlayer() { if(currentPlayer === player1){ currentPlayer = player2 crntPlayer = player1 return player1 }else{ currentPlayer = player1 crntPlayer = player2 return player2 } } return getPlayer; } function addToBoard(currentPlayer) { return function(square){ this.innerHTML = currentPlayer.mark let coords = square.split('') board[coords[0]][coords[1]] = currentPlayer.mark checkWin() } } function declareWinner(tie = false){ win = true; $('.winnermsg').show(); if(tie){ $('.winnermsg').html(`&lt;p&gt;Tie game, try again&lt;/p&gt;`); }else{ $('.winnermsg').html(`&lt;p&gt;Congratulations, ${crntPlayer.name} you have won&lt;/p&gt;`); } if (crntPlayer == player1){whichPlayer();} btnDiv.style.display = "grid" } function checkWin(){ //check horizontal for(let i=0;i&lt;board.length;i++){ array=[] if(board[i].every(x =&gt; x == crntPlayer.mark )){ declareWinner() } //check vertical for(let j=0;j&lt;board[i].length;j++){ array.push(board[j][i]) if(array.every(x=&gt;x == crntPlayer.mark &amp;&amp; array.length == 3)){ declareWinner() } } } //check diags newArray=[] newArray.push(board[0][0],board[1][1],board[2][2]) if(newArray.every(x =&gt; x == crntPlayer.mark)){ declareWinner() } newArray=[] newArray.push(board[0][2],board[1][1],board[2][0]) if(newArray.every(x =&gt; x == crntPlayer.mark)){ declareWinner() } //check tie newArray=board.reduce((a,b) =&gt; a.concat(b)) if(!newArray.includes('')){declareWinner('tie')} } })(); </code></pre> <p>So I just add event listeners to each div and if it's empty it changes the innerHTML to the player's mark and adds that mark to the board array and then checks if there's a winner.</p> <p>I feel like it's not very well organized but i'm not sure how it would best be improved.</p>
[]
[ { "body": "<p>Just a few pointers, some of which are my personal preference!</p>\n\n<ul>\n<li>Since you use modern concepts like arrow functions, const, and shorthand objects, you might as well replace jQuery <code>$(\".square\")</code> with <code>document.querySelectorAll(\".square\")</code></li>\n<li>Passing a div as an argument is not a good idea. I would keep all visualisation of the game in one separate function, for example: <code>function drawBoard()</code>. This function does all the DOM manipulation, and the DOM elements or jQuery functions should not be mentioned anywhere else in your code.</li>\n<li>I would use one game state array, and the event handlers should alter that game state array directly. If square 1 is clicked by player one, the state array would become <code>[1,0,0,0,0,0,0,0,0]</code>, and after the game state has updated, you call <code>drawBoard()</code> which draws the X and O visuals in the DOM.</li>\n<li>You can use this state array in your checkWin function too, instead of using so many temporary arrays! If you use numbers you can even see who won just by adding the numbers.</li>\n<li>You use a lot of temporary variables. I've added a suggestion to switch players without using those.</li>\n<li>Don't nest so many functions in each other, don't call them implicitly by sometimes adding <code>()</code> at the end, and other times not. It's hard to reason about.</li>\n<li>Arrow functions don't have their own scope, but sometimes you DO need a scope, for example in your gameboard class.</li>\n</ul>\n\n<p>Below are just a few sketches to rewrite the code, I realise this is far from complete but it might give you some ideas:</p>\n\n<pre><code>function Player(name, mark, id){\n this.name = name\n this.mark = mark\n this.id = id\n}\n\nfunction GameBoard(){\n let state = [0,0,0,0,0,0,0,0,0]\n let player1 = new Player(\"Mark\",\"X\", 1)\n let player2 = new Player(\"Joe\", \"O\", 2)\n let currentPlayer = player1\n\n this.initHandlers = function(){\n let fields = document.querySelectorAll(\".field\")\n for(let f of fields){\n f.addEventListener(\"click\", (e)=&gt; this.updateState(e))\n }\n }\n\n this.updateState = function(e){\n console.log(\"id of the clicked tile is \" + e.target.id)\n let id = parseInt(e.target.id)\n state[id] = currentPlayer.id\n this.drawBoard()\n this.checkWin()\n currentPlayer = this.switchPlayers()\n }\n\n\n this.switchPlayer = function(){\n return (currentPlayer == player1) ? player2 : player1\n }\n\n this.drawBoard = function(){\n // all DOM manipulation here\n }\n\n this.checkWin = function(){\n if(state[0] + state[3] + state[6] == 3) console.log(\"player one wins!\")\n }\n}\n\nlet board = new GameBoard()\nboard.initHandlers()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-04T04:27:28.150", "Id": "212821", "ParentId": "212658", "Score": "1" } } ]
{ "AcceptedAnswerId": "212821", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T21:38:33.740", "Id": "212658", "Score": "0", "Tags": [ "javascript", "jquery", "tic-tac-toe", "dom" ], "Title": "JavaScript Tic-Tac-Toe" }
212658
<p>My task was to create a Python script and connect to various TLS sites and grab the expiry dates. I've done this with openssl and ssl modules just fine.</p> <p>In my mind I was wanting to create a web page as a dashboard.</p> <p>I've done that.</p> <p>It's as simple as it gets I think (which I am happy with):</p> <p><a href="https://i.stack.imgur.com/rx7PD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rx7PD.png" alt="enter image description here"></a></p> <p>But I ended up doing a for loop of the dictionary I stored the values for expiration, url, and status.</p> <p>I.E</p> <pre><code>with open(htmlfile,'a') as fh: for urlandport,data in urldict.items(): url,tcpport = urlandport msg,status = data #print(url) if status == 'OK': delta = data[0] - now days_left = str(abs(delta.days)) color = 'green' if int(days_left) &gt; 400 \ else 'orange' if int(days_left) &lt; 100 \ else 'red' sclr = 'green' else: days_left = 'NA' expiration = 'NA' color = 'blue' sclr = 'blue' msg,status = status,msg #Swap dashboard order on failure fh.write( "&lt;tr&gt;" + "&lt;td&gt;" + url + " " + str(tcpport) + "&lt;/td&gt;" + \ "&lt;td&gt;&lt;font color="+color+"&gt;"+days_left+"&lt;/font&gt;"+"&lt;/td&gt;" + \ "&lt;td&gt;&lt;font color="+color+"&gt;"+ str(msg)+"&lt;/font&gt;"+"&lt;/td&gt;" + \ "&lt;td&gt;&lt;font color="+sclr+"&gt;"+str(status)+"&lt;/font&gt;"+"&lt;/td&gt;"+"&lt;/tr&gt;" ) </code></pre> <p>In my mind this does not seem very modern or flexible to proceed in manually cobbling HTML like this. It works. But I am wondering if I should invest in learning something more suitable for scalability.</p> <p>I was also also to separate out the certs into 4 different tables: soon to expire, OK for now, connect failure and too old to bother and display then in a particular order for the user.</p> <p>Hence, I ended up just creating 4 lists and appending to them so I could loop over each as I chose.</p> <p>It just feels like I wrote some eye searing python to cobble something together...I am not even sure if a "Web Framework" would help or frankly why...I've looked into some of them but it's not sinking in.</p> <p>Any suggestions? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T00:28:13.390", "Id": "411365", "Score": "0", "body": "It's counterintuitive to me that red indicates certificates with more than three months remaining. I would expect red to indicate imminent expiration." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T00:30:37.527", "Id": "411366", "Score": "0", "body": "Good catch....that was just an example page. The data is meaning less." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T00:34:00.007", "Id": "411367", "Score": "0", "body": "What do you mean by \"just an example page\"? On Code Review, we expect you to post real code from your project to review, and the code should be working correctly as intended." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T01:47:08.333", "Id": "411370", "Score": "0", "body": "It's test data in the same spirit that I don't work for example.com. The code is mine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T08:48:49.807", "Id": "411378", "Score": "1", "body": "Can you show how you did that testing? It helps reviewers if they can see how the function is called (e.g. what's in `urldict`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T17:06:30.057", "Id": "411443", "Score": "0", "body": "@Toby - happy to share more. In short was a dictionary with a tuple as key and value as well: urldict[(url,tcpport)] = (msg,status) msg is the expire date and status is whether the connection was ok or failed" } ]
[ { "body": "<h1>Usability</h1>\n<p>The two most common forms of colour-blindness are red-green and green-blue. Throughout this design, you're using green as an indicator colour and expecting users to be able to distinguish it from red or blue.</p>\n<p>Instead of baking the specific colours into the code, I think you should use <strong>classes</strong>, such as</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;tr class=&quot;no-data&quot;&gt;&lt;td&gt;....&lt;/td&gt;&lt;/tr&gt;\n&lt;tr class=&quot;expiring&quot;&gt;&lt;td&gt;....&lt;/td&gt;&lt;/tr&gt;\n</code></pre>\n<p>Then we can provide a stylesheet (or choice of stylesheet, if the UA supports it)</p>\n<pre class=\"lang-css prettyprint-override\"><code>tr.no-data { background: white; color: blue; } /* FIXME - green/blue blindness */\ntr.expiring { background: white; color: orange; } /* FIXME - red/green blindness */\n</code></pre>\n<p>Note that whenever we specify foreground colour in CSS, we should also specify a background <em>with the same selector</em>, and vice versa. This is so that other rules in the cascade (including UA rules) are not partially overridden. That's how bad sites end up with black-on-black or other unreadable combinations.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T08:59:41.580", "Id": "212675", "ParentId": "212664", "Score": "1" } }, { "body": "<blockquote>\n <p>It just feels like I wrote some eye searing python to cobble something together...I am not even sure if a \"Web Framework\" would help or frankly why...I've looked into some of them but it's not sinking in.</p>\n</blockquote>\n\n<p>I think it would definitely be better then what you have currently</p>\n\n<p>I can recommend <a href=\"http://flask.pocoo.org/docs/1.0/quickstart/\" rel=\"nofollow noreferrer\">flask</a>, a small web microframework. </p>\n\n<p>Pretty easy to use and has plenty of features, it will handle serving the page, making nicely formatted html pages, handling routes.</p>\n\n<p>If you want some pretty tables you could even use <a href=\"https://pypi.org/project/Flask-Table/\" rel=\"nofollow noreferrer\">Flask-Table</a></p>\n\n<p>But something simple as this should even work,</p>\n\n<p><em>app.py</em></p>\n\n<pre><code>from flask import Flask, render_template\napp = Flask(__name__)\n\n@app.route('/')\ndef ssl_status():\n ssl_connections = [\n [\"url.url\", 165, \"some-date-2019\", \"OK\"]\n ]\n return render_template('ssl_status.html', ssl_connections=ssl_connections)\n\nif __name__ == '__main__':\n app.run()\n</code></pre>\n\n<p><em>ssl_status.html</em></p>\n\n<pre><code>&lt;!doctype html&gt;\n&lt;title&gt;SSL Status page&lt;/title&gt;\n&lt;table&gt;\n {% for row in ssl_connections %}\n &lt;tr&gt;\n {% for item in row %}\n &lt;td&gt;{{ item }}&lt;/td&gt;\n {% endfor %}\n &lt;/tr&gt;\n {% endfor %}\n&lt;/table&gt;\n</code></pre>\n\n<p>You'd need some <code>.css</code> probably to make the colors work, and some other stuff to make it look the same as your example.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T15:19:33.843", "Id": "411416", "Score": "0", "body": "This pretty much looks exactly what I want. Surely it's better than my current setup!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T09:59:09.607", "Id": "212683", "ParentId": "212664", "Score": "2" } } ]
{ "AcceptedAnswerId": "212683", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T00:00:27.587", "Id": "212664", "Score": "2", "Tags": [ "python", "python-3.x", "html" ], "Title": "Python web page to display SSL certificate status" }
212664
<p>My objective is computing a table of primes up to n, where n is a natural number passed as an argument to the <code>prime_table</code> function.</p> <p>Here is <em>src/lib.rs</em>:</p> <pre><code>#![feature(vec_remove_item)] // Return a vector containing all the products between i and natural numbers beyond 2. // The vector only includes products which are not greater than the maximum specified. fn get_multiples(i: u32, max: u32) -&gt; Vec&lt;u32&gt; { let mut results = Vec::new(); let max_multiplier = max / i; for number in 2..=max_multiplier { results.push(i * number); } results } // Return a vector containg all the primes up to n. pub fn prime_table(n: u32) -&gt; Vec&lt;u32&gt; { let root_of_n = (n as f64).sqrt() as u32; let mut table: Vec&lt;u32&gt; = (2..=n).collect(); for i in 2..=root_of_n { if !table.contains(&amp;i) { continue; } for multiple in get_multiples(i, n).iter() { table.remove_item(&amp;multiple); } } table } </code></pre> <p>Something I'd like but I'm not sure is possible would be changing get_multiples to return an iterator of the <code>results</code> vector instead of the vector itself, but I'm not sure how. If there is a way, I suspect it necessitates lifetimes, something I haven't grasped yet</p> <p>My main concern is avoiding unnecessarily allocating memory.</p>
[]
[ { "body": "<p>Returning an iterator is fairly easy with <code>impl</code>. Here's how you can do it. Note that you need to use <code>move</code> with the closure so that it takes ownership of <code>i</code>. Since <code>u32</code> can be copied, this just copies it instead of taking a reference, which lets you avoid dealing with lifetimes on the return type.</p>\n\n<pre><code>fn get_multiples(i: u32, max: u32) -&gt; impl Iterator&lt;Item = u32&gt; {\n let max_multiplier = max / i;\n (2..=max_multiplier).map(move |n| i * n)\n}\n</code></pre>\n\n<p>As another note, I have a recommendation for improving performance on your sieve. Currently, every time you call <code>remove_item</code>, you have to search all the way through the vector, remove the item, then shift all items after it forward by one. This is awful for performance. Instead, you could have a <code>Vec&lt;bool&gt;</code> and simply flip the value based on index rather than remove it. Then when you're done sieving, you can go through this vector along with indices and create a <code>Vec&lt;u32&gt;</code> to return.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T20:12:12.663", "Id": "411459", "Score": "0", "body": "Remarkable that you suggest a small change that duplicates the hand process in use since we discovered the pesky things. Big list of numbers with possible 'Xs—wonder if Eratosthenes used sand or wax before scribing it all down? Reasonable code, great suggestion, I'd say well done…" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T13:10:39.777", "Id": "411507", "Score": "0", "body": "Now that I think about it, I could return the prime table as an iterator instead, the return expression would be mix of map and filter" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T19:24:16.463", "Id": "212710", "ParentId": "212665", "Score": "1" } } ]
{ "AcceptedAnswerId": "212710", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T00:18:30.697", "Id": "212665", "Score": "0", "Tags": [ "performance", "rust", "sieve-of-eratosthenes" ], "Title": "Computing a prime table in Rust" }
212665
<p>After learning the concept of steganography, I've decided to code an application for it in PHP out of all languages, using the Least Significant Bit technique. </p> <p>A pixel of a colored image generally has 3 channels, one for Red, one for Green and one for Blue. 8 bits are usually used to encode the value for each channel, which gives a range of 0 to 255 in decimal. The idea is to put the bits of my payload into the least significant bits of the color channel values.</p> <p>Theoretically, you could hide text or any type of file in an image as long as that image is large enough. The length of that text or file in bits must be smaller than the <code>width * height * 3</code>.</p> <p>From a visual perspective, the difference is not noticeable to the naked eye, which is why "steganalysis" tools are used to detect it.</p> <p>What I'm looking for is ways to</p> <ul> <li>maximize the performance </li> <li>improve the logic</li> </ul> <p>Converting the contents of my payload to binary form (inside a string) each time and processing all those 1's and 0's is probably a lot of work, or so I've noticed. The code that follows hides a simple, short text, but I've tried hiding the contents of an entire image inside another image and I either screwed up, or that really takes a long time since I set my max execution limit to 5 minutes and it exceeded even that. Maybe I'm just used to things running fast in this day and age.</p> <p><strong>functions.php</strong></p> <pre><code>&lt;?php function toBinary(string $message) { $result = ''; for($i = 0; $i &lt; strlen($message); $i++) { $result .= str_pad(decbin(ord($message[$i])), 8, "0", STR_PAD_LEFT); } return $result; } ?&gt; </code></pre> <p><strong>encode.php</strong></p> <pre><code>&lt;?php include('functions.php'); // Number of bytes in an integer. $INTEGER_BYTES = 4; $BYTE_BITS = 8; $message = "Hello from outer space, it's your commander speaking."; $binaryMessage = toBinary($message); // The number of bits contained in the message, aka the size of the payload as an integer. $messageLength = strlen($binaryMessage); // Convert the length to binary as well and make sure to pad it with 32 0's. $binaryMessageLength = str_pad(decbin($messageLength), $INTEGER_BYTES * $BYTE_BITS, "0", STR_PAD_LEFT); // The payload will incorporate the length and the message. $payload = $binaryMessageLength.$binaryMessage; $src = 'wilderness.jpg'; $image = imagecreatefromjpeg($src); $size = getimagesize($src); $width = $size[0]; $height = $size[1]; function encodePayload(string $payload, $image, $width, $height) { $payloadLength = strlen($payload); // We are able to store 3 bits per pixel (1 LSB for each color channel) times the width, times the height. if($payloadLength &gt; $width * $height * 3) { echo "Image not big enough to hold data."; return false; } $bitIndex = 0; for($y = 0; $y &lt; $height; $y++) { for($x = 0; $x &lt; $width; $x++) { $rgb = imagecolorat($image, $x, $y); // Each color channel's value is extracted from the original integer. $r = ($rgb &gt;&gt; 16) &amp; 0xFF; $g = ($rgb &gt;&gt; 8) &amp; 0xFF; $b = $rgb &amp; 0xFF; // LSB's are cleared by ANDing with 0xFE and filled by ORing with the current payload bit, as long as the payload length isn't hit. $r = ($bitIndex &lt; $payloadLength) ? (($r &amp; 0xFE) | $payload[$bitIndex++]) : $r; $g = ($bitIndex &lt; $payloadLength) ? (($g &amp; 0xFE) | $payload[$bitIndex++]) : $g; $b = ($bitIndex &lt; $payloadLength) ? (($b &amp; 0xFE) | $payload[$bitIndex++]) : $b; $color = imagecolorallocate($image, $r, $g, $b); imagesetpixel($image, $x, $y, $color); if($bitIndex &gt;= $payloadLength) { return true; } } } } if(encodePayload($payload, $image, $width, $height)) { echo 'Payload delivered.'.'&lt;br&gt;'; } else { echo 'Something went wrong.'.'&lt;br&gt;'; } imagepng($image, 'encoded.png'); imagedestroy($image); ?&gt; </code></pre> <p><strong>decode.php</strong></p> <pre><code>&lt;?php $INTEGER_BITS = 32; $src = 'encoded.png'; $image = imagecreatefrompng($src); $size = getimagesize($src); $width = $size[0]; $height = $size[1]; // Returns the message length in bits as an integer. function decodeMessageLength($image, $width, $height) { // We need to process the first 32 LSB's of the image to retrieve the int. $numOfBits = 32; $bitIndex = 0; $binaryMessageLength = 0; for($y = 0; $y &lt; $height; $y++) { for($x = 0; $x &lt; $width; $x++) { $rgb = imagecolorat($image, $x, $y); // We extract each component's LSB by simply ANDing with 1. $r = ($rgb &gt;&gt; 16) &amp; 1; $g = ($rgb &gt;&gt; 8) &amp; 1; $b = $rgb &amp; 1; $binaryMessageLength = ($bitIndex++ &lt; $numOfBits) ? (($binaryMessageLength &lt;&lt; 1) | $r) : $binaryMessageLength; $binaryMessageLength = ($bitIndex++ &lt; $numOfBits) ? (($binaryMessageLength &lt;&lt; 1) | $g) : $binaryMessageLength; $binaryMessageLength = ($bitIndex++ &lt; $numOfBits) ? (($binaryMessageLength &lt;&lt; 1) | $b) : $binaryMessageLength; if($bitIndex &gt;= $numOfBits) { return $binaryMessageLength; } } } } function decodeBinaryMessage($image, $width, $height, $offset, $messageLength) { $offsetRemainder = $offset % 3; // We get 3 bits for each pixel, so the offset needs to be divided by 3. $offset /= 3; // Instead of looping through all the pixels, an offset is used for the starting indices. $line = $offset / $width; $col = $offset % $width; $binaryMessage = ''; $bitIndex = 0; for($y = $line; $y &lt; $height; $y++) { for($x = $col; $x &lt; $width; $x++) { $rgb = imagecolorat($image, $x, $y); // We extract each component's LSB by simply ANDing with 1. $r = ($rgb &gt;&gt; 16) &amp; 1; $g = ($rgb &gt;&gt; 8) &amp; 1; $b = $rgb &amp; 1; // Depending on the remainder, we will start with a different LSB. if($offsetRemainder == 1) { $binaryMessage .= $g; $binaryMessage .= $b; $offsetRemainder = 0; $bitIndex += 2; } else if($offsetRemainder == 2) { $binaryMessage .= $b; $offsetRemainder = 0; $bitIndex++; } else { // As long as the bit index is lower than the length of the message, concatenate each component's LSB to the message. $binaryMessage = ($bitIndex++ &lt; $messageLength) ? ($binaryMessage.$r) : $binaryMessage; $binaryMessage = ($bitIndex++ &lt; $messageLength) ? ($binaryMessage.$g) : $binaryMessage; $binaryMessage = ($bitIndex++ &lt; $messageLength) ? ($binaryMessage.$b) : $binaryMessage; if($bitIndex &gt;= $messageLength) { return $binaryMessage; } } } } } $decodedMessageLength = decodeMessageLength($image, $width, $height); $decodedBinaryMessage = decodeBinaryMessage($image, $width, $height, $INTEGER_BITS, $decodedMessageLength); $decodedMessage = implode(array_map('chr', array_map('bindec', str_split($decodedBinaryMessage, 8)))); echo 'The hidden message was:'.'&lt;br&gt;'.$decodedMessage.'&lt;br&gt;'; imagedestroy($image); ?&gt; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T01:23:37.467", "Id": "212666", "Score": "2", "Tags": [ "performance", "php", "image", "steganography" ], "Title": "LSB Image Steganography" }
212666
<p>I am pretty new to python, and I am writing this program to randomly generate sentences based on the n-gram language. It takes me very long to run this with the large input file I have, so it is very hard for me to check my work. I guess my problem is that, when I need 2 words as the history and based on the count of words appear after the 2 words, I generate the next word. And it takes very long and hard for me to do that for some reason.</p> <p>Any suggestion would be really helpful.</p> <pre><code>from __future__ import unicode_literals from io import open import string import re import operator import math import random corpus = '' begin_token = '&lt;s&gt;' # read in file and preprocessing the text def ReadFile(): sentences_all = [] translate_table = dict((ord(char), None) for char in string.punctuation) # open file and preprocessing with open('moviereview.txt', 'r', encoding ='iso-8859-15') as file: for line in file: line = line.translate(translate_table) # remove punctuations line = '&lt;s&gt; ' + line.rstrip('\n') + '&lt;/s&gt;' # add &lt;s&gt; and &lt;/s&gt; sentences_all += line sentences_all.append(" ") # append each line with space corpus = ''.join(sentences_all) corpus = re.sub(' +', ' ', corpus) # replace multiple spaces with single space return corpus # a dictionary of sentences in corpus and their count def N_Gram(corpus, n): corpus = ''.join(corpus) corpus = corpus.split(' ') output = {} for i in range(len(corpus)-n+1): g = ' '.join(corpus[i:i+n]) output.setdefault(g,0) output[g] += 1 return output def Uni_Generation(): corpus = ReadFile() uni = N_Gram(corpus, 1) print(uni) final = unsmoothed_totalcount(uni) print(final) sentence_list = [] # the list of 5 sentences for b in xrange(0,5): sentence = '&lt;s&gt; ' while sentence.split()[-1] != '&lt;/s&gt;': #last word is not &lt;/s&gt; sentence += return_random_selected_item(final, uni) if len(sentence.split()) &gt;= 15 : # if the length of sentence is more than 15 sentence += '&lt;/s&gt;' #print(sentence) sentence = post_processing(sentence) sentence_list.append(sentence) #print(sentence_list) def post_processing(x): x = x.split(" ") x.pop(0) x[0] = x[0].capitalize() # capitalize the first word if(x[-1] == ''): x.pop(-1) x.pop(-1) elif(x[-1] == '&lt;/s&gt;'): x.pop(-1) x = " ".join(x) x = '&lt;s&gt; ' + x + ' . &lt;/s&gt;' return x def unsmoothed_totalcount(n_gram_dict): #get total count of words keyList = list(n_gram_dict.keys()) final = 0 for i, x in enumerate(keyList): if i-1 &lt; 0: continue prev_word = keyList[i-1] prev_count = n_gram_dict[prev_word] # get the previous word count final += prev_count return final def find_next_word(N_Gram_dic, N_m1_Gram_dic, histo): #find all bigram start with histo, use the count and do everything corpus = ReadFile() n_count_dic = {} uni_dic= N_Gram(corpus, 1) final = 0 if histo.count(' ') == 0: # there is no history for it #print("get here") n_count_dic = uni_dic # elif histo == '&lt;s&gt; &lt;s&gt;' or histo == '&lt;s&gt; &lt;s&gt; &lt;s&gt;' or histo == '&lt;s&gt; &lt;s&gt; &lt;s&gt; &lt;s&gt;' or histo == '&lt;/s&gt; &lt;s&gt;': # n_count_dic = uni_dic # return find_next_word(uni_dic, uni_dic, '&lt;s&gt;') else: # keyList = N_Gram_dic.keys() # #print(keyList) # leng = histo.count(' ') + 1 # #print("histo is ") # #print(histo) # for a in keyList: # word = ' '.join(a.split()[:leng]) # #print("word is " + word) # if(histo == word): if histo in N_Gram_dic: n_count_dic[histo] = N_Gram_dic[histo] print("histo") print(n_count_dic[histo]) #print(n_count_dic) # for x in N_m1_Gram_dic: # if histo == x: # final = N_m1_Gram_dic[x] final = unsmoothed_totalcount(N_m1_Gram_dic) print("i did my best") print(final) return return_random_selected_item(final, n_count_dic) def return_random_selected_item(total_count, n_count_dict): #print("hello from the other side") #print(total_count) r = random.randint(1,total_count) for x in n_count_dict: f1 = n_count_dict[x] if r - f1 &lt;= 0 : # if the word choosen is not ending token print(x) return x.split()[-1] + ' ' if r &gt; f1: r = r - f1 #print(Uni_Generation()) def N_Gram_Generation(n): corpus = ReadFile() if n == 1: return Uni_Generation() uni_gram = N_Gram(corpus, 1) #bi_gram = N_Gram(corpus, 2) n_Gram = N_Gram(corpus, n) N_m1_Gram = N_Gram(corpus, n-1) #final = unsmoothed_totalcount(N_m1_Gram) sentence_list = [] # the list of 5 sentences for b in xrange(0,5): sentence = '&lt;s&gt; ' while len(sentence.split()) &lt;= n: word = find_next_word(uni_gram, uni_gram, sentence.split()[-1]) #print("word" + word) sentence += word #print("sentence" + sentence ) while sentence.split()[-1] != '&lt;/s&gt;': list = sentence.split() his= list[-(n-1):] histor = ' '.join(his) print("histor ") print(histor) next_word = find_next_word(n_Gram, N_m1_Gram, histor) print(next_word) if next_word != '&lt;/s&gt;': sentence += next_word if next_word == '&lt;/s&gt;': break if len(sentence.split()) &gt;= 15 : # if the length of sentence is more than 15 sentence += '&lt;/s&gt;' sentence = post_processing(sentence) print(sentence) sentence_list.append(sentence) return sentence_list print(N_Gram_Generation(3)) </code></pre> <p>Sorry if I was not clear or anything. I am really lack of sleep right now for this assignment. The readfile and postprocessing part is all good so I will not put that here. Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T05:10:01.547", "Id": "411372", "Score": "3", "body": "Please fix your indentation. The easiest way to post code is to paste it into the question editor, highlight it, and press Ctrl-K to mark it as a code block." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T15:17:08.747", "Id": "411414", "Score": "0", "body": "@Ludisposed It just read file in and preprocess the corpus. I add it in if that helps." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T15:25:33.563", "Id": "411418", "Score": "0", "body": "Thank you, CR works best, when all relevant code is in the question." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T04:07:52.100", "Id": "212668", "Score": "1", "Tags": [ "python", "beginner" ], "Title": "Python Program Generating N-Gram Language Model" }
212668
<p>This is likely my first useful piece of Rust code. Planning to crate-ify it. It works.</p> <pre class="lang-rust prettyprint-override"><code>#[macro_use] extern crate failure; use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use std::path::Path; use std::env::temp_dir; use mio::{Events, Poll}; use mio_httpc::{CallBuilder, Httpc, HttpcCfg, SimpleCall}; use url::Url; use failure::Error; fn do_call(htp: &amp;mut Httpc, poll: &amp;Poll, mut call: SimpleCall) -&gt; Result&lt;String, Error&gt; { let mut buf: Option&lt;String&gt;; let to = ::std::time::Duration::from_millis(100); let mut events = Events::with_capacity(8); 'outer: loop { poll.poll(&amp;mut events, Some(to)).unwrap(); for cref in htp.timeout().into_iter() { if call.is_ref(cref) { return Err(format_err!("Request timed out")); } } for ev in events.iter() { let cref = htp.event(&amp;ev); if call.is_call(&amp;cref) &amp;&amp; call.perform(htp, &amp;poll).expect("Call failed") { let (resp, body) = call.finish().expect("No response"); println!("done req = {}", resp.status); for h in resp.headers() { println!("Header = {}", h); } match String::from_utf8(body.clone()) { Ok(s) =&gt; buf = Some(s), Err(_) =&gt; { return Err(format_err!("Non utf8 body sized: {}", body.len())); } } break 'outer; } } } match buf { Some(s) =&gt; Ok(s), None =&gt; Err(format_err!("Empty response")), } } pub fn basename(path: &amp;str) -&gt; String { match path.rsplit(std::path::MAIN_SEPARATOR).next() { Some(p) =&gt; p.to_string(), None =&gt; path.into(), } } pub fn download(dir: Option&lt;&amp;str&gt;, urls: Vec&lt;&amp;str&gt;) -&gt; Result&lt;HashMap&lt;String, String&gt;, Error&gt; { let mut url2response: HashMap&lt;String, String&gt; = HashMap::new(); let poll = Poll::new()?; let cfg = match HttpcCfg::certs_from_path(".") { Ok(cfg) =&gt; cfg, Err(_) =&gt; Default::default(), }; let mut htp = Httpc::new(10, Some(cfg)); for i in 0..urls.len() { let call = CallBuilder::get() .url(urls[i])? // .expect("Invalid url") .timeout_ms(10000) // .insecure_do_not_verify_domain() .simple_call(&amp;mut htp, &amp;poll)?; // .expect("Call start failed"); let mut error: Option&lt;Error&gt; = None; let download_path: Option&lt;String&gt; = if dir.is_some() { let uri_opt = match Url::parse(urls[i]) { Ok(uri) =&gt; Some(uri), Err(e) =&gt; { error = Some(format_err!("{}", e.to_string())); None } }; if uri_opt.is_none() { None } else { let p = Path::new(&amp;dir.unwrap()) .join(Path::new(&amp;basename(uri_opt.unwrap().path()))) .to_string_lossy() .into_owned(); if p.is_empty() { error = Some(format_err!( "Conversion to filename failed for: {:#?}", urls[i] )); None } else { Some(p) } } } else { None }; if error.is_some() { return Err(error.unwrap()); } if download_path.is_none() &amp;&amp; dir.is_some() { return Err(format_err!("No filename detectable from URL")); } match do_call(&amp;mut htp, &amp;poll, call) { Ok(response_string) =&gt; url2response.insert( urls[i].into(), String::from(if dir.is_some() { let dp = download_path.unwrap(); write_file(Path::new(&amp;dp), response_string)?; dp } else { response_string }), ), Err(e) =&gt; return Err(format_err!("{}", e)), }; println!("Open connections = {}", htp.open_connections()); } Ok(url2response) } pub fn write_file(path: &amp;Path, content: String) -&gt; Result&lt;(), Error&gt; { let display = path.display(); let mut file = match File::create(&amp;path) { Err(why) =&gt; Err(format_err!( "couldn't create {}: {:#?}", display, why.kind() )), Ok(file) =&gt; Ok(file), }?; match file.write_all(content.as_bytes()) { Err(why) =&gt; Err(format_err!( "couldn't write to {}: {:#?}", display, why.kind() )), Ok(_) =&gt; Ok(()), } } pub fn env_or(key: &amp;str, default: std::ffi::OsString) -&gt; std::ffi::OsString { match std::env::var_os(key) { Some(val) =&gt; val, None =&gt; default, } } #[cfg(test)] mod tests { use super::*; const URLS: &amp;'static [&amp;'static str] = &amp;["http://detectportal.firefox.com/success.txt"]; #[test] fn download_to_dir() { let _td = temp_dir(); let _td_cow = _td.to_string_lossy(); let tmp_dir = _td_cow.as_ref(); match download(Some(tmp_dir), URLS.to_vec()) { Ok(url2response) =&gt; { for (url, response) in &amp;url2response { assert_eq!(url, URLS[0]); assert_eq!(Path::new(response), Path::new(tmp_dir).join("success.txt")) } } Err(e) =&gt; panic!(e), } } #[test] fn download_to_mem() { match download(None, URLS.to_vec()) { Ok(url2response) =&gt; { for (url, response) in &amp;url2response { assert_eq!(url, URLS[0]); assert_eq!(response, "success\n") } } Err(e) =&gt; panic!(e), } } } </code></pre> <p>Annoyed though, it's ~200 lines of code, not particularly readable, lots of type conversions, not sure if I should be:</p> <ul> <li>borrowing and using implicit conversions with <code>From</code> on function definitions and/or <code>AsRef</code> to enable different kinds of collections; <ul> <li>E.g.: can I support arrays, slices, queues, vectors and stacks? - maybe rewrite using <code>Iterator</code>?</li> </ul></li> <li>relying on <a href="https://docs.rs/rayon/1.0.3/rayon" rel="nofollow noreferrer">rayon</a> as well as <a href="https://docs.rs/mio_httpc/0.8.6/mio_httpc" rel="nofollow noreferrer">mio_httpc</a>, so I can get simple multithreading and multiprocessing</li> <li>using async/await and integrating that into mio_httpc to cleanup the code</li> <li>error handling in some better way? <ul> <li>On that note, I guess I should test error branches also?</li> </ul></li> <li>what else I could be doing better?</li> </ul>
[]
[ { "body": "<h1>Error Handling</h1>\n\n<p>Your error handling is pretty inconsistent. Sometimes you just unwrap:</p>\n\n<pre><code> poll.poll(&amp;mut events, Some(to)).unwrap();\n</code></pre>\n\n<p>Sometimes you use expect:</p>\n\n<pre><code> call.perform(htp, &amp;poll).expect(\"Call failed\")\n</code></pre>\n\n<p>Sometimes you use ?:</p>\n\n<pre><code> let poll = Poll::new()?;\n</code></pre>\n\n<p>Sometimes you <code>match</code>:</p>\n\n<pre><code> match do_call(&amp;mut htp, &amp;poll, call) {\n Ok(response_string) =&gt; ...\n Err(e) =&gt; return Err(format_err!(\"{}\", e)),\n };\n</code></pre>\n\n<p>If you plan to write a reusable crate, you certainly do not want to <code>panic!()</code> via <code>unwrap()</code> or <code>expect()</code>. Your code in general would be a lot simpler if it consistently used ? to handle errors. </p>\n\n<h1>Types</h1>\n\n<p>Right now you pass around strings a lot. Part of the advantage of Rust is a powerful type system. Where possible it is better to have code take more precise types as parameters. For example, instead of taking the urls as a list of strings, take a list of URLs. Instead of running a path as a String, return it as a <code>Path</code>. When it comes download files from URLS, there is a good chance you don't want Strings at all (which have to be utf-8) but the more generic <code>Vec&lt;u8&gt;</code></p>\n\n<h1>Api</h1>\n\n<p>Your download function does very different things depending on whether the dir is None or not. In particular, the return value has a completely different meaning. This sort of thing is tolerated in some other languages, but deeply frowned upon in Rust. Downloading to memory and to file should be different functions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-04T21:18:40.833", "Id": "212876", "ParentId": "212669", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T07:06:09.000", "Id": "212669", "Score": "2", "Tags": [ "performance", "generics", "concurrency", "http", "rust" ], "Title": "Batch downloading to file or memory" }
212669
<p>Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.</p> <p>For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].</p> <p>Is there a better solution for this problem?</p> <blockquote> <p>Note: Division is not allowed.</p> </blockquote> <pre><code>public class DailyCodingProblem2 { public static void main(String args[]) { int[] arr = { 1, 2, 3, 4, 5 }; int[] ans = solution(arr, arr.length); System.out.println(Arrays.toString(ans)); arr = new int[] { 3, 2, 1 }; ans = solution(arr, arr.length); System.out.println(Arrays.toString(ans)); } private static int[] solution(int[] arr, int n) { int[] left = new int[n]; int[] right = new int[n]; int[] res = new int[n]; left[0] = 1; right[n - 1] = 1; for (int i = 1; i &lt; n; i++) { left[i] = arr[i - 1] * left[i - 1]; } for (int i = n - 2; i &gt;= 0; i--) { right[i] = arr[i + 1] * right[i + 1]; } for (int i = 0; i &lt; n; i++) { res[i] = left[i] * right[i]; } return res; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T11:42:44.777", "Id": "411393", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T03:44:16.133", "Id": "411479", "Score": "0", "body": "\"Note: Division is not allowed.\" Why? Is it because of a restriction for the assignment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-04T05:15:36.023", "Id": "411620", "Score": "0", "body": "@SolomonUcko Yes it is a restriction for the assignment" } ]
[ { "body": "<p>Time complexity-wise, I think not. You're required to 'visit' all numbers, and your solution is <code>O(n)</code>, so that can't be improved.</p>\n\n<p>Code clarity could be improved, as it's not very obvious what the intention is. Some <strong>comments</strong> would help that.\nI think shifting indices by 1 might make it clearer (<code>left[i+1] = arr[i] * left[i]</code>), but then maybe not because it'd mess up the last loop.</p>\n\n<p>Have you explored different algorithms? I wonder if straightforward memoization makes a very clear solution for this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T09:21:21.097", "Id": "212679", "ParentId": "212674", "Score": "2" } } ]
{ "AcceptedAnswerId": "212679", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T07:57:33.857", "Id": "212674", "Score": "1", "Tags": [ "java", "algorithm", "array" ], "Title": "Products excluding each element of the array" }
212674
<p>I am trying to optimize my reducer code, preferably into one-liner with high-order-functions.</p> <p>Reducer should return new array with names of groups, with new number.</p> <p>Below are correct inputs and outputs:</p> <pre><code>Input: | Output: | [] | ['A1'] ['A1'] | ['A1', 'A2'] ['A1', 'A3'] | ['A1', 'A2', 'A3'] ['WORD', 'A2']| ['WORD', 'A2', 'A1'] </code></pre> <p>Code below is part of switch-case block:</p> <pre><code>case DrivesPageActions.DrivesPageActionTypes.AddCustomGroup: if (state.customGroups.includes('A1') === false) { return { ...state, customGroups: [...state.customGroups, 'A1'] }; } else if (state.customGroups.includes('A2') === false) { return { ...state, customGroups: [...state.customGroups, 'A2'] }; } else { return { ...state, customGroups: [...state.customGroups, 'A3'] }; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T16:04:29.187", "Id": "411425", "Score": "0", "body": "A little context as to what this logic is used for would be great. Also, it looks like `A2` in the third example does not follow the logic. It's inserted in between, not appended at the end." } ]
[ { "body": "<blockquote>\n <p>preferably into one-liner with high-order-functions.</p>\n</blockquote>\n\n<p>Machines execute code the same way, minified or not. But a human doesn't read or understand minified code the same way as verbose JS. Write for a human, don't one-line code.</p>\n\n<p>Now one thing about your code. You do NOT compare booleans. <code>if</code> statements evaluate booleans. If your expression is already a boolean, then just use that boolean. If you need to negate it, use <code>!</code>.</p>\n\n<pre><code>case DrivesPageActions.DrivesPageActionTypes.AddCustomGroup:\n if (!state.customGroups.includes('A1')) {\n return {\n ...state,\n customGroups: [...state.customGroups, 'A1']\n };\n } else if (!state.customGroups.includes('A2')) {\n return {\n ...state,\n customGroups: [...state.customGroups, 'A2']\n };\n } else {\n return {\n ...state,\n customGroups: [...state.customGroups, 'A3']\n };\n }\n</code></pre>\n\n<p>Looks like your code is looking for <code>A1</code>, <code>A2</code> and <code>A3</code> in that order and adding the first one that's not found. You could just create an array of the three, then filter it by the array in the state, removing the ones already present. The first item in the filtered array is the item you want.</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 inserts = ['A1', 'A2', 'A3']\nconst defaultInsert = inserts[inserts.length - 1]\n\nfunction reducer(state, action){\n switch (action) {\n case 'AddCustomGroup':\n const missing = inserts.filter(v =&gt; !state.customGroups.includes(v))\n const insert = missing[0] || defaultInsert\n return { ...state, customGroups: [...state.customGroups, insert] }\n default:\n return state\n }\n}\n\nconsole.log(reducer({ customGroups: [] }, 'AddCustomGroup'))\nconsole.log(reducer({ customGroups: ['A1'] }, 'AddCustomGroup'))\nconsole.log(reducer({ customGroups: ['A1', 'A3'] }, 'AddCustomGroup'))\nconsole.log(reducer({ customGroups: ['WORD', 'A2'] }, 'AddCustomGroup'))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T16:21:48.680", "Id": "212706", "ParentId": "212677", "Score": "1" } } ]
{ "AcceptedAnswerId": "212706", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T09:12:45.533", "Id": "212677", "Score": "0", "Tags": [ "javascript", "redux" ], "Title": "Optimizing NGRX reducer" }
212677
<p>I'm under no illusion that this is at all the best way or even a good way of doing this. It's simply a working solution. Tips, opinions, suggestions, insults, death threats, let's hear it.</p> <pre><code>&lt;?php require_once '../include/include.php'; include FUNCTIONS.DS.'functions.php'; $getPage = CurlPage($URL); $getPage1httpCode = $getPage['httpCode']; if ($getPage1httpCode != 200) { sleep(rand(5, 10)); echo '&lt;h3 style="color:white;"&gt;Attempt #2&lt;/h3&gt;'; $getPage2 = CurlPage($URL); $getPage1httpCode2 = $getPage2['httpCode']; if ($getPage1httpCode2 != 200) { sleep(rand(5, 10)); echo '&lt;h3 style="color:white;"&gt;Attempt #3&lt;/h3&gt;'; $getPage3 = CurlPage($URL); $getPage1httpCode3 = $getPage3['httpCode']; if ($getPage1httpCode3 != 200) { sleep(rand(5, 10)); echo '&lt;h3 style="color:white;"&gt;Attempt #4&lt;/h3&gt;'; $getPage4 = CurlPage($URL); $getPage1httpCode4 = $getPage4['httpCode']; if ($getPage1httpCode4 != 200) { sleep(rand(5, 10)); echo '&lt;h3 style="color:white;"&gt;Attempt #5&lt;/h3&gt;'; $getPage5 = CurlPage($URL); $getPage1httpCode5 = $getPage5['httpCode']; if ($getPage1httpCode5 != 200) { sleep(rand(5, 10)); echo '&lt;h3 style="color:white;"&gt;Failed.&lt;/h3&gt;'; var_dump('Fatal Error'); die(); } } } } } if ($getPage == 200 || $getPage1httpCode == 200 || $getPage1httpCode2 == 200 || $getPage1httpCode3 == 200 || $getPage1httpCode4 == 200 || $getPage1httpCode5 == 200) { if ($getPage == 200) { $HTML = $getPage['Data']; echo '&lt;h3 style="color:green;&gt;httpCode1 Success: 200&lt;/h3&gt;'; } elseif ($getPage1httpCode == 200) { $HTML = $getPage1httpCode['Data']; echo '&lt;h3 style="color:green;&gt;httpCode2 Success: 200&lt;/h3&gt;'; } elseif ($getPage1httpCode2 == 200) { $HTML = $getPage1httpCode2['Data']; echo '&lt;h3 style="color:green;&gt;httpCode3 Success: 200&lt;/h3&gt;'; } elseif ($getPage1httpCode3 == 200) { $HTML = $getPage1httpCode3['Data']; echo '&lt;h3 style="color:green;&gt;httpCode4 Success: 200&lt;/h3&gt;'; } elseif ($getPage1httpCode4 == 200) { $HTML = $getPage1httpCode4['Data']; echo '&lt;h3 style="color:green;&gt;httpCode5 Success: 200&lt;/h3&gt;'; } elseif ($getPage1httpCode5 == 200) { $HTML = $getPage1httpCode5['Data']; echo '&lt;h3 style="color:green;&gt;httpCode6 Success: 200&lt;/h3&gt;'; } else { var_dump('Fatal Error'); die(); } if (isHTML($HTML)) { $saveHTMLfileName = ROOT_DIR.DS.'pages'.DS.date('m-d-Y_hia').'.html'; if (!file_exists($saveHTMLfileName)) { file_put_contents($saveHTMLfileName, $HTML); } } TruncateCookieFile(); $conn = NULL; </code></pre> <blockquote> <blockquote> <p>Associated Functions // include FUNCTIONS.DS.'functions.php';</p> </blockquote> </blockquote> <pre><code>function CurlPage($URL) { $Cookie = ROOT_DIR . DS . '_misc' . DS . 'cookie.txt'; if (!file_exists($Cookie)) { $OpenCookieFile = fopen($Cookie, "w"); fclose($OpenCookieFile); } $Host = 'example.com'; $acceptLanguage = 'en-US'; $Curl = curl_init(); curl_setopt($Curl, CURLOPT_URL, $URL); curl_setopt($Curl, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($Curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($Curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($Curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($Curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($Curl, CURLOPT_ENCODING, 1); curl_setopt($Curl, CURLOPT_COOKIESESSION, 1); curl_setopt($Curl, CURLOPT_COOKIEJAR, $Cookie); curl_setopt($Curl, CURLOPT_COOKIEFILE, $Cookie); curl_setopt($Curl, CURLOPT_HTTPHEADER, array( 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Language:' . $acceptLanguage . ',en;q=0.9', 'Cache-Control: max-age=0', 'Connection: keep-alive', 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0', 'Host: ' . $Host )); $Content = curl_exec($Curl); $httpCode = curl_getinfo($Curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($httpCode == 200) { return array( 'httpCode' =&gt; $httpCode, 'Data' =&gt; $Content ); } elseif ($httpCode != 200) { return array( 'httpCode' =&gt; 0, 'Data' =&gt; 0 ); } } function TruncateCookieFile() { $Cookie = ROOT_DIR . DS . '_misc' . DS . 'cookie.txt'; $openCookieFile = @fopen($Cookie, "r+"); if ($openCookieFile !== false) { ftruncate($openCookieFile, 0); fclose($openCookieFile); } } function isHTML( $str ) { return preg_match( "/\/[a-z]*&gt;/i", $str ) != 0; } </code></pre> <p>I'm especially turned off by my loop-from-hell HTTP Code 200 Validator. I know I can add a validator on the HTML being returned, matching content-size to file-size. Of course add a more detailed and verbose error logging system. But these are just new features, irrelevant to the question.</p> <p>I want to know how much my code sucks and how it can be improved.</p>
[]
[ { "body": "<p>You can put your logic in a <code>while</code> loop that repeats indefinitely (we'll break out of it later). In that loop make your HTTP request and parse the response. If it is successful get the HTML returned by it and <code>break</code> out of the loop. If it fails pause, increment your retry attempts, and then check to see if you have reached your maximum amount of retries. If so, <code>die()</code>.</p>\n\n<pre><code>while (true) {\n $getPage = CurlPage($URL);\n $getPage1httpCode = $getPage['httpCode'];\n if ($getPage1httpCode === 200) {\n $HTML = $getPage['Data'];\n break;\n }\n sleep(rand(5, 10));\n $attempts++;\n if ($attempts === 5) {\n die('Fatal Error');\n }\n}\n</code></pre>\n\n<p>I didn't run this code but it should demonstrate how you can simply this code and avoid code repetition and the <a href=\"http://wiki.c2.com/?ArrowAntiPattern\" rel=\"nofollow noreferrer\">arrowhead anti-pattern</a>.</p>\n\n<p><strong>Variable Naming</strong></p>\n\n<p>When naming variables don't use all uppercase unless you are trying to represent a constant. <code>$HTML</code> should be <code>$html</code>. (And if you are trying to have a variable act as a constant you should use <code>define()</code> to make it an actual constant but that doesn't apply here).</p>\n\n<p>Variables should also start with a lower case letter. So <code>$Cookie</code> becomes <code>$cookie</code>.</p>\n\n<p><strong>Follow PSR coding standards</strong> </p>\n\n<p>The PSR coding standards exist to ensure a high level of technical interoperability between shared PHP code. They also ensure conformity for projects with multiple developers. </p>\n\n<p><a href=\"https://www.php-fig.org/psr/psr-2/\" rel=\"nofollow noreferrer\">PSR-2 </a> says that:</p>\n\n<blockquote>\n <p>Opening braces for control structures MUST go on the same line, and closing braces MUST go on the next line after the body.</p>\n</blockquote>\n\n<pre><code>if ($getPage1httpCode != 200)\n{\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>if ($getPage1httpCode != 200) {\n</code></pre>\n\n<p><strong>When doing comparisons use === whenever possible</strong></p>\n\n<p>Unlike <code>==</code> which compares values only, <code>===</code> compares both values and <em>type</em>. This strict comparison helps to avoid error, and attacks, that occur when PHP encounters a comparison of two variables of different types it will coerce one of the variables into the type of the other variable in order to do the comparison.</p>\n\n<p>For example</p>\n\n<pre><code>1 == '1' // true\n1 === '1' // false\n</code></pre>\n\n<p>How much does this matter? It depends. If you get into a situation where you are getting numbers as strings but you are trying to use them as numbers, for something like sorting, you can get unexpected results if your check only checks value instead of type. And those of us who remember phpBB remember when it was subject to a slew of high profile vulnerabilities many of which were resolved simply by using a stricter comparison. So, yes, it matters. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T21:51:00.507", "Id": "411465", "Score": "0", "body": "Very informative and insightful, thank you. Looking forward to doing some clean up with these techniques in mind. The while loop is quite brilliant I was hoping there was a viable solution to loop X amount of times with a variable. Haven't tested yet either, will soon, but see no reason why it wouldn't work. Thanks again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T03:06:19.597", "Id": "411477", "Score": "0", "body": "You can configure to loop a variable number of times. Just remove the hard coded `5` and replace it with a variable that you assign a value to elsewhere." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T06:28:36.213", "Id": "411489", "Score": "0", "body": "Yes, that's why I was especially thankful. Tried it out by the way - works great. Actually never used an infinite loop before.. very cool solution." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T12:49:58.433", "Id": "212687", "ParentId": "212682", "Score": "2" } } ]
{ "AcceptedAnswerId": "212687", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T09:46:08.527", "Id": "212682", "Score": "2", "Tags": [ "php", "curl" ], "Title": "Retrying Curl X amounts of Time until Successful Return (Script/Functions)" }
212682
<p>I am running a script to identify polygons that overlap with other polygons within the same layer. I have managed to do this with the code below but the problem is that it is very slow (about 3 seconds per feature). </p> <p>Is there anything I can do to improve its performance?</p> <pre><code>arcpy.CreateFeatureclass_management("results.gdb", "Overlapping_Polygons", "POLYGON", "lyr_existing_cadastre", "DISABLED", "DISABLED", arcpy.Describe("lyr_existing_cadastre").spatialReference) arcpy.MakeFeatureLayer_management("results.gdb/Overlapping_Polygons", "lyr_Overlapping_Polygons") arcpy.CreateFeatureclass_management("results.gdb", "Remaining_Polygons", "POLYGON", "lyr_existing_cadastre", "DISABLED", "DISABLED", arcpy.Describe("lyr_existing_cadastre").spatialReference) arcpy.MakeFeatureLayer_management("results.gdb/Remaining_Polygons", "lyr_Remaining_Polygons") arcpy.CreateFeatureclass_management("in_memory", "row", "POLYGON", "lyr_existing_cadastre", "DISABLED", "DISABLED", arcpy.Describe("lyr_existing_cadastre").spatialReference) arcpy.MakeFeatureLayer_management("row", "lyr_row") arcpy.AddSpatialIndex_management("lyr_existing_cadastre") with arcpy.da.SearchCursor("lyr_existing_cadastre", ["OBJECTID"]) as search_cursor: for row in search_cursor: log("\t {}".format(row[0])) # Get the OBJECTID of row and use it to select row arcpy.SelectLayerByAttribute_management("lyr_existing_cadastre", "NEW_SELECTION", "\"OBJECTID\" = " + str(row[0])) # Copy row into a new feature class called row arcpy.Append_management("lyr_existing_cadastre", "lyr_row", "NO_TEST") # Remove row from the input arcpy.DeleteFeatures_management("lyr_existing_cadastre") # Select all features that intersect with row and copy them into the row feature class arcpy.SelectLayerByLocation_management("lyr_existing_cadastre", "WITHIN", "lyr_row", selection_type="NEW_SELECTION") arcpy.Append_management("lyr_existing_cadastre", "lyr_row", "NO_TEST") # If there is more than one feature in the row feature class # meaning there was something else in addition to row then delete those overlaps # from the input and append everything in row into the output feature class if (int(arcpy.GetCount_management("lyr_row").getOutput(0)) &gt; 1): arcpy.DeleteFeatures_management("lyr_existing_cadastre") arcpy.Append_management("lyr_row", "lyr_Overlapping_Polygons", "NO_TEST") else: arcpy.Append_management("lyr_row", "lyr_Remaining_Polygons", "NO_TEST") arcpy.SelectLayerByAttribute_management("lyr_existing_cadastre", "CLEAR_SELECTION") arcpy.TruncateTable_management("lyr_row") del search_cursor </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T13:13:24.423", "Id": "411399", "Score": "4", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T13:32:24.937", "Id": "411402", "Score": "2", "body": "Thank you. I have made the edits. I hope it's better now." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T13:05:25.097", "Id": "212688", "Score": "3", "Tags": [ "python", "performance", "arcpy" ], "Title": "Select polygons that overlap with other polygons within a single feature class" }
212688
<p>I've got this code to loop through each cell in Column A and check the cell value. If the value matches the if criteria it moves the entire row to the correct Sheet and then replaces the Column A cell with an X. This makes a call to the server for every cell and I'm curious if there is a way for me to optimize it similar to what Google has documented as <a href="https://developers.google.com/apps-script/guides/support/best-practices" rel="nofollow noreferrer">Best Practices</a>. The Cache service is confusing me.</p> <p><a href="https://docs.google.com/spreadsheets/d/1DNND1A5-UROw2IoIGtTCQc77CcTjsHkZzpm08xJEPwE/edit?usp=sharing" rel="nofollow noreferrer">Here is a copy of the spreadsheet I'm working on.</a> The code has a menu execution under Move Row.</p> <pre><code>function moveToQA() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = SpreadsheetApp.getActiveSheet(); var lastRow = sheet.getLastRow(); var columnNumberToWatch = 1; var targetSheet = ss.getSheetByName("QA "); for( var i = 3; i &gt;= 3; i++ ) { var cell = sheet.getRange(i,1); var cellValue = cell.getValue(); if (cellValue == "Captures Sent " || cellValue == "QA In Progress " || cellValue == "Recapture Completed ") { var targetRange = targetSheet.getRange(targetSheet.getLastRow() + 1, 1); sheet.getRange(cell.getRow(), 1, 1, sheet.getLastColumn()).moveTo(targetRange); cell.setValue("X"); } else if (cellValue != "") { continue; } else if (cellValue == "" || cell == lastRow) { break; } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T14:09:46.087", "Id": "212691", "Score": "1", "Tags": [ "google-apps-script" ], "Title": "Google App Script sheet that moves row to correct sheet" }
212691
<p>I have implemented below code for binary search tree implementation using shared pointer. At present, I have considered only integers. It supports insertion and deletion of values. Also, a print method is implemented for inorder traversal.</p> <p>Please review and provide your suggestions.</p> <pre><code>class Bst { struct node { int val; shared_ptr&lt;node&gt; left, right; node(int v) : val(v), left(nullptr), right(nullptr){} }; shared_ptr&lt;node&gt; root; shared_ptr&lt;node&gt; _insert(shared_ptr&lt;node&gt; curr, int val); shared_ptr&lt;node&gt; _del(shared_ptr&lt;node&gt; curr, int val); shared_ptr&lt;node&gt; findmin(shared_ptr&lt;node&gt; curr); void _print(shared_ptr&lt;node&gt; curr); public: void insert(int val) { root = _insert(root, val); } void del(int val) { root = _del(root, val); } void print() { _print(root); cout &lt;&lt; '\n'; } }; shared_ptr&lt;Bst::node&gt; Bst::_insert(shared_ptr&lt;node&gt; curr, int val) { if (curr == nullptr) return make_shared&lt;node&gt;(val); if (val &lt; curr-&gt;val) curr-&gt;left = _insert(curr-&gt;left, val); else curr-&gt;right = _insert(curr-&gt;right, val); return curr; } shared_ptr&lt;Bst::node&gt; Bst::findmin(shared_ptr&lt;node&gt; curr) { while (curr-&gt;left) curr = curr-&gt;left; return curr; } shared_ptr&lt;Bst::node&gt; Bst::_del(shared_ptr&lt;node&gt; curr, int val) { if (val &lt; curr-&gt;val) curr-&gt;left = _del(curr-&gt;left, val); else if (val &gt; curr-&gt;val) curr-&gt;right = _del(curr-&gt;right, val); else { if (curr-&gt;right == nullptr) return curr-&gt;left; if (curr-&gt;left == nullptr) return curr-&gt;right; shared_ptr&lt;node&gt; temp = findmin(curr-&gt;right); curr-&gt;val = temp-&gt;val; curr-&gt;right = _del(curr-&gt;right, curr-&gt;val); } return curr; } void Bst::_print(shared_ptr&lt;node&gt; curr) { if (curr == nullptr) return; _print(curr-&gt;left); cout &lt;&lt; curr-&gt;val &lt;&lt; " "; _print(curr-&gt;right); } </code></pre>
[]
[ { "body": "<ul>\n<li>please do not <code>using namespace std;</code></li>\n<li>why has <code>Bst::findmin</code> no prefix <code>_</code>?</li>\n<li>why do you use <code>std::shared_ptr&lt;&gt;</code> at all? <code>std::shared_ptr</code> is ment to represent shared ownership. This makes no sense for tree nodes, you're not going to have two trees with the same nodes. <code>std::unique_ptr&lt;&gt;</code> is a better candidate.</li>\n<li>it is generally good to separate the data structure from its serialization. Make <code>print</code> a separate function and also handle the member printing outside of the class. </li>\n</ul>\n\n<hr>\n\n<p><strong>Edit</strong>\nAs you had trouble getting the <code>unique_ptr</code> running, here's what works for me.</p>\n\n<p>Modify the node to use <code>unique_ptr</code>:</p>\n\n<pre><code>struct node\n{\n int val;\n std::unique_ptr&lt;node&gt; left;\n std::unique_ptr&lt;node&gt; right;\n\n // c'tor left out\n};\n</code></pre>\n\n<p>Also, use a <code>unique_ptr</code> for <code>root</code>. You'll receive heavy compiler complaints, \nbecause a unique_ptr cannot be simply copied (one of the instances must go invalid, as it's <em>unique</em>). I suggest altering the private functions:</p>\n\n<pre><code>void _insert(std::unique_ptr&lt;node&gt;&amp; curr, int val);\nvoid _del(std::unique_ptr&lt;node&gt;&amp; curr, int val);\n</code></pre>\n\n<p>Sample implementation for <code>_insert</code>:</p>\n\n<pre><code>void Bst::_insert(std::unique_ptr&lt;node&gt;&amp; curr, int val)\n{\n if (!curr)\n {\n curr = std::make_unique&lt;node&gt;(val);\n return;\n }\n\n if (val &lt; curr-&gt;val)\n {\n _insert(curr-&gt;left, val);\n }\n else\n {\n _insert(curr-&gt;right, val);\n }\n}\n</code></pre>\n\n<p>Your public <code>insert</code> method would be something like:</p>\n\n<pre><code>void insert(int val)\n{ \n _insert(root, val);\n}\n</code></pre>\n\n<p>Also: add a <code>find</code> function to see if an element is in the tree. Use the <code>find</code> function to write some simple tests. You may rename <code>del</code> to <code>erase</code> to be closer at the standard naming. </p>\n\n<hr>\n\n<p><strong>Edit 2</strong> Separate output from data storage:</p>\n\n<p>A friend function is relatively inflexible, as you cannot easily exchange the printing algorithm. You may implement iterators (hard) or provide a traverse function. I'd go for the second approach, as you already have the algorithm in <code>_print</code>: rename <code>print</code> to <code>traverse</code> and pass it a function pointer, then replace the output to <code>std::cout</code> by a call to the function pointer. </p>\n\n<pre><code>\nclass Bst\n{\n...\n // traverse with function pointer\n void traverse(void (*func)(int));\n};\n\nint main()\n{\n Bst b;\n // insert data ... \n\n b.traverse([](auto v){ std::cout &lt;&lt; v &lt;&lt; \" \"; });\n std::cout &lt;&lt; \"\\n\";\n}\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T17:24:07.117", "Id": "411444", "Score": "0", "body": "I am doing \"using std::cin\"(similarly for others) and not \"using namespace std\". Is it ok ? Also, I thought of using unique_ptr but in that case how do i pass arguments in recursion as it is not allowed for unqiue_ptr ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T17:33:39.660", "Id": "411446", "Score": "0", "body": "You shouldn't do so in header files as you cannot tell if you/someone else wants to use identifiers as `cin` or `shared_ptr`. In implementation files it's kind of ok, though I would strongly advice against doing. At best it looks funny. Everybody else will think it is something different than an STL template, so you're reducing the readability of your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T06:32:11.500", "Id": "411490", "Score": "0", "body": "Thanks for your valuable review. Regarding your fourth point of making print a separate function. Since, root is a private member of Bst class, I will have to create a friend function so that print can access the nodes ?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T14:46:16.707", "Id": "212696", "ParentId": "212692", "Score": "10" } }, { "body": "<ul>\n<li>Separate your class declaration and definition into separate <code>Bst.h</code> and <code>Bst.cpp</code> files</li>\n<li>For <code>Bst.h</code> provide <a href=\"https://en.wikipedia.org/wiki/Include_guard\" rel=\"noreferrer\">header guards</a></li>\n<li>initialize <code>shared_ptr&lt;node&gt;</code> member, <code>root</code> with <code>nullptr</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T17:30:18.400", "Id": "411445", "Score": "2", "body": "I thought root will be initialized to nullptr by default ?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T16:09:52.327", "Id": "212705", "ParentId": "212692", "Score": "5" } }, { "body": "<p>You forgot to include any of the headers that your code depends on; copy/paste of this into <a href=\"https://godbolt.org/\" rel=\"nofollow noreferrer\">https://godbolt.org/</a> gives lots of errors until I add <code>#include &lt;memory&gt;</code> and iostream, and some <code>using</code> declarations (<a href=\"https://godbolt.org/z/cE0GDR\" rel=\"nofollow noreferrer\">https://godbolt.org/z/cE0GDR</a>). So the code in the question is incomplete.</p>\n\n<p><strong>More importantly, for <code>shared_ptr</code> to be thread-safe, it has to use atomic-increment / decrement instructions, and check if the ref-count has become 0 after it's done referencing a node.</strong> This makes it significantly more expensive than I think you want. As another answer suggests, <code>std::unique_ptr&lt;&gt;</code> is probably a better choice.</p>\n\n<p>So for example, your <code>findmin()</code> source looks really simple, just traversing down to the left-most leaf node, but because you're using <code>shared_ptr</code> it compiles (on x86-64) to <code>lock add</code> and <code>lock xadd</code> instructions, potentially calling the destructor to free the node.</p>\n\n<p>(gcc emits checks before actually doing the atomic ++ / -- ref counting. It checks <a href=\"https://stackoverflow.com/questions/27257655/undefined-reference-to-gthrw-pthread-key-createunsigned-int-void-voi\">the <em>address</em> of a weak alias for <code>__pthread_key_create</code></a>. I think this might just be checking if the program could possibly be multi-threaded, i.e. linked with the thread library, rather than if multiple threads are currently running. So some of the cost of <code>shared_ptr</code> might go away in some single-threaded programs.)</p>\n\n<p>If you're looking at the asm on the Godbolt compiler explorer, search for the <code>lock</code> prefix for x86-64. Or for AArch64, look for <code>ldaxr</code>/<code>stlxr</code> LL/SC retry loops (load-acquire exclusive / store sequential-release exclusive).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T08:23:45.803", "Id": "212746", "ParentId": "212692", "Score": "0" } } ]
{ "AcceptedAnswerId": "212696", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T14:26:44.207", "Id": "212692", "Score": "8", "Tags": [ "c++", "object-oriented", "c++11", "design-patterns", "pointers" ], "Title": "Binary Search Tree implementation using smart pointers" }
212692
<h3>SplitSort</h3> <p><em>SplitSort</em> is a rather simple <em>Inv</em>-adaptive and <em>Rem</em>-adaptive sorting algorithm described in <em>Splitsort — an adaptive sorting algorithm</em> by Christos Levcopoulos and Ola Petersson. The paper actually contains two algorithms: a smart out-of-place version, and a simpler in-place version which removes a few of the algorithm's subtleties in order to make it run without having to allocate additional memory.</p> <p><em>SplitSort</em> is a sorting algorithm working in three steps:</p> <ol> <li>First it tries to isolate an approximation of a <a href="https://en.wikipedia.org/wiki/Longest_increasing_subsequence" rel="nofollow noreferrer">longest non-decreasing subsequence</a> (LNDS) in the collection by splitting the collection in two parts: one with the LNDS and one with the other elements.</li> <li>Then it sorts the elements that are not part of the LNDS.</li> <li>Finally it merges the two parts of the collection.</li> </ol> <p>Instead of trying to find an actual LNDS, the algorithm uses a simple heuristic to find an approximate LNDS: it reads the collection element per element and considers every element found so far to be part of the LNDS, but whenever it reads an element which is strictly smaller than the previous one, it removes both elements from the approximate LNDS.</p> <p>In order to implement that as an in-place algorithm, the following technique is used: an iterator points to the next element to read, and another iterator points to the last element which is part of the approximate LNDS; both pointers are increased as long as the elements read are part of the approximate LNDS and the latest read value is swapped with the element right after the head of the approximate LNDS. Whenever two elements need to be dropped, the iterator pointer to the head of the LNDS is decremented and the reader iterator is still increased. Once the whole collection has been crossed by the reader iterator, the resulting collection should have roughly the following shape:</p> <pre><code>[ LNDS | unsorted elements ] </code></pre> <p>The only thing left to do is to sort the unsorted elements and to merge the two parts of the collection in order to obtained a fully sorted collection.</p> <h3>The code</h3> <pre class="lang-cpp prettyprint-override"><code>#include &lt;algorithm&gt; #include &lt;functional&gt; #include &lt;iterator&gt; #include &lt;utility&gt; template&lt;typename RandomAccessIterator, typename Compare=std::less&lt;&gt;&gt; auto split_sort(RandomAccessIterator first, RandomAccessIterator last, Compare compare={}) -&gt; void { if (std::distance(first, last) &lt; 2) return; // Read elements and build the LNDS auto middle = first; // Last element of the LNDS for (auto reader_it = std::next(first) ; reader_it != last ; ++reader_it) { if (compare(*reader_it, *middle)) { // We remove the top of the subsequence as well as the new element if (middle != first) { --middle; } } else { // Everything is fine, add the new element to the subsequence ++middle; std::iter_swap(middle, reader_it); } } std::sort(middle, last, compare); std::inplace_merge(first, middle, last, compare); } </code></pre> <h3>Performance</h3> <p>As a bonus, here is a graph showing the performance of <em>SplitSort</em> against two other sorting algorithms when sorting collections of <span class="math-container">\$ 10^5 \$</span> long <code>std::string</code> with an increasing number of out-of-place elements:</p> <p><img src="https://i.imgur.com/Mp0aKfF.png" alt="splitsort benchmark"></p> <p>It's a bit sketchy but we can see that <em>SplitSort</em> performs better than <a href="https://github.com/orlp/pdqsort" rel="nofollow noreferrer">pdqsort</a> (a smart introsort derivative) when under 40% of the elements are out-of-place and has some additional overhead when more elements are out-of-place. I also included <a href="https://github.com/adrian17/cpp-drop-merge-sort" rel="nofollow noreferrer">drop-merge-sort</a> in the benchmark because it uses a technique really similar to <em>SplitSort</em> except that it uses a smarter LNDS approximation scheme, and also isn't an in-place algorithm contrary to <em>SplitSort</em>. We can see that both algorithms offer a different trade-off with drop-merge-sort being faster than <em>SplitSort</em> when there aren't many out-of-place elements, but having a higher overhead when there are more such elements. Interestingly enough, both algorithms have a cut-off point around 40% of out-of-place elements where they start to perform worse than an introsort-like algorithm.</p> <h3>Conclusion</h3> <p>That's it, now you know how to write a simple algorithm to sort collections with few out-of-place elements faster. Any suggestion about improving the code so that it's more performant or more readable is welcome :)</p>
[]
[ { "body": "<p>There is nothing wrong that I can see.</p>\n\n<p>I can nitpick (so this is only to be overly nitpicky). But nothing I say here would stop me from merging this into an existing code base (assuming you had the tests to prove it worked correctly).</p>\n\n<ol>\n<li><p>Your template type <code>RandomAccessIterator</code> indicates you only support random access iterators (RAI). If you absolutely want this to be a RAI then maybe you should enforce it? Does <code>std::sort()</code> enforce that for you? Even if it does is the error messaging a bit obtuse? Ask the question can I help the user of my code spot and diagnose issues more easily if they use it incorrectly?</p></li>\n<li><p>With C++17 <code>std::sort()</code> and <code>std::inplace_merge()</code> support execution policies. Can you work that into your sort? Even if you don't use it yourself can you pass it through to one (or both) of these methods?</p></li>\n<li><p>Find the new return type syntax a bit unnatural still. Personally I only use this when I need to determine the return type at compile time. But don't have anything against it per say.</p></li>\n<li><p>The graph is a bit spikey. I presume that is because of the randomness of the strings you sort. Don't get rid of that but if you supplemented that by assuming one sort is base time and drawing the other two lines as percentage better/worse relative to your reference sort. Does this provide clearer indication of how each sort improves with randomness?</p></li>\n<li><p>Since this is a pretty unique sort. I would add a comment that has a link to the paper describing the sort. Maybe also a link to any graphs documentation you have written (which could be this page).</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T21:33:40.487", "Id": "411462", "Score": "0", "body": "Answering your points one by one: 1. I just did it the standard library does, hoping it's enough ^^\" 2. Note the C++14 tag to avoid having to deal with execution policies altogether, I have yet to play with them :p 3. I've stopped fighting over comments about this style (I get it almost once per question here), I just use it everywhere for consistency, but also because I like it more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T21:35:33.220", "Id": "411463", "Score": "0", "body": "4. Concerning the graph, I'm not sure why it's more spikey than the original (see the graphs in the drop-merge-sort repository, I used their benchmark), which might be because each spike is just the average over sorting the collection 5 times, maybe I could run it for longer. Just replacing `pdq_sort` by `std::sort` would probably be enough for people to consider it the reference sort. 5. Unfortunately the paper isn't publicly accessible, so I can't really give a direct link to it :/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T21:41:38.013", "Id": "411464", "Score": "0", "body": "@Morwenn None of my points are super important. As I said they are super nit picky and if you did no changes it would still be good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T22:01:39.467", "Id": "411467", "Score": "0", "body": "I wanted to address them anyway, I always feel like I need to provide explanations/justifications :p" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T19:50:23.283", "Id": "212712", "ParentId": "212693", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T14:28:09.073", "Id": "212693", "Score": "6", "Tags": [ "c++", "algorithm", "sorting", "c++14" ], "Title": "SplitSort — An adaptive algorithm to handle collections with few inversions" }
212693
<p>I am completely new to programming and to python and as my first self-learning project I am creating a simple Tic-Tac-Toe game. I have already posted a version of my code here on stack: <a href="https://codereview.stackexchange.com/questions/211766/tic-tac-toe-game-in-python-3-x-using-tkinter-ui">Tic Tac Toe game in Python 3.X using tkinter UI</a></p> <p>However, after I've spent some time learning and came back to the code - I have found a whole bunch of problems with it and decided to try and fix it myself. In addition to that I've switched from procedural tkinter GUI approach to the object-oriented tkinter GUI approach. I'm still not sure if I'm doing things the right way. Thus, I seek your advice.</p> <p>Note: choosing a setting in settings window does nothing for now. I am planning on implementing this feature in the future. I left it to get advice on creating radiobuttons and handling their control variables.</p> <pre><code>import random import tkinter as tk import tkinter.ttk as ttk class AppMain: def __init__(self, master): self.master = master self.frame = ttk.Frame(master, width=250, height=150, relief='groove') self.frame.pack_propagate(False) self.play = ttk.Button(self.frame, text='Play', command=lambda: PlayMenu(do=0)) self.settings = ttk.Button(self.frame, text='Settings', command=SettingsWindow) self.qb = ttk.Button(self.frame, text="Quit", command=root.destroy) self.main_window() def main_window(self): self.remove_widgets() self.frame.pack(padx=25, pady=75) self.play.pack(side='top', pady=(33, 0)) self.settings.pack(side='top', pady=5) self.qb.pack(side='top', pady=(0, 32)) def remove_widgets(self): for widget in self.master.winfo_children(): widget.pack_forget() class SettingsWindow(AppMain): def __init__(self): self.frame = ttk.Frame(root, width=250, height=150, relief='groove') self.frame.pack_propagate(False) self.rb1 = ttk.Radiobutton(self.frame, text='Easy', variable=mode, value=0) self.rb2 = ttk.Radiobutton(self.frame, text='Impossible', variable=mode, value=1) self.rb3 = ttk.Radiobutton(self.frame, text='2 players', variable=mode, value=2) self.back = ttk.Button(self.frame, text='Back', command=lambda: AppMain(master=root)) self.settings_window() def settings_window(self): r = AppMain(master=root) r.remove_widgets() self.frame.pack(padx=25, pady=75) self.rb1.pack(side='top', pady=(10, 0)) self.rb2.pack(side='top', pady=(10, 0)) self.rb3.pack(side='top', padx=(0, 22), pady=(10, 0)) self.back.pack(side='top', pady=(16, 16)) class PlayMenu(AppMain): def __init__(self, do): self.do = do self.label = ttk.Label(root, text='Choose your side', font=('French Script MT', 20)) self.frame = ttk.Frame(root, width=250, height=150, relief='groove') self.frame.pack_propagate(False) self.player_x = ttk.Button(self.frame, text='X', command=lambda: GameWindow(pl='X', pc='O')) self.player_o = ttk.Button(self.frame, text='O', command=lambda: GameWindow(pl='O', pc='X')) self.back = ttk.Button(self.frame, text='Back', command=lambda: AppMain(master=root)) if do == 'redeclare': global statusLib statusLib = [None for v in range(9)] self.play_menu() def play_menu(self): r = AppMain(master=root) r.remove_widgets() self.label.pack(side='top', pady=(25, 0)) self.frame.pack(padx=25, pady=25) self.player_x.grid(column=0, row=0, padx=(5, 0), pady=(5, 0)) self.player_o.grid(column=1, row=0, padx=(0, 5), pady=(5, 0)) self.back.grid(column=0, row=1, sticky='w, e', padx=(5, 5), pady=(0, 5), columnspan=2) class GameWindow(AppMain): def __init__(self, pl, pc): self.pl, self.pc, self.stop_game = pl, pc, False self.frame = ttk.Frame(root, width=650, height=700) self.frame.pack_propagate(False) self.canvas = tk.Canvas(self.frame, width=600, height=600) self.restart = ttk.Button(self.frame, text='Restart', command=lambda: PlayMenu(do='redeclare')) self.game_window() def game_window(self): r = AppMain(master=root) r.remove_widgets() self.frame.pack() self.canvas.pack(side='top', pady=(25, 0)) self.restart.pack(side='bottom', pady=20) self.draw_board() self.canvas.bind('&lt;Button-1&gt;', self.square_selector) if self.pl == 'O': self.computer_move() def draw_board(self): self.canvas.create_line(0, 200, 600, 200) self.canvas.create_line(0, 400, 600, 400) self.canvas.create_line(200, 0, 200, 600) self.canvas.create_line(400, 0, 400, 600) def square_selector(self, event): self.player_move(square=(event.x // 200 * 3 + event.y // 200)) def player_move(self, square): if statusLib[square] is None: self.make_move(sq=square, symbol=self.pl, turn='player') if not self.stop_game: self.computer_move() def computer_move(self): status, square = 0, None while status is not None: square = random.randint(0, 8) status = statusLib[square] self.make_move(sq=square, symbol=self.pc, turn='computer') def make_move(self, sq, symbol, turn): self.draw_move(symbol=symbol, sq=sq) statusLib[sq] = symbol self.end_game(this_move=turn, symbol=symbol) def draw_move(self, symbol, sq): pos = [100 + sq // 3 * 200, 100 + sq % 3 * 200] self.canvas.create_text(pos, text=symbol, font=('French Script MT', 50), anchor='center') def end_game(self, this_move, symbol): condition = self.check_end_game(symbol=symbol) self.stop_game = condition[0] text = '' if condition[0]: self.canvas.unbind('&lt;Button-1&gt;') if this_move == 'player' and not condition[1]: text = 'You win' elif this_move == 'computer' and not condition[1]: text = 'You lose' elif condition[1]: text = 'It\'s a tie' self.finisher(fin=condition[2]) self.canvas.create_text(300, 300, text=text, font=('French Script MT', 50), fill='#EE2C2C') @staticmethod def check_end_game(symbol): if statusLib[0] == statusLib[1] == statusLib[2] == symbol: return [True, False, 1] elif statusLib[3] == statusLib[4] == statusLib[5] == symbol: return [True, False, 2] elif statusLib[6] == statusLib[7] == statusLib[8] == symbol: return [True, False, 3] elif statusLib[0] == statusLib[3] == statusLib[6] == symbol: return [True, False, 4] elif statusLib[1] == statusLib[4] == statusLib[7] == symbol: return [True, False, 5] elif statusLib[2] == statusLib[5] == statusLib[8] == symbol: return [True, False, 6] elif statusLib[2] == statusLib[4] == statusLib[6] == symbol: return [True, False, 7] elif statusLib[0] == statusLib[4] == statusLib[8] == symbol: return [True, False, 8] elif all(k is not None for k in statusLib): return [True, True, 0] else: return [False, False, 0] def finisher(self, fin): lib = [[100, 100, 100, 500], [300, 100, 300, 500], [500, 100, 500, 500], [100, 100, 500, 100], [100, 300, 500, 300], [100, 500, 500, 500], [500, 100, 100, 500], [100, 100, 500, 500]] if fin != 0: self.canvas.create_line(lib[fin - 1][0], lib[fin - 1][1], lib[fin - 1][2], lib[fin - 1][3], fill='#1874CD', width=5) if __name__ == '__main__': root = tk.Tk() root.title('Tic Tac Toe') root.minsize(width=300, height=300) statusLib = [None for i in range(9)] mode = tk.IntVar() AppMain(master=root) root.mainloop() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T15:17:07.860", "Id": "212699", "Score": "0", "Tags": [ "python", "beginner", "python-3.x", "tic-tac-toe", "tkinter" ], "Title": "Tic Tac Toe game in Python 3.X using tkinter GUI version 2" }
212699
<p>Good day. So, I need to find the number of integers between 1 and K (inclusive) satisfying the following condition, modulo (10^9)+7:</p> <blockquote> <p>The sum of the digits in base ten is a multiple of D</p> </blockquote> <p>Here is my code: </p> <pre><code>k = int(input()) d = int(input()) count = 0 for i in range(1,k+1): hello = sum(list(map(int,str(i)))) if (hello%d == 0): count += 1 print (count) </code></pre> <p>Basically, what the above code does is:</p> <ol> <li>Takes as input two numbers: k &amp; d. </li> <li>Defines a counter variable called <code>count</code>, set to the default value of <code>0</code>. </li> <li>Iterates over all numbers in the given range: <code>1 to k</code>. </li> <li>If any number the sum of any number in the above range is a multiple of <code>d</code>, then it adds to the counter <code>count</code> by 1. </li> <li>And then, at the end, finally, it outputs the <code>count</code>, meaning the number of integers between 1 and K, that have their sum of digits as a multiple of D. </li> </ol> <p>Now, this code works just fine, but I am seeking to make it run for any number until 10^10000 in 1 second or less. </p> <p>EDIT: </p> <p>The actual problem that I am trying to solve can be found here: <a href="https://dmoj.ca/problem/dps" rel="nofollow noreferrer">Digit Sum - DM::OJ</a> </p> <p>Thank you. </p>
[]
[ { "body": "<p>There's probably a more efficient method, but I can't think of one at the moment. A few suggestions, though:</p>\n\n<ul>\n<li>Why do you have a badly-named variable <code>hello</code> that is only used once? I'd recommend inlining it.</li>\n<li>There's no need for parentheses around the condition for the <code>if</code> statement.</li>\n<li>There's no need to convert the <code>map</code> to a <code>list</code> before finding the <code>sum</code>.</li>\n<li>You could convert the loop into the sum of a generator expression.</li>\n<li>It's probably a good idea to convert your code to have a <code>main</code> function and an <code>if __name__ == '__main__'</code> guard.</li>\n</ul>\n\n<p>Result (not tested):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def perform_calculation(k, d):\n return sum(sum(map(int, str(i))) % d == 0 for i in range(1, k+1))\n\ndef main():\n k = int(input())\n d = int(input())\n\n print(perform_calculation(k, d))\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T16:37:02.310", "Id": "212707", "ParentId": "212701", "Score": "4" } }, { "body": "<p>Solomon has made some excellent review comments. I won’t duplicate those. </p>\n\n<p>If you want it to work for any number up to 10^1000 in under 1 second, you are going to have to get rid of testing every number in <code>range(1,k+1)</code>, and the <code>count += 1</code> counting of each number. </p>\n\n<p>Consider a sum of digits that has to be a multiple of <code>d=7</code>. The first number that satisfies that is <code>7</code>. To maintain the sum of 7, if we subtract 1 from the digit 7, we have to add one to another digit, such as a leading zero. <code>0+1,7-1</code> or <code>16</code>. If we repeat that, we get <code>25</code>. Adding 1 to the tens digit and subtracting 1 from the ones digit is the equivalent of simply adding 9. So we can quickly generate a few more values: 34, 43, 52, 61, and 70. Adding 9 again results in 79, who’s digit sum of 16, so we have to stop at 70. Still, that generated a few numbers. Specifically <code>(70-7)/9+1=8</code> numbers.</p>\n\n<p>14 is the next multiple of 7, and the smallest number with that digit sum is 59. Again, subtracting 1 from the ones digit, and adding 1 to the tens digit is simply adding 9, so we can generate 68, 77, 86, and 95. The next value is 104, who’s digit sum is only 5, so we have to stop at 95.</p>\n\n<p>Can you figure out a way to generate the first number in each series? Can you identify a stopping criteria? If so, you can directly count the number of numbers in that series with:</p>\n\n<pre><code> count += (last - first) / inc + 1\n</code></pre>\n\n<p>What about 3 digit numbers? 106 has a digit sum of 7, and 149 has a digit sum of 14. </p>\n\n<p>What other values of <code>inc</code> do you need? Can you add 1 to the hundreds digit and subtract 1 from the ones? How about adding 1 to the hundreds and subtracting 1 from the tens? Any others?</p>\n\n<hr>\n\n<p>The above will speed up the counting by computing series of numbers, and exploiting commonality. But it is getting way to complicated, as you have to break the series into groups by numbers of digits, and you can have up to 10000 digits.</p>\n\n<p>Perhaps a different approach is needed to determine all of the permutations of digits that result in the required sums.</p>\n\n<blockquote class=\"spoiler\">\n <p> Emphasis on permutations.</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T15:36:41.890", "Id": "212759", "ParentId": "212701", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T15:32:10.923", "Id": "212701", "Score": "3", "Tags": [ "python", "performance", "algorithm", "mathematics" ], "Title": "Finding the number of integers between 1 and K, who's sum of the digits is a multiple of D" }
212701