body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Here is a light command line I built with JavaScript. I would like to ask if there are many stupidities, bad code and such? The only test command right now is <code>add arg1 arg2</code> so writing <code>add 1 1</code> should get you <code>&gt;&gt;&gt; 2</code>. It will print <code>Command *** not found</code> with other commands than <code>add</code>. See the fiddle below.</p> <p><strong>jsfiddle.net</strong> <a href="http://jsfiddle.net/Nr2Am/26/" rel="nofollow">http://jsfiddle.net/Nr2Am/26/</a></p> <p><strong>JavaScript</strong></p> <pre><code>function cli_focus() { var cli = document.getElementById("commandline"); cli.focus(); } function arguments_to_array(args) { var arr = new Array(); for (var i=0; i&lt;args.lentgh; ++i) { arr[i] = args[i]; } return arr; } function cli_go(input) { var lines = input.value; var lines_arr = lines.split(/\n+/); var cmd = lines_arr[lines_arr.length-1]; cli_run(cmd); return false; } function cli_parse(cmd) { return cmd.split(/\s+/); } function cli_remove_blank_words(words) { while (words.length&gt;0 &amp;&amp; words[0]==="") { words = words.slice(1); } while (words.length&gt;0 &amp;&amp; words[words.length-1]==="") { words = words.slice(0, words.length-1); } return words; } function cli_run(cmd) { var words = cli_parse(cmd); words = cli_remove_blank_words(words); var last_word = null; for (var i=0; i&lt;words.length; ++i) { var func_name = words.slice(0, i+1).join("_"); if (window[func_name] === undefined) { break; } else { last_word = i; } } if (last_word===null || words.length===0) { document.getElementById('commandline').value = document.getElementById('commandline').value + '\n&gt;&gt;&gt; Command ' + words[0] + ' not found'; return; } var func_name = words.slice(0, last_word+1).join( "_" ); var func = window[func_name]; var args = words.slice(last_word+1); func.apply(this, args); } function add(a,b) { var result = parseInt(a)+parseInt(b); document.getElementById('commandline').value = document.getElementById('commandline').value + '\n&gt;&gt;&gt; ' + result; } </code></pre>
[]
[ { "body": "<p>Looks like <code>arguments_to_array()</code> can be removed.</p>\n\n<p>You may want to consider having <code>cli_parse()</code> call <code>cli_remove_blank_words()</code> rather than <code>cli_run()</code>.</p>\n\n<p>Also, depending on the direction you're going with the command line, you can probably simplify <code>cli_run()</code> in other ways. That long document.getElementById expression should probably be isolated in its own function, since it seems it's going to be used the same way every time for the most part. By doing <code>shift()</code> to the cmd array, you can get the function you want to call from that (and the remaining elements in the array are simply your args to that function). Then you can use a logical operator to check whether that function exists, otherwise call a function that handles errors and such.</p>\n\n<p>Here's how I'd do it:</p>\n\n<pre><code>function cli_parse(cmd) {\n return cli_remove_blank_words(cmd.split(/\\s+/));\n}\n\nfunction cli_run(cmd) {\n var words = cli_parse(cmd);\n var func_name = words.shift();\n var func = window[func_name] || window.cli_error;\n func.apply(this, words);\n}\n\nfunction cli_print(txt) {\n document.getElementById('commandline').value = document.getElementById('commandline').value + '\\n&gt;&gt;&gt; ' + txt; \n}\n\nfunction cli_error(error_info) {\n cli_print(\"Unknown command\");\n}\n\nfunction add(a,b) {\n var result = parseInt(a)+parseInt(b);\n cli_print(result); \n}\n</code></pre>\n\n<p>Although, I'd really say using a more object oriented approach would probably facilitate expansion easier, but this works fine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T11:17:52.663", "Id": "49126", "Score": "0", "body": "`cli_print` could be simplified to `document.getElementById('commandline').value += '\\n>>> ' + txt;`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T13:25:53.497", "Id": "28552", "ParentId": "28509", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T14:10:21.400", "Id": "28509", "Score": "1", "Tags": [ "javascript", "optimization" ], "Title": "Online command line JavaScript optimization" }
28509
<p>This plugin is initialized like so:</p> <pre><code>$("#calendar").ksdCalendar({ feedUrl: "http://www.kent.k12.wa.us/site/RSS.aspx?DomainID=275&amp;ModuleInstanceID=4937&amp;PageID=4334", elemHeight: 750 }); </code></pre> <p>I would like a review on the code, structure, or anything else that comes to mind. What this plugin does is take an RSS feed from JGFeed, parse the entries, then pass them into another calendar plugin which in turn builds and displays the calendar.</p> <pre><code>(function ( $, window, document, undefined ) { "use strict"; var Calendar = { init: function(options, elem) { this.options = $.extend( {}, this.options, options ); this.elem = $(elem); this.setupAjax(); this.getFeed(); return this; }, options: { feedUrl: "", elemHeight: 750 }, entries: [], getFeed: function() { var self = this; $.jGFeed(this.options.feedUrl, function (feeds) { if (!feeds) { return false; } $.extend(self.entries, feeds.entries); self.parseEntries(); }, 100); }, parseEntries: function() { //Rename to fit plugin requirements for (var i = 0; i &lt; this.entries.length; i++) { var entry = this.entries[i]; entry["allDay"] = false; //Rename entry["url"] = entry["link"]; delete entry["link"]; var position = entry.title.indexOf(' - '); if (position === -1) { //All day event entry.allDay = true; var space = entry.title.indexOf(" "), title = entry.title.substring(space + 1), firstHalf = entry.title.slice(0, space); //Start date, no time because it's all day event } else { var firstHalf = entry.title.slice(0, position), //Start date/time secondHalf = entry.title.substring(position + 3); if (secondHalf.indexOf("AM") !== -1) { var title = secondHalf.substring(secondHalf.indexOf("AM") + 3); //Title if has AM } else { var title = secondHalf.substring(secondHalf.indexOf("PM") + 3); //Title if has PM } secondHalf = secondHalf.slice(0, -(title.length + 1)); //End date/time } entry["start"] = Date.parse(firstHalf); entry["end"] = Date.parse(secondHalf); entry.title = title; }; this.setUpCalendar(); }, setUpCalendar: function() { this.elem.fullCalendar({ editable: false, weekends: true, header: { left: 'month basicDay', center: 'title', right: 'today prev, next' }, height: this.options.elemHeight, events: this.entries }); } }; if ( typeof Object.create !== 'function' ) { Object.create = function (o) { function F() {} F.prototype = o; return new F(); }; } $.fn.ksdCalendar = function( options ) { if (this.length) { return this.each(function() { var myCalendar = Object.create(Calendar); myCalendar.init(options, this); $.data(this, 'ksdCalendar', myCalendar); }); } }; })( jQuery, window, document ); </code></pre>
[]
[ { "body": "<p>This code looks good, I only have 2 minor items from a once over;</p>\n\n<ul>\n<li><p>I would have a constant for <code>-1</code> meaning an all day event</p>\n\n<pre><code>var ALL_DAY_EVENT = -1; // &lt;-- Declared somewhere on top\nif (position === ALL_DAY_EVENT) {\n ...\n</code></pre></li>\n<li><p>This:</p>\n\n<pre><code>if (secondHalf.indexOf(\"AM\") !== -1) {\n var title = secondHalf.substring(secondHalf.indexOf(\"AM\") + 3); //Title if has AM\n} else {\n var title = secondHalf.substring(secondHalf.indexOf(\"PM\") + 3); //Title if has PM\n}\n</code></pre>\n\n<p>Declares <code>title</code> with <code>var</code> twice, you should declare <code>title</code> only once, ideally on top before your loop. Also, there is some serious code repetition there. I would suggest something like:</p>\n\n<pre><code>//Declare meridiem and title somewhere higher prior to the loop\nmeridiem = ~secondHalf.indexOf(\"AM\") ? \"AM\" : \"PM\"; \ntitle = secondHalf.substring(secondHalf.indexOf(meridiem) + 3);\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-28T14:46:43.610", "Id": "48404", "ParentId": "28511", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T15:14:53.003", "Id": "28511", "Score": "2", "Tags": [ "javascript", "jquery", "datetime", "plugin", "rss" ], "Title": "RSS Feed Calendar Plugin" }
28511
<pre><code>$controller = new UserController(); if (isset($_POST['submitform'])) { $validated = false; $inputs = array ( 'username', 'email', 'password', 'repassword', 'password_f', 'repassword_f', 'display' ); $i = 0; foreach ($inputs as $key) { if (isset($_POST[$key]) &amp;&amp; !empty($_POST[$key])) { $i++; if ((int)$i == count($inputs)) { $validated = true; break; } else { $controller-&gt;error = ""; break; } } } if ($validated) { echo 2; } } </code></pre> <p>So let's overview the code.</p> <p>First we are checking if the form was submitted.</p> <p>Then we are creating a new <code>boolean $validated</code> and setting it <code>false</code> by default.</p> <p>Then we created our array with the <code>POST</code> names.</p> <p>Now the checking part, setting variable <code>int i</code> to <code>0</code> by default. Now we are looping through the array elements.</p> <p>Checking if the current <code>index</code> was set or not <code>empty</code>, if yes, <code>add +1 to int $i</code>.</p> <p>Once int <code>$i</code> hits the number of counted elements of our array, set <code>$validated</code> to <code>true</code>, and break out of the array, else parse error and break out.</p> <p>Then we are checking, if <code>bool $validated</code> is true, then echo 2.</p> <p><em><strong>Is it a good way of doing this? Is there any cleaner/better way?</em></strong></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T17:45:37.617", "Id": "44768", "Score": "1", "body": "I would discourage you from using flags. Don't set `$validated` in the first place, instead, when you need to, just call the desired function." } ]
[ { "body": "<p>I'd do this instead:</p>\n\n<pre><code>function validateForm() {\n if (!isset($_POST['submitform']))\n return false; // Maybe $controller-&gt;error = \"Something\"; as well?\n $inputs = array (\n 'username', 'email', 'password',\n 'repassword', 'password_f', 'repassword_f',\n 'display'\n );\n foreach ($inputs as $key)\n if (empty($_POST[$key]))\n {\n global $controller;\n $controller-&gt;error = \"\";\n return false;\n }\n return true;\n}\n...\nif (valudateForm()) {\n echo 2;\n} else {\n // Form data not ok\n}\n</code></pre>\n\n<p>Seems cleaner, no flags, no counting array elements, validation has its own function,...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T07:40:27.913", "Id": "44809", "Score": "0", "body": "Although your answer is pretty close to what I would do, I can't upvote it with the `global` in it :) (Maybe just return the keys of the invalid input and build the error message in the controller)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T08:45:39.347", "Id": "44814", "Score": "1", "body": "global is good if used properly. Look at Drupal core. They use global all over the place, but that doesn't make it bad code..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T09:21:26.320", "Id": "44815", "Score": "0", "body": "@mnhg Global variables can make all kinds of chaos, I agree. However, the above doesn't seem like a reusable code, but rather a single script, in which `$controller` seems like something common for the whole site. I see no problem `global`-ing something in such case, and I believe that nothing sould ever be discarded as \"generally wrong\" without addressing the exact situation. If you have a problem with `global` in here, I'd love to hear it (possibly learning something useful)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T07:22:33.120", "Id": "44909", "Score": "0", "body": "@Vedran Nip it in the bud. It is unnecessarily hard to write isolated test with globals and do be sure to don't mess thinks up with new tests or a change to a global. This is no local script, but a web page, so no need for hacking." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T07:29:43.353", "Id": "44911", "Score": "0", "body": "@Pinoniq I'm not familiar with Drupal in detail. Do you have any articles about testing-best-practice in Drupal in relation to globals?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T15:31:10.793", "Id": "44994", "Score": "0", "body": "Anyone mentioning Drupal as any kind of code quality measurement has no clue what they're talking about. Not only is Drupal one of the worst applications ever developed, it's notoriously slow and awful to use. Using `global` is always a bad idea, without exception. You'll use it once, then twice, then a next guy joins in and you have a nice mess. If you require a variable / object that exists outside the scope of a function, pass it along as a parameter. It's much cleaner and easier to understand where it came from." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T16:01:06.067", "Id": "44999", "Score": "0", "body": "So, basically, `global` is bad because you cannot control yourself to use it only when it really makes sense? For example, if a PHP script is a part of a web site never to be included anywhere else, why would I pass a PDO object all the time? I'd `global` it and use it, no more different than superglobals like `$_POST` (apart from them not needing `global`). And the above `$controller` seems to be exactly that kind of variable. If it's not, I agree that the OP should pass it as an argument, but I will not diss anything just because some programmers cannot make a proper per-case judgement." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T22:29:48.780", "Id": "28523", "ParentId": "28515", "Score": "1" } }, { "body": "<p>First, it's not a real validation here. The check is: are all required fields filled with some value? Please notice that all modern browsers can use the 'required' attribute in formfields and will not post a form while not all required fields are filled. But double checking server-side is of course always good practice.\nPlease, keep functions as clean as possible. They only have to do <strong>one</strong> thing. So: no error-messages in the function etc. Only return true or false. That way, you can re-use your function. So I think this simple function will do just fine.</p>\n\n<pre><code>&lt;?php\n/**\n * Check if all required fields are filled\n * \n * @param array $post the POST array\n * @param array $fieldsArray an array with values to check\n * @return boolean\n */\nfunction filledRequiredFields($post, $fieldsArray)\n{\n foreach($fieldsArray as $key)\n {\n if(empty($post[$key]))\n {\n return false;\n }\n }\n return true;\n}\n\nif ($_SERVER['REQUEST_METHOD'] === 'POST')\n{\n $inputs = array(\n 'username', 'email', 'password',\n 'repassword', 'password_f', 'repassword_f',\n 'display'\n );\n\n if (filledRequiredFields($_POST, $inputs))\n {\n echo 2;\n }\n else \n {\n //etc.\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T13:23:37.893", "Id": "28828", "ParentId": "28515", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T17:22:52.673", "Id": "28515", "Score": "0", "Tags": [ "php" ], "Title": "Better way of handling isset/!empty?" }
28515
<p>I need to crawl web contents from some websites and then do some processing. Note that this is a small application, so the dataset is relatively small (need to crawl about 30,000 pages every time, once a week). The problem is that I can't start too many threads to crawl the pages at the same time. Otherwise my IP will be recognized unusual and will be blocked. </p> <p>So, I create a class, called <code>CrawlingService</code>. It's designed to encapsulate these things: </p> <ul> <li>Start some threads to crawl the web content</li> <li>Control the waiting time after a page is crawled (a thread need to "have a rest" after a page is crawled to prevent the app from being blocked by the server)</li> <li>Notify other classes that a webpage is crawled</li> <li>Automatically retry N times when fail to crawl a page (most are "Timeout" errors)</li> <li>When an error occurs (99% is timeout), all threads need to pause for a while. Because the "Timeout" is mostly caused by server busy.</li> </ul> <p>The following is my implementation. </p> <ul> <li>The main class is <code>CrawlingService</code> which is already mentioned above. </li> <li><code>ITaskRestStrategy.Duration()</code> method is used to return the information about how long a thread need to wait for after a page is crawled. </li> <li>The <code>AbstractHttpClient</code> is used to make HTTP requests, not important.</li> <li>Let's ignore argument null checking</li> </ul> <p><strong>What I want to know</strong></p> <ul> <li>Is the multi-threading implementation correct? (Not good at this)</li> <li>Can I improve the multi-threading implementation by using a better approach?</li> <li>Can I improve the design of these classes?</li> <li>Better naming for the classes/methods/variables? (Not quite good at English)</li> </ul> <p><strong>WebResource.cs</strong></p> <pre><code>/// &lt;summary&gt; /// Represents a webpage to be crawled. /// &lt;/summary&gt; public class WebResource { public string Url { get; private set; } public Encoding Encoding { get; private set; } public string Content { get; set; } // Ignore the constructor } </code></pre> <p><strong>CrawlingEventArgs.cs</strong></p> <pre><code>public class CrawlingEventArgs : EventArgs { public WebResource Resource { get; private set; } public Exception Exception { get; private set; } // Ignore the constructor } </code></pre> <p><strong>CrawlingService.cs</strong></p> <pre><code>public class CrawlingService { static readonly Logger _log = LogManager.GetCurrentClassLogger(); private ConcurrentQueue&lt;QueueItem&gt; _queue = new ConcurrentQueue&lt;QueueItem&gt;(); private AbstractHttpClient _httpClient; // the strategy for "having rest" after a page is crawled private ITaskRestStrategy _itemRestStrategy; // the strategy for "having rest" after an error occurs private ITaskRestStrategy _errorRestStrategy; // this is used to control the "pause" of all threads private ManualResetEventSlim _continueEvent; private readonly object _startLock = new object(); // this is used for the Wait method called by client code private int _totalWorkingThreads; private ManualResetEventSlim _exitEvent; public event EventHandler&lt;CralwingEventArgs&gt; ItemSucceeded; public event EventHandler&lt;CralwingEventArgs&gt; ItemFailed; public bool IsRunning { get; private set; } /// &lt;summary&gt; /// The maximum number of threads can be run in parallel. /// &lt;/summary&gt; public int MaxDegreeOfParallelism { get; private set; } /// &lt;summary&gt; /// The maximum allowed retries when failed to crawl a page. /// &lt;/summary&gt; public int MaxRetriesForEachItem { get; private set; } public CralwingService() : this(RandomTaskRestStrategy.FromSeconds(1, 2, 3, 4, 5), new SimpleTaskRestStrategy(TimeSpan.FromSeconds(15))) { } public CralwingService( ITaskRestStrategy itemRestStrategy, ITaskRestStrategy errorRestStrategy) : this(itemRestStrategy, errorRestStrategy, 2, 3, new DefaultHttpClient()) { } public CralwingService( ITaskRestStrategy itemRestStrategy, ITaskRestStrategy errorRestStrategy, int maxDegreeOfParallelism, int maxRetriesForEachItem, AbstractHttpClient httpClient) { _httpClient = httpClient; _itemRestStrategy = itemRestStrategy; _errorRestStrategy = errorRestStrategy; MaxDegreeOfParallelism = maxDegreeOfParallelism; MaxRetriesForEachItem = maxRetriesForEachItem; } /// &lt;summary&gt; /// Add webpages to the crawling queue. /// &lt;/summary&gt; public void Add(IEnumerable&lt;WebResource&gt; resouces) { lock (_startLock) { if (IsRunning) throw new InvalidOperationException("Cannot add new items after the service is started."); foreach (var info in resouces) { _queue.Enqueue(new QueueItem { ResourceInfo = info }); } } } /// &lt;summary&gt; /// Starts the background crawling threads. /// &lt;/summary&gt; public bool Start() { if (IsRunning) { return false; } lock (_startLock) { if (IsRunning) { return false; } IsRunning = true; _continueEvent = new ManualResetEventSlim(true); _totalWorkingThreads = MaxDegreeOfParallelism; for (var i = 0; i &lt; MaxDegreeOfParallelism; i++) { StartProcessingNextItem(); } } return true; } /// &lt;summary&gt; /// Wait until all pages are crawled. /// &lt;/summary&gt; public void Wait() { if (_exitEvent == null) { _exitEvent = new ManualResetEventSlim(); } _exitEvent.Wait(); OnExit(); } private void StartProcessingNextItem() { _continueEvent.Wait(); QueueItem item = null; if (_queue.TryDequeue(out item)) { var resource = item.ResourceInfo; var task = _httpClient.GetAsync(resource.Url, resource.Encoding) .ContinueWith(t =&gt; { if (t.Exception != null) { // If error occuors, all threads need to pause and "have a rest" _continueEvent.Reset(); // Add the failed item back to the crawling queue if it's still retryable if (item.TotalRetries &lt; MaxRetriesForEachItem) { item.TotalRetries++; _queue.Enqueue(item); } else { OnItemFailed(resource, t.Exception); } Thread.Sleep(_errorRestStrategy.Duration()); // Notify all threads to continue after the "rest" _continueEvent.Set(); } else { OnItemSucceeded(resource, t.Result); // Have a rest also after an item is processed successfully Thread.Sleep(_itemRestStrategy.Duration()); } // Finish processing one page, so now can start processing next page StartProcessingNextItem(); }); } else { var totalWorkingThreads = Interlocked.Decrement(ref _totalWorkingThreads); if (totalWorkingThreads == 0) { // Now I'm the only thread still executing if (_exitEvent != null) { _exitEvent.Set(); } else { OnExit(); } } } } private void OnItemFailed(WebResource resource, Exception exception) { if (ItemFailed != null) { SafeExecuteAsync(() =&gt; { ItemFailed(this, new CralwingEventArgs(resource, exception)); }, "Error invoking ItemFailed event handlers."); } } private void OnItemSucceeded(WebResource resource, string content) { if (ItemSucceeded != null) { resource.Content = content; SafeExecuteAsync(() =&gt; { ItemSucceeded(this, new CralwingEventArgs(resource)); }, "Error invoking ItemSucceeded event handlers."); } } private void SafeExecuteAsync(Action action, string errorMessage) { Task.Factory.StartNew(() =&gt; { try { action(); } catch (Exception ex) { _log.ErrorException(UserReference.System(), ex, errorMessage); } }); } // Cleanup resources private void OnExit() { _continueEvent.Dispose(); _continueEvent = null; if (_exitEvent != null) { _exitEvent.Dispose(); _exitEvent = null; } IsRunning = false; } class QueueItem { public WebResource ResourceInfo = null; public int TotalRetries = 0; } } public interface ITaskRestStrategy { TimeSpan Duration(); } public class SimpleTaskRestStrategy : ITaskRestStrategy { private TimeSpan _duration; public SimpleTaskRestStrategy(TimeSpan duration) { _duration = duration; } public TimeSpan Duration() { return _duration; } } public class RandomTaskRestStrategy : ITaskRestStrategy { static readonly Random _random = new Random(); private TimeSpan[] _durations; public RandomTaskRestStrategy(TimeSpan[] durations) { Require.NotNull(durations, "durations"); Require.That(durations.Length &gt; 0, "'durations' must have one item at least."); _durations = durations; } public static RandomTaskRestStrategy FromSeconds(params int[] seconds) { var durations = new TimeSpan[seconds.Length]; for (var i = 0; i &lt; durations.Length; i++) { durations[i] = TimeSpan.FromSeconds(seconds[i]); } return new RandomTaskRestStrategy(durations); } public TimeSpan Duration() { var index = _random.Next(0, _durations.Length); return _durations[index]; } } </code></pre> <p><strong>Found Issues</strong></p> <ol> <li><p>The "Wait" method call might block forever:</p> <pre><code>service.Start(); // Short tasks might all complete here. // In this case, calling Wait will block forever service.Wait(); </code></pre></li> <li><p>The <code>_startLock</code> is useless</p></li> <li><p><code>System.Random</code> is not thread safe</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T18:35:12.093", "Id": "44777", "Score": "1", "body": "I have several programs doing the same thing and also avoiding DOS detection on the server. For throttling, I use a Semaphore; and for downloading and sleeping I use a Task<T> instance that has a ContinueWith method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T20:42:39.543", "Id": "44882", "Score": "2", "body": "Is it a .NET 4.0 or 4.5 (`async`/`await` can reduce complexity of the code)? Do you crawl pages from one web site or multiple sites (affects how cool off period should be implemented)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T20:52:14.673", "Id": "44884", "Score": "0", "body": "@almaz, was that q for Mouhong or me? My stuff is 4.5 and uses async and Reactive Extensions and the Concurrent Collection namespace. The crawling strategy is implemented via polymorphism, but that's actually a separate question altogether :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T21:45:38.997", "Id": "44890", "Score": "0", "body": "@GarryVass my question was to original author" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T02:10:25.013", "Id": "44895", "Score": "0", "body": "@almaz .NET 4.0. I crawl pages from one website, once a week. Each time it need to crawl 30,000 pages around. Cos the server will detect DOS attack. So I need to \"slow down\" the crawl speed. Yesterday I made some change to let it randomly pick a proxy server to crawl the page. But that's not important for the code review. Any feedback is welcome: scalability, robustness, code quality, etc :P Thanks" } ]
[ { "body": "<p>Generally, very well written code. I just have a few suggestions:</p>\n\n<ol>\n<li>In the <code>Start</code> method, I understand why, but I don't like that there are two calls to check if the service is running. It feels kind of redundant, and I don't think you'll get a speed increase by short-circuiting the lock.</li>\n<li><p>I would rather create and throw customized <code>Exception</code> classes rather than using the built-in one.</p>\n\n<pre><code>throw new ServiceIsAlreadyRunningException()\n</code></pre>\n\n<p>is less confusing than:</p>\n\n<pre><code>InvalidOperationException(\"Cannot add new items after the service is started.\")\n</code></pre></li>\n<li>I would change the IsRunning property to use an <code>enum</code>. This will allow the addition of more states in the future (<code>Starting</code>, <code>Running</code>, <code>Stopped</code>, <code>ShuttingDown</code>, ...)</li>\n<li>I'm not sure what version of .Net you are using, but look into the <code>await</code> keyword. I found it makes my code flow so much better and makes it easier to follow when using threads.</li>\n<li><p>In your constructors, check the injected classes for <code>null</code>. This will save you problems when trying to use them later:</p>\n\n<pre><code>public CralwingService(\n ITaskRestStrategy itemRestStrategy,\n ITaskRestStrategy errorRestStrategy,\n int maxDegreeOfParallelism,\n int maxRetriesForEachItem,\n AbstractHttpClient httpClient)\n{\n\n if (itemRestStrategy == null) throw new ArgumentNullException(\"itemRestStrategy\");\n // same for all other reference types injected\n\n // rest of constructor code\n}\n</code></pre></li>\n</ol>\n\n<p>Overall, this was easy code to read, and very well written, which I like. The suggestions I've pointed out will take it from good code to excellent code, in my opinion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T03:17:26.940", "Id": "76643", "Score": "0", "body": "Great input, thanks! I'm not using C# 5, so no \"await\" keyword to use. In my real code, I'll check the constructor arguments. Here I removed them to save space :P" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T22:13:24.723", "Id": "44207", "ParentId": "28517", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T17:54:16.907", "Id": "28517", "Score": "6", "Tags": [ "c#", "multithreading", "thread-safety" ], "Title": "Class to encapsulate and manage multiple background web crawlers" }
28517
<p>I have a project from my college. I'm making a site which will display different quotations each time the page is loaded. I use the following code:</p> <pre><code>$con = mysql_connect("localhost","root",""); if (!$con){ die('Could not connect: ' . mysql_error()); } mysql_select_db("xlsx_db", $con); $result = mysql_query("SELECT * FROM sheet1 ORDER BY RAND() LIMIT 1"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } $row = mysql_fetch_array($result); echo "&lt;b&gt;Quote: &lt;/b&gt;"; echo $row['quote']."&lt;br&gt;"; echo $row['by']."&lt;br&gt;"; ?&gt; </code></pre> <p>All works fine. But my teacher told me to make the text link-able. So that if anyone copy that link of the quote, that case, he can pest the code on the browser and can see that quote again.</p> <p>Could anyone please help me with this task? Any kind of help is really appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T13:52:08.613", "Id": "44778", "Score": "2", "body": "Having obtained a random quote ID from the database (`ORDER BY RAND()` will scale very poorly, by the way), you could redirect the browser to a page e.g. `?quote_id=12345` and then fetch/display the specified quote details. Anyone going directly to that URL will skip the first random bit and jump directly into fetching of the specified quote." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T13:48:25.963", "Id": "44827", "Score": "0", "body": "**NEVER** use `ORDER BY RAND()` in this context: http://stackoverflow.com/a/9934740/727208 . Also, [**please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [**warning**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://j.mp/PoWehJ)." } ]
[ { "body": "<p>Your link should look like this:</p>\n\n<pre><code>&lt;a href=\"http://www.yoursite.com/quotes?q_id=123\"&gt;Permalink&lt;/a&gt;\n</code></pre>\n\n<p>In your php code, you can grab the selected quote id like this:</p>\n\n<pre><code>$q_id = $_GET['q_id'];\n</code></pre>\n\n<p>To check if the q_id has been set:</p>\n\n<pre><code>if (array_key_exists('q_id', $_GET)) {\n // the q_id was specified\n}\n</code></pre>\n\n<p>To check that the q_id is numeric (important to do before plugging it into a mysql query):</p>\n\n<pre><code>if (is_numeric($_GET['q_id'])) {\n // q_id is a number\n}\n</code></pre>\n\n<p>To fetch that single quote:</p>\n\n<pre><code>$result = mysql_query(\"SELECT * FROM sheet1 WHERE q_id = \" . $q_id);\n</code></pre>\n\n<h3>Deprecation of mysql_ functions</h3>\n\n<blockquote>\n <p>PHP functions that start with <code>mysql_</code> have been deprecated as of PHP 5.5.0. If you are in a position to do so, please consider updating your code to use the <a href=\"http://www.php.net/manual/en/book.mysqli.php\" rel=\"nofollow\">MySQLi</a> or <a href=\"http://www.php.net/manual/en/ref.pdo-mysql.php\" rel=\"nofollow\">PDO</a> extensions instead.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T14:06:52.883", "Id": "44779", "Score": "0", "body": "+1 I prefer this as a refresh will still produce a random quote __and__ a link to return to that page." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T13:56:00.753", "Id": "28520", "ParentId": "28519", "Score": "1" } }, { "body": "<p>you'd need an ID for each quote in the database and add ?id=1245 after your domain and page</p>\n\n<pre><code>if($_GET['id']){\n$result = mysql_query(\"SELECT * FROM sheet1 WHERE id \".$_GET['id'].\"\");\n} else {\n $result = mysql_query(\"SELECT * FROM sheet1 ORDER BY RAND() LIMIT 1\");\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T14:08:42.690", "Id": "44780", "Score": "0", "body": "`www.yoursite.com/quotes?id=;DROP TABLE sheet1;--`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T14:18:43.403", "Id": "44781", "Score": "0", "body": "I use PDO prepared statement i kinda forgot about that" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T14:01:33.373", "Id": "28521", "ParentId": "28519", "Score": "0" } }, { "body": "<p>Here's a full solution from @eggyals comment</p>\n\n<p>Assuming quote_id is the index on the sheet1 table</p>\n\n<pre><code>&lt;?php\n$con = mysql_connect(\"localhost\",\"root\",\"\");\nif (!$con){\ndie('Could not connect: ' . mysql_error());\n}\nmysql_select_db(\"xlsx_db\", $con);\n//get quote from url\n$quote_id=intval(urldecode($_GET['quote_id']));\n// if not set get a random one\nif($quote_id==0)\n{\n $result = mysql_query(\"SELECT * FROM sheet1 ORDER BY RAND() LIMIT 1\") or die('Could not run query: ' . mysql_error());\n $row = mysql_fetch_array($result);\n $get=$_GET;\n $get['quote_id']=$row['quote_id'];\n // jump to page with link in url, so it can be copied\n header(\"Location:\".$_SERVER['PHP_SELF'].'?'.http_build_query($get));\n exit();\n}\n// get the specified quote\n$result = mysql_query(\"SELECT * FROM sheet1 WHERE quote_id=\".intval($quote_id).\" LIMIT 1\") or die('Could not run query: ' . mysql_error());\n$row = mysql_fetch_array($result);\necho \"&lt;b&gt;Quote: &lt;/b&gt;\";\necho $row['quote'].\"&lt;br&gt;\";\necho $row['by'].\"&lt;br&gt;\";\n?&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T17:38:22.197", "Id": "44782", "Score": "0", "body": "Hi, thank you very much for the answer. Having a problem. My code returning with an id that is 0. I set the column \"quote_id\" as index on mysql database. but still show it is 0. and also I'm facing problem of \"undefined index: quote_id\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T15:25:38.653", "Id": "44783", "Score": "0", "body": "in that case you should `$quote_id=0; if(isset($_GET['quote_id'])) $quote_id=intval(urldecode($_GET['quote_id']));` __BUT__ Joe Frambach's answer is better!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T14:02:10.657", "Id": "28522", "ParentId": "28519", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T13:48:14.677", "Id": "28519", "Score": "0", "Tags": [ "php", "mysql", "random" ], "Title": "RAND() with a generated link" }
28519
<p>This is my attempt at <a href="http://projecteuler.net/problem=12" rel="nofollow" title="Problem 12">problem 12 from Project Euler</a>. However, my code freezes my old, linux computer when I run it. I've only got 512MB of RAM and an old Intel Core 2 Duo processor on my machine which, I assume, is why it can't run the code.</p> <p>Is there a way to optimize this code without using up too much resources?</p> <pre><code>#!/bin/python def nth_triangle_number(nth): """ Sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. """ return sum([i for i in range(nth+1)]) def get_number_of_factors(num): quantity = 0 for i in range(1, int(num/2)+1): # I think the problem lies here in range() if not num % i: # BTW, using math.sqrt() produces the wrong quantity += 1 # answer for smaller numbers. I don't know why. return quantity + 1 # Added 1 to count for num (as in 1 * num) def get_triangle_number(divisors): """ Find the triangle number with the given amount of divisors """ i = 1 while get_number_of_factors(nth_triangle_number(i)) &lt;= divisors: i += 1 return nth_triangle_number(i) if __name__ == '__main__': number_of_divisors = 500 print "Answer found: ", get_triangle_number(number_of_divisors) </code></pre> <p>I've tried initializing get_triangle_number(), i, at higher values, but it didn't seem to help. I believe the problem is with get_number_of_factors(). I had originally stored all the factors of a given integer into a list then compared its length to number_of_divisors. I figured counting each integer that satisfied the condition would save some resources.</p> <p>The code does run properly and produces the correct answer when I tested the example provided on <a href="http://projecteuler.net/problem=12" rel="nofollow" title="Problem 12">Project Euler</a> and the following values:</p> <pre><code> number_of_divisors = 5 # Runs properly and produces correct answer number_of_divisors = 50 # Runs properly and " " number_of_divisors = 150 # Runs properly and " " number_of_divisors = 200 # Crash </code></pre>
[]
[ { "body": "<p>First, you can easily find the bottleneck in your code by running it with the profiler (ran with <code>number_of_divisors = 100</code>):</p>\n\n<pre><code>~&gt; python -m cProfile t.py\nAnswer found: 73920\n 1926 function calls in 0.522 seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.522 0.522 t.py:1(&lt;module&gt;)\n 385 0.006 0.000 0.008 0.000 t.py:1(nth_triangle_number)\n 1 0.000 0.000 0.522 0.522 t.py:13(get_triangle_number)\n 384 0.472 0.001 0.514 0.001 t.py:6(get_number_of_factors)\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n 769 0.043 0.000 0.043 0.000 {range}\n 385 0.001 0.000 0.001 0.000 {sum}\n</code></pre>\n\n<p>You can immediately see that:</p>\n\n<ol>\n<li>Indeed, <code>get_number_of_factors()</code> slows everything down;</li>\n<li>You can slightly optimize things by replacing <code>range</code> with <code>xrange</code> (which does not create a list).</li>\n</ol>\n\n<p>In your case <code>get_number_of_factors()</code> is a good example of a function that requires algorithmic optimization. Currently it has O(N) complexity. As you correctly guessed, iterating only till <code>sqrt(num)</code> will make it faster:</p>\n\n<pre><code>def get_number_of_factors(num):\n\n limit = math.sqrt(num)\n int_sqrt = int(round(limit))\n\n if int_sqrt ** 2 == num:\n int_limit = int_sqrt\n quantity = 1\n else:\n int_limit = int(limit) + 1\n quantity = 0\n\n for i in xrange(1, int_limit):\n if not num % i:\n quantity += 2\n\n return quantity\n</code></pre>\n\n<p>Some highlights:</p>\n\n<ol>\n<li><code>math.sqrt</code> returns a float, so if you want to be extra-safe, you need to convert it to integer properly (if <code>sqrt(4)</code> gives you <code>3.9999999</code>, just <code>int()</code> will produce <code>3</code>).</li>\n<li>When you are iterating to the square root, each factor you found stands for two factors: <code>i</code> and <code>num / i</code>.</li>\n<li>But you do not want to include the root itself, because if <code>num</code> is a perfect root, you only need to count <code>sqrt(num)</code> once.</li>\n</ol>\n\n<p>This makes your algorithm run in O(sqrt(N)). \n<strong>Edit</strong>: if you want even more performance, you can try to implement <a href=\"http://en.wikipedia.org/wiki/General_number_field_sieve\" rel=\"nofollow\">number field sieve</a>.</p>\n\n<p>To add more performance, you can replace the direct sum in <code>nth_triangle_number()</code> with a known formula for arithmetic progression.\nThe result is:</p>\n\n<pre><code>import math\n\ndef nth_triangle_number(nth):\n \"\"\" Sequence of triangle numbers is generated by adding the natural numbers.\n So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.\n Using the fact that 1 + ... + n = n * (n + 1) / 2\n \"\"\"\n return nth * (nth + 1) / 2\n\ndef get_number_of_factors(num):\n\n limit = math.sqrt(num)\n int_sqrt = int(round(limit))\n\n if int_sqrt ** 2 == num:\n int_limit = int_sqrt\n quantity = 1\n else:\n int_limit = int(limit) + 1\n quantity = 0\n\n for i in xrange(1, int_limit):\n if not num % i:\n quantity += 2\n\n return quantity\n\ndef get_triangle_number(divisors):\n \"\"\" Find the triangle number with the given amount of divisors \"\"\"\n i = 1\n while get_number_of_factors(nth_triangle_number(i)) &lt;= divisors:\n i += 1\n\n return nth_triangle_number(i)\n\nif __name__ == '__main__':\n number_of_divisors = 100\n print \"Answer found: \", get_triangle_number(number_of_divisors)\n</code></pre>\n\n<p>And it runs much faster now. For <code>100</code>:</p>\n\n<pre><code>~&gt; python -m cProfile t.py \nAnswer found: 73920\n 1540 function calls in 0.007 seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.007 0.007 t.py:1(&lt;module&gt;)\n 384 0.006 0.000 0.006 0.000 t.py:10(get_number_of_factors)\n 1 0.000 0.000 0.006 0.006 t.py:28(get_triangle_number)\n 385 0.000 0.000 0.000 0.000 t.py:3(nth_triangle_number)\n 384 0.000 0.000 0.000 0.000 {math.sqrt}\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n 384 0.000 0.000 0.000 0.000 {round}\n</code></pre>\n\n<p>And for <code>500</code>:</p>\n\n<pre><code>~&gt; python -m cProfile t.py \nAnswer found: 76576500\n 49504 function calls in 5.364 seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 5.364 5.364 t.py:1(&lt;module&gt;)\n 12375 5.342 0.000 5.349 0.000 t.py:10(get_number_of_factors)\n 1 0.010 0.010 5.363 5.363 t.py:28(get_triangle_number)\n 12376 0.005 0.000 0.005 0.000 t.py:3(nth_triangle_number)\n 12375 0.003 0.000 0.003 0.000 {math.sqrt}\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n 12375 0.004 0.000 0.004 0.000 {round}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T14:22:13.387", "Id": "44829", "Score": "1", "body": "Excellent! So much useful information in your review! I especially like the algorithms you've introduced. I'm at the end my first year in my CS course and I have yet to explore this stuff. Thanks for the head start!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T02:41:35.683", "Id": "28533", "ParentId": "28527", "Score": "2" } } ]
{ "AcceptedAnswerId": "28533", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T00:40:23.217", "Id": "28527", "Score": "1", "Tags": [ "python", "project-euler" ], "Title": "Simple code that finds number of factors crashes my computer. Is there a workaround for a large number?" }
28527
<p>Consider (simplified)</p> <pre><code>low_count = 0 high_count = 0 high = 10 low = 5 value = 2 </code></pre> <p>What is a clean way to check a number <code>value</code> versus a min <code>low</code> and a max <code>high</code>, such that if <code>value</code> is below <code>low</code> <code>low_count</code> increments, and if <code>value</code> is above <code>high</code> <code>high_count</code> increments? Currently I have (code snippet)</p> <pre><code> high_count = 0 low_count = 0 low = spec_df['Lower'][i] high = spec_df['Upper'][i] #Calculate results above/below limit for result in site_results: if result&lt;low: low_count+=1 else: if result&gt;high: high_count+=1 </code></pre> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T00:39:47.417", "Id": "44789", "Score": "4", "body": "Use `elif` instead of `else:\\nif`." } ]
[ { "body": "<p>The pythonic way would be:</p>\n\n<pre><code> for result in site_results:\n if result&lt;low:\n low_count+=1\n elif result&gt;high:\n high_count+=1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T00:45:26.283", "Id": "44790", "Score": "5", "body": "Truly pythonic code would follow PEP8, particularly [with regards to spacing](http://www.python.org/dev/peps/pep-0008/#other-recommendations)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T00:41:00.630", "Id": "28529", "ParentId": "28528", "Score": "0" } }, { "body": "<p>Seems pretty clean. I would edit the following:</p>\n\n<pre><code>elif result&gt;high:\n high_count+=1\n</code></pre>\n\n<p>Source: <a href=\"http://docs.python.org/2/tutorial/controlflow.html\" rel=\"nofollow\">http://docs.python.org/2/tutorial/controlflow.html</a><br>\nIs the code not working for you or are you just looking for a better way?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T00:52:45.690", "Id": "44791", "Score": "1", "body": "There is no `elseif` in Python. It's `elif`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T01:02:25.297", "Id": "44795", "Score": "0", "body": "Right you are, good eye! Edited." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T00:47:17.947", "Id": "28530", "ParentId": "28528", "Score": "1" } }, { "body": "<p>For a more complex case, I'd write a function and use a <code>Counter</code>. For example:</p>\n\n<pre><code>def categorize(low, high):\n def func(i):\n if i &lt; low:\n return 'low'\n elif i &gt; high:\n return 'high'\n else:\n return 'middle'\n return func\n\nsite_results = list(range(20))\n\ncounts = collections.Counter(map(categorize(5, 10), site_results))\nprint(counts['high'], counts['low'])\n</code></pre>\n\n<p>But for a trivial case like this, that would be silly. Other than tenstar's/minitech's suggestions, I wouldn't do anything different.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T00:53:28.637", "Id": "44792", "Score": "0", "body": "Wow - I was playing with: `print Counter({-1: 'low', 1: 'high'}.get(cmp(result, low), 'eq') for result in site_results)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T01:00:24.297", "Id": "44794", "Score": "0", "body": "@JonClements: If you want to one-liner-ize it, you'd need something like `(cmp(result, low) + cmp(result, high)) // 2`, which I think goes way beyond the bounds of readability…" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T00:52:32.487", "Id": "28531", "ParentId": "28528", "Score": "0" } }, { "body": "<p>I would write it as</p>\n\n<pre><code>low_count = sum(map(lambda x: x &lt; low, site_results))\nhigh_count = sum(map(lambda x: x &gt; high, site_results))\n</code></pre>\n\n<p>but admit I'm spoiled by Haskell.</p>\n\n<p><strong>Edit</strong>: As suggested by @Nick Burns, using list comprehension will make it even clearer:</p>\n\n<pre><code>low_count = sum(x &lt; low for x in site_results)\nhigh_count = sum(x &gt; high for x in site_results)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T03:54:16.710", "Id": "44796", "Score": "1", "body": "+1 - I agree that this is far more pythonic in this example. However, would probably use a simple generator inside sum: `sum(x for x in site_results if x < low)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T04:19:15.603", "Id": "44803", "Score": "1", "body": "I agree that the list comprehension is even clearer, but I believe you meant ``len``, not ``sum`` (since the count of low-value elements is needed); it will also require wrapping the comprehension in list, since you can't take ``len`` of a generator. Alternatively, you can write ``sum(x < low for x in site_results)``" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T04:36:57.300", "Id": "44804", "Score": "0", "body": "sorry -good point. This was a typo, meant to read: `sum(1 for x in site_results if x < low)` . I which case, no need for a list :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T17:28:48.233", "Id": "44853", "Score": "0", "body": "wouldn't this code be poor performing once you get a huge number of items in `site_results`? I'm thinking this is four linear, a.k.a. `O(n)`, operations, since `sum` and `map` are `O(n)`...is this incorrect?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T00:13:18.850", "Id": "44894", "Score": "2", "body": "@omouse: not four, but only two, since ``map`` or list comprehensions return iterators, not lists. Yes, in my solution technically there will be more additions (you will add ``False`` values too), but @Nick's solution does not have this drawback. Finally, it's still O(N), same as the original code, and in the very unlikely event the different coefficient matters, it will be picked up during profiling. I prefer to optimize for humans first." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T01:48:15.120", "Id": "28532", "ParentId": "28528", "Score": "3" } }, { "body": "<p>You can make use of the fact that Python can interpret boolean values as integers:</p>\n\n<pre><code>for result in site_results:\n low_count += result &lt; low\n high_count += result &gt; high\n</code></pre>\n\n<p>If those conditions evaluate to <code>True</code>, this will add <code>1</code> to the counts, otherwise <code>0</code>. This is the same principle as used in the list comprehensions by Bogdan and Nick Burns:</p>\n\n<pre><code>high_count = sum(result &gt; high for result in site_results)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T08:21:48.877", "Id": "28542", "ParentId": "28528", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T00:38:14.367", "Id": "28528", "Score": "2", "Tags": [ "python" ], "Title": "Python Clean way to get whether a number is above/below two values and increment accordingly" }
28528
<p>Sometimes I need to ensure that some references won't be processed while examination from the associated <code>ReferenceQueue</code>. Generally at those moments I don't know reachability status of the referent.</p> <p>The only way I've came up with:</p> <pre><code>class MyReference&lt;V&gt; extends SoftReference&lt;V&gt; { private boolean active = true; public MyReference(V referent, ReferenceQueue&lt;? super V&gt; queue) { super(referent, queue); } public void disable() { active = false; } public boolean isActive() { return active; } } // examination Reference&lt;? extends V&gt; ref; while ((ref = referenceQueue.poll()) != null) { @SuppressWarnings("unchecked") MyReference&lt;V&gt; myRef = (MyReference&lt;V&gt;) ref; if (myRef.isActive()) { // process ref } } </code></pre> <p>Is this the right approach?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T03:57:34.457", "Id": "44857", "Score": "0", "body": "This is the best way I can think of to do it." } ]
[ { "body": "<p>I believe there is a flaw in your logic that is insurmountable......</p>\n\n<p>SoftReferences, once they are added to the queue, have already lost the Referent instance. I cannot think of any reason why you would want to handle an 'active' queued (the value has been GC'd) softreference in any way differently from an 'inactive' one.</p>\n\n<p>Once the reference has been queued it's too late to do anything about the instance it was softly referencing.</p>\n\n<p>On the other hand, if you want to 'process' a referant, and make sure it is not GC'd during the processing, then jsut keep a reference to it:</p>\n\n<pre><code>V referent = softref.get();\nif (referent == null) {\n // it's already been GC'd (and at some point we will see it poll'd from the Q)\n return;\n}\n// do things with our referent\n// since our referent varaible is a hard-reference,\n// nothing can happen to the soft reference.\n....\n\n// then clear our reference (or return from our method,\n// or clear our hard reference in some other way)\nreferent = null;\n// after this the referent can (possibly) be GC'd again\n</code></pre>\n\n<hr>\n\n<p>EDIT after comments:</p>\n\n<p>From the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/ref/SoftReference.html\" rel=\"nofollow\">Javadoc for SoftReference</a>:</p>\n\n<blockquote>\n <p>Suppose that the garbage collector determines at a certain point in time that an object is softly reachable. At that time it may choose to clear atomically all soft references to that object and all soft references to any other softly-reachable objects from which that object is reachable through a chain of strong references. At the same time or at some later time it will enqueue those newly-cleared soft references that are registered with reference queues. </p>\n</blockquote>\n\n<p>The GC will only nequeue <strong>newly cleared</strong> soft references. Further, from the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/ref/SoftReference.html#get%28%29\" rel=\"nofollow\">SoftReference.get()</a> method, we have:</p>\n\n<blockquote>\n <p>Returns this reference object's referent. If this reference object has been cleared, either by the program or by the garbage collector, then this method returns null</p>\n</blockquote>\n\n<p>Finally, here is a <a href=\"http://www.pawlan.com/monica/articles/refobjs/\" rel=\"nofollow\">third-party 'reference' on 'references'</a> ... heh. It appears to be quite good.</p>\n\n<hr>\n\n<p>EDIT 2: how to keep a value 'active' (responding to comments)</p>\n\n<p>If the requirement is to prevent a particular Soft reference referent from being GC'd, the answer is relatively simple: create a hard reference and keep it.... For example:</p>\n\n<pre><code>private static final IdentityHashMap&lt;MyType, Object&gt; active = new .....;\nprivate static final Object token = new Object();\n\nprivate static final boolean forceActive(SoftReference&lt;MyType&gt; reference) {\n MyType referent = softref.get();\n if (referent == null) {\n // it's already been GC'd ... and ...\n // if the reference was created with a ReferenceQueue, we can\n // expect to 'poll' the reference from that queue at some point\n // maybe we have already done that....\n return false;\n }\n // referent is now a hard reference, we are guaranteed that `reference`\n // is not on any Queue, and that it will not be GC'd (since we have a hard reference)\n\n // we want to keep our referent 'active', so we need to keep a hard reference:\n // the key in the identity hash map is our hard link.\n active.put(referent, token);\n // we exit our keep-active method, but the hard reference remains.\n return true;\n}\n\nprivate static final boolean deActive(SoftReference&lt;MyType&gt; reference) {\n MyType referent = softref.get();\n if (referent == null) {\n // it's already been GC'd ... and ... that means it was not\n // in our active map (otherwise it would not have been GC'd).\n return false;\n }\n // if the map contains the referent as a key, then it will return 'token'.\n // and we have now successfully removed the hard-reference to the referent.\n return token == active.remove(referent);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T10:15:10.050", "Id": "58304", "Score": "0", "body": "\"*Some time after the garbage collector determines that the reachability of the referent has changed* to the value corresponding to the type of the reference, it will add the reference to the associated queue. At this point, the reference is considered to be enqueued.\" -- I haven't found in the docs clear statement that `ref.get() == null` for references in the queue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T12:30:12.867", "Id": "58313", "Score": "0", "body": "@leventov updated reference material" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T14:29:23.623", "Id": "58331", "Score": "0", "body": "I have a slightly different issue. In your example code, I want to prevent the ref from being enqueued after `referent == null` check. At that point I don't know, is the ref is already enqueued or not (in the latter case I can simple write `softref = null;` to \"remove\" the soft ref from the queue)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T14:36:15.150", "Id": "58333", "Score": "0", "body": "More complicated answer than this space has.... let me edit again...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T14:49:24.557", "Id": "58339", "Score": "0", "body": "Editing done. All the best." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:05:38.293", "Id": "58414", "Score": "1", "body": "No. Suppose referent is GC'd (`ref.get() == null`, but I don't know is the ref is already enqueued or not. If it isn't enqueued, I just need to \"forget\" the ref. Otherwise, I need to \"remove\" it from the queue (that was the purpose of `MyReference` class from the question)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:43:35.620", "Id": "58425", "Score": "0", "body": "My recommendation is that you don't bother with the queue. it ads no value to you. You already have SoftReference instances that you are keeping 'outside' of the GC system, and you don't need to keep track of when the referent is GC'd. You just need to make sure that, for certain periods, it is Not GC'd (if it has not been GC'd already)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:46:33.247", "Id": "58426", "Score": "1", "body": "@leventov Also, note, that if the referent *is* GC'd, the Reference *will* be have `get() == null` and also be enqueued 'at some point'... but you don't know where in the queue it will be, and there is only 1 method you can use on the queue, and that's `poll()` and that may not remove *your* Reference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:46:54.500", "Id": "58427", "Score": "0", "body": "in your case you can easily do what you want to do, without using the Queue at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T21:14:16.543", "Id": "58468", "Score": "1", "body": "No. I touch some refs and don't want to process them through the `queue.poll()`, but there are some other refs which follow the \"normal\" queue way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T21:21:24.123", "Id": "58470", "Score": "1", "body": "Once you register a SoftReference with a queue there is no way to deregister it, other than to clear it's referent value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-19T01:11:53.773", "Id": "333838", "Score": "0", "body": "@leventov, Re \"*haven't found in the docs*\", admittedly the wording of the docs isn't clear. But fwiw: http://archive.is/j4Hsg#selection-283.281-283.294 and http://archive.is/SP2B8#selection-275.378-275.391" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-19T01:55:45.547", "Id": "333839", "Score": "0", "body": "@leventov, See my answer." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T04:26:09.410", "Id": "35803", "ParentId": "28534", "Score": "3" } }, { "body": "<p>&lt;<code>while (... referenceQueue.poll()</code>> is a busy loop. 98.5% of times, you will not want it. Opt for <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/ref/ReferenceQueue.html#remove()\" rel=\"nofollow noreferrer\"><code>.remove</code></a> instead.</p>\n\n<p>Otherwise, it looks pretty good. If you need an additional functionality which is to asap <code>ReleaseResources()</code>, do this:</p>\n\n<pre><code>class MyReference&lt;V&gt; extends SoftReference&lt;V&gt; {\n public V GetObjAndReleaseIfNeeded() {\n V obj = get();\n if(obj === null) ReleaseResources();\n }\n public void ReleaseResources(){\n if(is_released)return;\n // release\n is_released = true;\n }\n</code></pre>\n\n<p>..and in the queue:</p>\n\n<pre><code>while (ref = referenceQueue.remove()) {\n @SuppressWarnings(\"unchecked\")\n MyReference&lt;V&gt; myRef = (MyReference&lt;V&gt;) ref;\n myRef.ReleaseResources()\n}\n</code></pre>\n\n<p>This will ensure that even if the GC takes forever to queue your ref, you'll still <code>ReleaseResources()</code> when the user calls <code>GetObjAndReleaseIfNeeded()</code>.</p>\n\n<p>Naturally, if the user does not call <code>GetObjAndReleaseIfNeeded</code>, your resources will be unreleased even while obj has been out of scope, all the way until the GC queues your ref and the queue has been polled, <strong>if ever</strong>. </p>\n\n<p>A running GC is <a href=\"http://archive.is/j4Hsg#selection-283.18-283.21\" rel=\"nofollow noreferrer\">never guaranteed</a> to ever queue a softreference.</p>\n\n<p>In fact, a GC is never guaranteed to run, ever, thus even weakreferences are <a href=\"http://archive.is/Y1suz#selection-275.2-275.14\" rel=\"nofollow noreferrer\">never guaranteed to be queued </a>. </p>\n\n<p><strong>Note: Be careful of synchronization if getting ref and polling queue ain't on the same thread.</strong></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-19T01:55:24.833", "Id": "176024", "ParentId": "28534", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T03:21:32.480", "Id": "28534", "Score": "5", "Tags": [ "java", "weak-references" ], "Title": "“Removing” reference from its ReferenceQueue" }
28534
<p>A friend of mine wanted an array-to-CSV string function for Node.js, so I came up with this. Basically, it can take in a single object, a 2D array or an array of objects. </p> <p>If the children or parent is an object then the object properties become the headers, if the children are arrays then the first array is the headers.</p> <p>Each cell is enclosed inside double quotes in the case of commas inside of the cell, and any double quotes inside the cell are escaped. Is there anything else I should be escaping?</p> <pre><code>exports.objectToCSVString = function (ob) { var str = "", row, a, i, o, c, r; if(ob instanceof Object &amp;&amp; !(ob instanceof Array)){ ob = [ob]; } if(ob instanceof Array){ for(r in ob){ if(ob.hasOwnProperty(r)){ row = ob[r]; if(row instanceof Array){ a = ""; for(i in row){ if(row.hasOwnProperty(i)){ a += a.length === 0 ? "" : ","; a += "\"" + row[i].toString().replaceAll("\"", "\\\"") + "\""; } } str += str.length === 0 ? a : "\r\n" + a; }else if(row instanceof Object){ if(o === undefined){ o = []; a = ""; for(c in row){ if(row.hasOwnProperty(c)){ o.push(c); a += a.length === 0 ? "" : ","; a += "\"" + c.toString().replaceAll("\"", "\\\"") + "\""; } } str += str.length === 0 ? a : "\r\n" + a; } a = ""; for(c in o){ if(o.hasOwnProperty(c) &amp;&amp; row[o[c]] !== undefined){ a += a.length === 0 ? "" : ","; a += "\"" + row[o[c]].toString().replaceAll("\"", "\\\"") + "\""; } } str += str.length === 0 ? a : "\r\n" + a; }else{ throw "row is not an Array or object"; } } } return str; } throw "Object is not an Array"; }; String.prototype.replaceAll = function(a, b){ var t = this, o = [], i; //get all the occurances of it for(i = 0; i &lt; t.length; i+=1){ if(t.substr(i, i - 1 + a.length) == a){ o.push(i); } } for(i = 0; i &lt; o.length; i+=1){ t = t.substr(0, o[i] - 1) + b + t.substr(o[i] + b.length, t.length - 1); } return t; }; </code></pre> <p>Is the concept right? Do I cover everything when it comes to creating a CSV string? Any other comments?</p> <p>Is there any way I can improve this or improve the performance? It seems to be rather quick when running, but I'm not sure what to base it on either. </p> <hr> <p><strong>Examples</strong></p> <p>Given I have required the file and it is names csv</p> <p><code>csv.objectToCSVString({a:"a1",b:"b1"});</code></p> <p>will output:</p> <pre><code>"a", "b" "a1", "b1" </code></pre> <p><code>csv.objectToCSVString([{a:"a1",b:"b1"},{a:"a2",b:"b2"}]);</code></p> <p>will output:</p> <pre><code>"a","b" "a1","b1" "a2","b2" </code></pre> <p><code>csv.objectToCSVString([["a", "b"], ["a1", "b1"], ["a2", "b2"]]);</code></p> <p>will output:</p> <pre><code>"a","b" "a1","b1" "a2","b2" </code></pre> <p><code>csv.objectToCSVString({a:"a\"1\"",b:"b\"1\""});</code></p> <p>will output:</p> <pre><code>"a","b" "a\"1\"","b\"1\"" </code></pre> <p><strong>NOTE</strong> I am working on the replace all function, it doesn't work as it should yet</p>
[]
[ { "body": "<p>There's a few points you can improve on:</p>\n\n<hr>\n\n<h2><code>throw</code>:</h2>\n\n<blockquote>\n<pre><code>throw \"Object is not an Array\";\n</code></pre>\n</blockquote>\n\n<p>You should use <code>throw new Error</code> instead of <code>throw</code> as <code>throw new Error</code> contains a stack trace as well.</p>\n\n<hr>\n\n<h2><code>for in</code>:</h2>\n\n<p><code>for in</code> is a bit weird and can cause issues as it iterates over prototypes as well.</p>\n\n<p>Considering you're testing that the properties are array items anyway, you can just use <code>forEach</code> instead.</p>\n\n<blockquote>\n<pre><code>if(ob instanceof Array){\n for(r in ob){\n if(ob.hasOwnProperty(r)){\n row = ob[r];\n</code></pre>\n</blockquote>\n\n<p>into:</p>\n\n<pre><code>if(ob instanceof Array){\n ob.forEach(function(row, index){\n //...\n</code></pre>\n\n<hr>\n\n<h2>Declaring globals:</h2>\n\n<p>You shouldn't be declaring globals like:</p>\n\n<blockquote>\n<pre><code>var str = \"\", row, a, i, o, c, r;\n</code></pre>\n</blockquote>\n\n<p>Use them at their respective levels, don't have left over variables.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-03T16:15:00.283", "Id": "214878", "Score": "0", "body": "Similarly to how it doesn't _really_ belong in your question, it doesn't belong in my answer: You can just find a `replaceAll` implementation on MDN." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-04T10:51:45.983", "Id": "214983", "Score": "0", "body": "I should really post an update on this, I have really progressed since then. :). Thanks for the comments." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-03T16:14:15.167", "Id": "115733", "ParentId": "28536", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T04:10:46.017", "Id": "28536", "Score": "5", "Tags": [ "javascript", "csv" ], "Title": "Correctness of a CSV writer in Node.js" }
28536
<p>After considerable effort, I've come up with the following code to generate a list of primes of a given length.</p> <p>I would be very interested to see how an experienced coder would modify my code to make it more readable, more concise, or somehow better. I won't be able to follow fancy-pants coding that doesn't involve basic iterations of the type I have used, so please keep it simple for me. I've been learning the language only a few months.</p> <p>Function returns number of primes indicated in call.</p> <p>Algorithm: Add two to last candidate in list (starting with [2, 3, 5]) and check whether other members divide the new candidate, iterating only up to the square root of the candidate.</p> <pre><code>import math def primeList(listLength): plist = [2, 3] j = 3 while listLength &gt; len(plist): prime = 'true' i = 0 j +=2 plist.append(j) while plist[i] &lt;= math.sqrt(j) and prime == 'true': if j%plist[i] == 0: prime = 'false' i +=1 if prime == 'false': plist.pop(-1) return plist </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T04:04:10.643", "Id": "44798", "Score": "1", "body": "See http://stackoverflow.com/questions/567222/simple-prime-generator-in-python?rq=1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T04:07:06.617", "Id": "44799", "Score": "0", "body": "see http://stackoverflow.com/questions/3939660/sieve-of-eratosthenes-finding-primes-python" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T04:08:12.460", "Id": "44801", "Score": "0", "body": "But immediately: use `True` and `False`, not `'true'` and `'false`'. And use `not prime` and `and prime`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T04:11:59.010", "Id": "44802", "Score": "0", "body": "See: http://www.macdevcenter.com/pub/a/python/excerpt/pythonckbk_chap1/index1.html?page=2" } ]
[ { "body": "<p>Other than the few things pointed out above, it might be 'cleaner' to use a helper function to test primality. For example:</p>\n\n<pre><code>import math\n\ndef is_prime(x, primes):\n return all(x % i for i in primes if i &lt; math.sqrt(x))\n\ndef first_k_primes(i, k, my_primes):\n if k &lt;= 0:\n return my_primes\n\n if is_prime(i, my_primes):\n my_primes.append(i) \n return first_k_primes(i + 2, k - 1, my_primes)\n\n return first_k_primes(i + 2, k, my_primes)\n\nprint(first_k_primes(5, 10, [2, 3]))\n</code></pre>\n\n<p>Now, I know you didn't want any \"fancy-pants\" coding, but this is actually really really similar to your iterative approach, just using recursion. If we look at each bit we have the following:</p>\n\n<p><code>is_prime(x, primes)</code>: this tests whether the value <code>x</code> is prime or not. Just like in your code, it takes the modulo of <code>x</code> against all of the primes up to the square root of <code>x</code>. This isn't too tricky :) The <code>all()</code> function gathers all of these tests and returns a boolean (True or False). If all of the test (from 2 up to sqrt(x)) are False (i.e., every single test confirms ti is prime) then it returns this finding, and we know x is prime.</p>\n\n<p><code>first_k_primes(i, k, my_primes)</code>: ok, this is recursive, but it isn't too tricky. It takes 3 parameters: </p>\n\n<ul>\n<li>i: the number to test</li>\n<li>k: the number of primes you still need to find until you have the\nnumber you want, e.g. if you want the first 4 primes, and you\nalready know [2, 3, 5], then k will be 1</li>\n<li>my_primes: which is the list of primes so far.</li>\n</ul>\n\n<p>In python, the first thing you need to do with a recursive function, is to figure out a base case. Here, we want to keep going until we have k number of primes (or until k = 0), so that is our base case.</p>\n\n<p>Then we test to see if <code>i</code> is prime or not. If it is, we add it to our growing list of my_primes. Then, we go to the next value to test (<code>i += 2</code>), we can reduce k by one (since we just added a new prime) and we continue to grow our list of my_primes by calling the modified: <code>first_k_primes(i + 2, k - 1, my_primes)</code>.</p>\n\n<p>Finally, if it happens that <code>i</code> is not prime, we don't want to add anything to <code>my_primes</code> and all we want to do is test the next value of <code>i</code>. This is what the last return statement does. It will only get this far if we still want more primes (i.e. k is not 0) or i wasn't prime.</p>\n\n<p>Why do I think this is more readable? The main thing is that I think it is good practice to separate out your logic. <code>is_prime()</code> does one thing and one thing only, and it does the very thing it says it does - it tests a value. Similarly <code>first_k_primes()</code> does exactly what it says it does too, it returns the first k primes. The really nice thing, is that this all boils down to one simple test:</p>\n\n<pre><code>if is_prime(i, my_primes):\n my_primes.append(i)\n</code></pre>\n\n<p>the rest just sets up the boundaries (i.e. the kth limit). So once you have seen a bit of recursion, you intuitively zoom in on the important lines and sort of 'ignore' the rest :)</p>\n\n<p>As a side note, there is a slight gotcha with using recursion in Python: Python has a recursion limit of 1,000 calls. So if you need to recurse on large numbers it will often fail. I love recursion, it is quite an elegant way to do things. But it might also be just as easy to do the <code>first_k_primes()</code> function as an iterative function, or using a generator.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T03:54:10.343", "Id": "44900", "Score": "0", "body": "It fails for k = 1001. It isn't really that big a number. So that recursive approach won't work for even moderate numbers. http://ideone.com/k4u9So" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T04:45:55.300", "Id": "44903", "Score": "0", "body": "You're right - and that is why the caveat is there in the last paragraph and a recommendation to use an iterative approach or a generator expression." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T04:53:29.467", "Id": "44904", "Score": "0", "body": "I tested this a bit more and it failed for all n > 312. http://ideone.com/jYliuH and http://ideone.com/dDgwiz This was a bit too much. Shouldn't the limit of recursion be more in Python? Your approach would be great in both clarity as well as speed in C as compilers optimize tail-recursive calls. In Python this flaw of tail-recursive calls not being optimized led to this being useless." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T04:58:37.580", "Id": "44905", "Score": "0", "body": "You don't seem to be considering the number of recursive calls necessary to generate 300 primes. It is far more than 300 calls because not all calls will generate a prime number. Again, the limits of recursion in Python have been discussed" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T05:03:38.887", "Id": "44906", "Score": "0", "body": "I understand that there are more than 300 calls. Just saying that I didn't understand why this was so. I found that stack frames are big in Python and guido doesn't like tail-recursion but just... Anyways, me babbling doesn't help anyone so I'll stop with this." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T05:11:25.320", "Id": "28539", "ParentId": "28537", "Score": "0" } }, { "body": "<p>Don't be afraid of typing. Longer names are more readable and should be used except for simple counters. Split out complicated sub-parts where they are separate concepts.</p>\n\n<p>Here is how I would improve it:</p>\n\n<pre><code>import math\n\ndef isPrime (primeList, candidate):\n upperLimit = math.sqrt(candidate)\n for p in primeList:\n if candidate % p == 0:\n return False\n if p &gt;= upperLimit:\n break\n\n return True\n\ndef primeList(listLength):\n if listLength &lt; 1 :\n return []\n primes = [2]\n\n candidate = 3\n while listLength &gt; len(primes):\n if isPrime(primes, candidate):\n primes.append(candidate)\n candidate +=2\n\n return primes\n</code></pre>\n\n<p>To make a faster simple prime algorithm, consider the other naive algorithm in <a href=\"http://en.wikipedia.org/wiki/Primality_test\" rel=\"nofollow\">the primality test wikipedia article</a> where all primes are of the form 6k +- 1.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T05:18:25.023", "Id": "44805", "Score": "0", "body": "+1 for near identical solutions :) Fantastic to see an iterative approach to `primeList` against the similar recursive one in my answer. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T03:47:21.937", "Id": "44899", "Score": "0", "body": "This code **does not run** http://ideone.com/v6cOLI. `j` is not defined in the function `isprime`. Also why are not just returning when it is non-prime. It seems like a waste to use a variable to do essentially the same thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T04:15:58.643", "Id": "44901", "Score": "0", "body": "Thanks @AseemBansal. I had no idea that a site like ideone.com existed. That will be very useful. Very good point about not just returning, and I got rid of the while loop as well. Also I have no idea why I named the list inside primeList the same as the function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-30T15:12:04.073", "Id": "143259", "Score": "0", "body": "thanx@DominicMcDonnell ,nut I think in primeList function,,, the statement candidate += 2 should be below if statement body ,, because it doesn't include 3 to the prime list." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T05:15:28.870", "Id": "28540", "ParentId": "28537", "Score": "5" } }, { "body": "<p>I'll firstly talk about micro-optimizations then go for major optimizations that can be done in your code.</p>\n\n<p>Don't use the <code>while</code> loop when you can instead use <code>for i in xrange()</code>. It is very slow. Take a look <a href=\"http://mail.python.org/pipermail/tutor/2011-March/082586.html\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://stackoverflow.com/questions/1377429/what-is-faster-in-python-while-or-for-xrange\">here</a>. There are some limitations but<code>xrange</code> unless you are hitting that limit your code would get faster.</p>\n\n<p>The inner <code>while</code> loop's conditions can be improved. As you have placed calculating <code>math.sqrt()</code> in the conditions it is calculated every time. That makes it very slow because finding square root consumes much time. You should use a variable before the loop to store that value. The second condition is not needed. Instead of checking always for the value of <code>prime</code> you can delete this condition as well as the variable and simply use a <code>break</code> in the <code>if</code> statement.</p>\n\n<p>About using <code>append</code>. You are appending numbers and popping them if they are not primes. Not needed. Just append at the correct condition and use <code>break</code></p>\n\n<p>Also read the Python performance tips link given in Python Tags' wiki on codereview.\nI would have written it like this:</p>\n\n<pre><code>import math\ndef primeList(listLength):\n if listLength &lt; 1:\n return []\n plist = [2]\n j = 3\n sqr_root = math.sqrt\n list_app = plist.append\n while listLength &gt; len(plist):\n temp = sqr_root(j)\n for i in xrange(len(plist)):\n if j % plist[i] == 0:\n break\n if plist[i] &gt; temp:\n list_app(j)\n break\n\n j += 2\n return plist\n</code></pre>\n\n<p>Notice that I defined <code>math.sqrt</code> as something. You'll find that in the Python Performance tips. Also your implementation had a bug. If I entered anything less than 2 it returned <code>[2, 3]</code> which was incorrect result.</p>\n\n<p>This worked in 44 % time that your original function took. Your <a href=\"http://ideone.com/4dhotO\" rel=\"nofollow noreferrer\">code's timing</a> and <a href=\"http://ideone.com/FUI8Nc\" rel=\"nofollow noreferrer\">my code's timing</a>. Note that memory usage is lower in my case. I changed my code a bit. This <a href=\"http://ideone.com/tPuBBf\" rel=\"nofollow noreferrer\">new code uses only 34% time</a> of OP's code.</p>\n\n<p>Now done with micro-optimizations I'll get to major optimizations.</p>\n\n<p>Using this approach to find the list of prime numbers is actually very naive. I also used it in the beginning and after much headache and waiting for outputs to come I found that such approaches can be very slow. Nothing you change in Python's syntax can offset the advantage of using a better algorithm. Check out <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">this</a>. It is not to difficult to implement. You can look at <a href=\"https://github.com/anshbansal/Python\" rel=\"nofollow noreferrer\">my github</a> to get a basic implementation. You'll have to tweak it but you won't have to write it from the beginning.</p>\n\n<p>Hope this helped.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T15:59:08.047", "Id": "28561", "ParentId": "28537", "Score": "1" } }, { "body": "<pre><code>import math\ndef primeList(n):\n plist = [2, 3]\n j = 3\n while len(plist) &lt; n:\n j += 2\n lim = math.sqrt(j)\n for p in plist: # 100k primes: 3.75s vs 5.25 with while loop\n if p &gt; lim: # and the setting of the flag, \n plist.append(j) # on ideone - dNLYD3\n break\n if j % p == 0:\n break\n return plist\nprint primeList(100000)[-1] \n</code></pre>\n\n<p>Don't use long variable names, they hamper readability. Do add comments at first use site of a var to explain what it is (if not self-evident). Move repeated calculations out of the (inner) loop. No need to <em>index</em> into the <code>plist</code> list; just <code>for ... in</code> it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T04:43:16.203", "Id": "44902", "Score": "0", "body": "Avoiding the dots can give better timing.[Your code](http://ideone.com/qYBeUF) timing was 0.25 and by [avoiding dots](http://ideone.com/tPuBBf) it was 0.17." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T06:07:49.963", "Id": "44908", "Score": "0", "body": "@AseemBansal no, your testing is unreliable, because you chose too small a test size so it runs too fast, so you can't be sure whether you observe a real phenomenon or just some fluctuations. I tested this code for 100,000 primes, and [there was no change in timing](http://ideone.com/tbofSs). OTOH even on the same code it was 3.75s usually but there was a one-time outlier of 4.20 (yes I ran it several times, to be sure my observation was repeatable). Another thing, my code performs its steps in correct sequence. It doesn't test any prime above the square root of the candidate. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T07:22:52.797", "Id": "44910", "Score": "0", "body": "I wrote that in that sequence because I thought that would be better as there are more chances of a number being composite. I thought that benefit would build up. About the dots, I don't know why the Python Performance tips say that it helps the performance if they don't. About unreliable timing, noone is answering [this question](http://codereview.stackexchange.com/questions/28373/is-this-the-proper-way-of-doing-timing-analysis-of-many-test-cases-in-python-or) so I am stuck with using ideone for doing the timing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T12:31:33.217", "Id": "44921", "Score": "0", "body": "@AseemBansal Ideone's fine, just short timespans (smaller than half a second, say) are not so reliable, a priori. --- ok, so your ordering saves one comparison for each composite, mine saves one division for each prime." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T19:53:58.740", "Id": "28584", "ParentId": "28537", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T03:58:48.117", "Id": "28537", "Score": "5", "Tags": [ "python", "algorithm", "primes" ], "Title": "Generating a list of primes of a given length" }
28537
<p>I am developing a website and I want to use PDO and MVC.</p> <p>Before, I was coding in procedural MySQL, but I'm starting to understand the object-oriented programming.</p> <p>My problem is the following:</p> <p>If I understand the MVC pattern, there are 3 parts</p> <ol> <li>View (It's my Html)</li> <li>Model (PHP requests)</li> <li>Controller (Control and form validation)</li> </ol> <p>Right?</p> <p>I want to know if I have the right approach to MVC.</p> <p>So, I put code that works and I try to change in MVC. (My test MVC is lower in the page.)</p> <pre><code>$db = new DbConnect(); $error = ''; if(isset($_POST['login_submit'])){ if(empty($_POST['login']) || empty($_POST['password'])){ $error = 'All fields required'; }else{ $db-&gt;query('SELECT * FROM users WHERE u_login = :login AND u_password = :password'); $db-&gt;bind(':login', $_POST['login']); $db-&gt;bind(':password', md5(sha1($_POST['password']))); $row = $db-&gt;single(); if($db-&gt;rowCount() &gt; 0){ echo 'I can save some informations by sessions'; echo '&lt;pre&gt;'; print_r($row); echo '&lt;/pre&gt;'; }else{ $error .= 'Not find in the Data Base'; } } } if(!empty($error)){ echo $error; } </code></pre> <p>Here the html form:</p> <pre><code>&lt;form action="login" method="post" name="login"&gt; &lt;label for="login"&gt;Login: &lt;input type="text" name="login" id="login"&gt; &lt;/label&gt; &lt;label for="password"&gt;Mot de passe: &lt;input type="password" name="password" id="password"&gt; &lt;/label&gt; &lt;input type="submit" name="login_submit" value="Se connecter"&gt; </code></pre> <p></p> <p>Now I try to evolve towards the MVC model like this:</p> 1. My Model called <strong>model.login.php</strong>: <pre><code>class Auth extends DbConnect{ protected $login; protected $password; protected $email; public function ConnectSecure(){ if(isset($_POST['login_submit'])){ CheckPostLogin(); $this-&gt;query('SELECT * FROM users WHERE u_login = :login AND u_password = :password'); $this-&gt;bind(':login', $_POST['login']); $this-&gt;bind(':password', md5(sha1($_POST['password']))); $this-&gt;single(); if($this-&gt;rowCount() &gt; 0){ echo 'OK and I put some informations by sessions'; }else{ echo 'No in DB or error combination user/password'; } echo '&lt;pre&gt;'; print_r($result); echo '&lt;/pre&gt;'; } } } </code></pre> 2. My controller called <strong>controller.login.php</strong>: <pre><code>require 'models/model.login.php'; function CheckPostLogin(){ if(empty($_POST['login']) || empty($_POST['password'])){ Message::ShowError('All fields required.'); return false; } } </code></pre> 3. My view has the same HTML code listed above. <p>I have also a global class that will handle static functions to display messages for error, success, etc. like this (just an example):</p> <pre><code>class Message{ public static function ShowError($message){ echo $message; } } </code></pre> <p>I have another problem:</p> <p>Inside my model, after the query, I check if I have some result. I think this part need go on the controller. Right? If yes, how can I do this properly?</p> <p>I'm new to OOP. If you see any errors or discrepancies, your advice is welcome.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-28T13:52:13.697", "Id": "84947", "Score": "0", "body": "Simplified, the controller is the traffic agent that links the correct model(s) and view(s) together." } ]
[ { "body": "<blockquote>\n<p><sup>Well .. <strong>you do not understand MVC design pattern</strong>. You seem to got all three parts wrong. Since I am quite lazy person, I will just direct to some older posts of mine that might help you to deal with <a href=\"https://stackoverflow.com/a/11369679/727208\">handling pdo</a>, some <a href=\"https://stackoverflow.com/a/16356866/727208\">initial studies</a> for the subject, basics of <a href=\"https://stackoverflow.com/a/16596704/727208\">views</a>, <a href=\"https://stackoverflow.com/a/5864000/727208\">model layer</a>, some minor note on <a href=\"https://stackoverflow.com/a/13396866/727208\">controllers</a>. Also there is a bit about <a href=\"https://stackoverflow.com/a/9685039/727208\">access control</a> in context of MVC, that might be useful to you.</sup></p>\n</blockquote>\n<h3>Now! To the code ...</h3>\n<p><strong>File:</strong> <em>model.login.php</em></p>\n<ul>\n<li><p>Model is not subtype of database connection (wel .. model is not even a class). This class is violating SRP <sup><a href=\"http://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">[1]</a>, <a href=\"http://tomdalling.com/wp-content/uploads/LSP.jpg\" rel=\"nofollow noreferrer\">[2]</a>, <a href=\"http://docs.google.com/a/cleancoder.com/viewer?a=v&amp;pid=explorer&amp;chrome=true&amp;srcid=0BwhCYaYDn8EgNzAzZjA5ZmItNjU3NS00MzQ5LTkwYjMtMDJhNDU5ZTM0MTlh&amp;hl=en\" rel=\"nofollow noreferrer\">[3]</a> </sup>.</p>\n</li>\n<li><p>Aside from making a pointless wrapper for PDO, there is also a serious problem there: <code>md5(sha1( ... ))</code> should <strong>NEVER</strong> be used for hashing passwords. Please read the <a href=\"https://stackoverflow.com/a/4948393/727208\">following</a> <a href=\"https://stackoverflow.com/a/16896216/727208\">three</a> <a href=\"https://stackoverflow.com/a/16044003/727208\">posts</a> from @ircmaxell.</p>\n</li>\n</ul>\n<p><strong>File:</strong> <em>controller.login.php</em></p>\n<ul>\n<li><p>You should learn how to use autoloader. Start by reading the documentation about <a href=\"http://php.net/manual/en/function.spl-autoload-register.php\" rel=\"nofollow noreferrer\"><code>spl_autoload_register()</code></a>. Also I would recommend to look into what are <a href=\"http://php.net/manual/en/language.namespaces.php\" rel=\"nofollow noreferrer\">namespaces</a> and how then can be used together with autoloading schemes.</p>\n</li>\n<li><p>Don't us static method calls. Just because you wrap something in a <code>class</code> does not make it object-oriented (notice how it isn't called &quot;class-oriented programming&quot; .. there is a distinction). When used this way, your class acts only as namespace for your global-scope functions.</p>\n</li>\n</ul>\n<p>... the rest, IMHO, is covered in the linked posts above.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T09:22:03.863", "Id": "28544", "ParentId": "28541", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T08:13:53.860", "Id": "28541", "Score": "2", "Tags": [ "php", "object-oriented", "mysql", "mvc", "pdo" ], "Title": "Structure pages mvc + oop" }
28541
<p>I was reading more about the <code>instancetype</code> on Stack Overflow and now my question is:</p> <p>For every convenience constructor that I write, do I need to have the corresponding one using <code>init</code>?</p> <p>For example:</p> <p><strong>RandomItem.h</strong></p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @interface RandomItem : NSObject @property (nonatomic, copy) NSString *aString; +(instancetype)itemWithString:(NSString *)string; @end </code></pre> <p><strong>RandomItem.m</strong></p> <pre><code>#import "RandomItem.h" @implementation RandomItem +(instancetype)itemWithString:(NSString *)string { RandomItem *anItem = [[self alloc] init]; anItem.aString = string; return anItem; } @end </code></pre> <p>And compare this when using an <code>-initWithString:</code> constructor as well:</p> <p><strong>RandomItem.h</strong></p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @interface RandomItem : NSObject @property (nonatomic, copy) NSString *aString; -(id)initWithString:(NSString *)string; +(instancetype)itemWithString:(NSString *)string; @end </code></pre> <p><strong>RandomItem.m:</strong></p> <pre><code>#import "RandomItem.h" @implementation RandomItem -(id)initWithString:(NSString *)string { self = [super init]; if (self) { self.aString = string; } return self; } +(instancetype)itemWithString:(NSString *)string { return [[self alloc] initWithString:string]; } @end </code></pre> <p>I suppose that both cases are fine, but I would like to hear your comments.</p> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T11:27:30.590", "Id": "44816", "Score": "0", "body": "I've answered below, but wondering whether this question might be more appropriate for programmers.stackexchange.com, or maybe Stack Overflow?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T11:30:56.287", "Id": "44817", "Score": "0", "body": "Having said that, it probably falls within \"Best practices and design pattern usage\". :)" } ]
[ { "body": "<p>It's not necessary to match your initialisers with your class convenience constructor, especially in an ARC environment.</p>\n\n<p>Take a look at the class documentation for <a href=\"http://developer.apple.com/library/ios/#documentation/uikit/reference/UICollectionViewLayoutAttributes_class/Reference/Reference.html\" rel=\"nofollow\"><code>UICollectionViewLayoutAttributes</code></a> as an example from Apple — it defines three different convenience constructors, but no initialisers other than <code>-init</code>.</p>\n\n<p>However, if you're not using ARC, there is a difference in memory management semantics: <strong>class constructors are expected to return autoreleased objects</strong> (and must be explicitly retained to transfer ownership to the caller). Or, more correctly, an object created by any method beginning with <code>alloc</code>, <code>new</code>, <code>copy</code>, or <code>mutableCopy</code> is owned by the caller (and thus any object that you are sending an <code>init...</code> message). See <a href=\"https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html#//apple_ref/doc/uid/20000994-SW1\" rel=\"nofollow\">Apple's memory management guide</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T11:24:26.860", "Id": "28548", "ParentId": "28545", "Score": "1" } }, { "body": "<p>Personally I would prefer the second option because it makes it easier/less weird for subclasses to use and override alloc-init.</p>\n\n<p>As a side node I would point to some reasons to reconsider user properties in your constructors. </p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/8056260/608157\">Should I refer to self.property in the init method with ARC?</a></li>\n<li><a href=\"http://www.mikeash.com/pyblog/friday-qa-2009-11-27-using-accessors-in-init-and-dealloc.html\" rel=\"nofollow noreferrer\">Friday Q&amp;A 2009-11-27: Using Accessors in Init and Dealloc</a></li>\n<li><a href=\"http://qualitycoding.org/objective-c-init/\" rel=\"nofollow noreferrer\">Don’t Message self in Objective-C init (or dealloc)</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T20:24:11.057", "Id": "30275", "ParentId": "28545", "Score": "2" } } ]
{ "AcceptedAnswerId": "30275", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T10:05:28.087", "Id": "28545", "Score": "3", "Tags": [ "objective-c", "constructor" ], "Title": "Is this a correct way to write a convenience constructor?" }
28545
<p>I wanted to create a class to cache dynamic PHP output (or a portion of it from one page) using Memcached key/value story. Basically it checks to see if the file has been cached already, if it has, it grabs it from Memcached and spits it out, otherwise, it outputs the file and stores it in Memcached for three hours.</p> <p>The purge function loops through all the keys in Memcached (because I also use Memcached for other things and "flush" won't work) and pulls out all the keys starting with "cache_" and removes them. I run this whenever I have completed database updates. </p> <p>I was looking for feedback on this class -- for those more talented than me to point out issues with the code -- and also thought others might be interested in it if others thought it was of legitimate value.</p> <p>Following is the class:</p> <pre><code>class MemcachedCache { var $objMemCached; var $strCacheKey; var $boolTimeStamp = true; var $intCacheTime = 10800; //three hours var $boolCaching = false; function __construct() { $this-&gt;objMemCached = new Memcached; $this-&gt;objMemCached-&gt;addServer('localhost', 11211); $this-&gt;strCacheKey = 'cache_' . base64_encode($_SERVER['REQUEST_URI']); } function start() { if(!($result = $this-&gt;objMemCached-&gt;get($this-&gt;strCacheKey))) { $this-&gt;boolCaching = true; ob_start(); } else { echo $result; exit; } } function end() { if ($this-&gt;boolCaching) { $data = ob_get_contents(); if ($this-&gt;boolTimeStamp) $data .= '&lt;!-- Memcached at: ' . date('Y/m/d H:i:s') . ' --&gt;'; $this-&gt;objMemCached-&gt;set($this-&gt;strCacheKey, $data, $this-&gt;intCacheTime); ob_end_flush(); } } function purge() { $arCachedKeys = $this-&gt;objMemCached-&gt;getAllKeys(); //get all the keys in the db foreach($arCachedKeys as $strKey) //loop through each one { if (substr($strKey, 0, 6) == 'cache_') //for all of the player date keys $this-&gt;objMemCached-&gt;delete($strKey); //delete the date key } } </code></pre> <p>Following is an example of how it could be implemented:</p> <pre><code>$cache = new MemcachedCache(); $cache-&gt;start(); //PHP output here $cache-&gt;end(); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T13:33:03.653", "Id": "28553", "Score": "1", "Tags": [ "php", "cache" ], "Title": "Memcached caching" }
28553
<p>We have a linklist which is made of alphabets. We have to shift the vowels towards the end of the linklist, without changing the order in which they appear. So,</p> <pre><code>A-&gt;C-&gt;E-&gt;F-&gt;G-&gt;O </code></pre> <p>should become</p> <pre><code>C-&gt;F-&gt;G-&gt;A-&gt;E-&gt;O </code></pre> <p>This is the code I have written</p> <pre><code>#include&lt;iostream&gt; using namespace std; struct node { char ch; node *next; }; void enqueue (node **head, node **tail, char val) { node *newn = (node *)malloc(sizeof(node)); newn-&gt;ch = val; newn-&gt;next = NULL; if (*head == NULL) { *head = newn; *tail = newn; } (*tail)-&gt;next = newn; (*tail) = newn; } void print (node *head) { while (head!=NULL) { cout&lt;&lt;head-&gt;ch&lt;&lt;" "; head = head-&gt;next; } cout&lt;&lt;endl; } bool isVowel (char ch) { ch = ch | 32; if (ch == 'a' || ch =='e' || ch=='i' || ch=='o' || ch=='u') return true; return false; } node* segregateVowels (node *head, node *tail) { if (head == NULL || head-&gt;next == NULL) return head; node *temp = head; node *fin = tail; while (temp-&gt;next!=fin) { cout&lt;&lt;temp-&gt;ch&lt;&lt;" "&lt;&lt;fin-&gt;ch&lt;&lt;endl; if (isVowel(temp-&gt;next-&gt;ch)) { node *shift = temp-&gt;next; temp-&gt;next = temp-&gt;next-&gt;next; tail-&gt;next = shift; shift-&gt;next = NULL; tail = shift; } else temp = temp-&gt;next; } if (temp-&gt;next!=NULL &amp;&amp; isVowel(temp-&gt;next-&gt;ch)) /* Handling the case where the last element is a vowel */ { node *toMove = temp-&gt;next; temp-&gt;next = temp-&gt;next-&gt;next; tail-&gt;next = toMove; toMove-&gt;next = NULL; } else temp = temp-&gt;next; if (isVowel(head-&gt;ch)) /* Handling the case where the first element is a vowel */ { node *toMove = head; head = head-&gt;next; toMove-&gt;next = temp-&gt;next; temp-&gt;next = toMove; } return head; } int main() { srand(time(NULL)); node *head = NULL, *tail = NULL; int i = 20; while (i&gt;=0) { enqueue (&amp;head, &amp;tail, rand()%26+65); i--; } print(head); head = segregateVowels (head, tail); print(head); } </code></pre> <p>Although this does seem to give me correct results, but I have to explicitly check for two edge cases. Also I feel there is a better solution for this problem or a better approach which I seem to be missing. The problem can be handled by creating two separate Link Lists too, and then joining them together. But what modifications do you suggest in the above program?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T14:24:51.490", "Id": "44830", "Score": "0", "body": "Your formatting is really consistent (especially for new lines). Also, can you explain your bit manipulation in `isVowel()` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T14:30:04.377", "Id": "44831", "Score": "0", "body": "I don't quite follow what you mean when you say that the formatting is consistent. The bit manipulation in isVowel() is just to turn 'A-Z' to 'a-z'. In case if I ever expand the problem to input both small and capital alphabets." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T15:12:45.143", "Id": "44836", "Score": "0", "body": "Ok, thanks, that what I thought. I meant 'inconsistent' as you sometimes skip a few lines for no obvious reasons." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T15:27:11.643", "Id": "44838", "Score": "0", "body": "Okay thanks, will keep that in mind. But I think I do that intentionally. I tend to divide my program on modules. Now these are the modules which come to my head when I think upon the implementation of the problem or the algorithm of the problem. So when I give spaces, I segregate those modules. It sometimes helps in debugging, and helps in figuring out if I am making a common mistake over and over again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T15:56:04.170", "Id": "44840", "Score": "0", "body": "@user2560730: Why not make a LinkedList `class` instead? You're initializing `head` and `tail` in `main()`, but it shouldn't handle the list like that. Also, `new` should be used instead of `malloc` since this is a C++ program." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T15:56:35.967", "Id": "44841", "Score": "0", "body": "I agree on the principle. I have just not too sure we need a blank line for instance between `int i = 20;` and `while (i>=0)`. For other comments, I'll try to post an answer asap." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T16:41:35.033", "Id": "44847", "Score": "0", "body": "@jamal: I have made a transition from C to C++, so I tend to do procedural style programming rather than object oriented style programming. But it's a valid point, and I'll try using classes more." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T23:22:57.073", "Id": "44892", "Score": "1", "body": "@user2560730: This is still C code (you may be using a couple of C++ objects std::cout etc). But the style is C. Note: C++ is a mulch-paradiam language not just OO but there are ways to use the language that avoid the bad parts of C." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T04:34:21.187", "Id": "44960", "Score": "0", "body": "Note that for real code, you probably want to use `std::stable_partition` instead of writing the code yourself." } ]
[ { "body": "<p><strong>Don't do <code>using namespace std</code></strong></p>\n\n<p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Here's a SO question which should provide you more information about this</a>.</p>\n\n<p><strong><code>For</code> loops are here to help you</strong></p>\n\n<p>You could write</p>\n\n<pre><code>int i = 20;\nwhile (i&gt;=0)\n{\n enqueue (&amp;head, &amp;tail, rand()%26+65);\n i--;\n}\n</code></pre>\n\n<p>in a much clearer way using a for-loop : <code>for (int i=20; i&gt;=0; i--)</code> or <code>for (int i=0; i&lt;21; i++)</code>. I prefer the latter because I tend to count forward and not backward and it makes much clearer the fact that you want 21 iterations.</p>\n\n<p><strong>Avoid boilerplate and useless code</strong></p>\n\n<pre><code>if (ch == 'a' || ch =='e' || ch=='i' || ch=='o' || ch=='u')\n return true;\nreturn false;\n</code></pre>\n\n<p>could be simply written :</p>\n\n<pre><code>return (ch == 'a' || ch =='e' || ch=='i' || ch=='o' || ch=='u');\n</code></pre>\n\n<p><strong>Avoid magic numbers</strong></p>\n\n<p>Even if I can guess them, I don't want to learn the ascii code for the different characters.\nYou could rewrite <code>enqueue (&amp;head, &amp;tail, rand()%26+65);</code> in a more explicit way : <code>enqueue (&amp;head, &amp;tail, rand()%26+'A');</code></p>\n\n<p><strong>Be consistent with your brackets</strong></p>\n\n<p>Using brackets for single statement is a <a href=\"https://softwareengineering.stackexchange.com/questions/16528/single-statement-if-block-braces-or-no\">personal preference</a> but if you do use them for the then-block, then please use them for the else-block as it makes things look \"balanced\".</p>\n\n<p><strong>Add a bit of documentation</strong>\nI know it's tedious and not so interesting and I usually try to avoid to ask for it but here, I am getting a but confused by the two functions taking two lists as parameters and trying to understand what is intended for both of them.</p>\n\n<p>This being said, I have to go and I'll try to have a deeper look later on.</p>\n\n<p>In the meantime, here's your code with the comments above taken into account :</p>\n\n<pre><code>#include&lt;iostream&gt;\n\nstruct node\n{\n char ch;\n node *next;\n};\n\nvoid enqueue (node **head, node **tail, char val)\n{\n node *newn = (node *)malloc(sizeof(node));\n newn-&gt;ch = val;\n newn-&gt;next = NULL;\n\n if (*head == NULL)\n {\n *head = newn;\n *tail = newn;\n }\n\n (*tail)-&gt;next = newn;\n (*tail) = newn;\n}\n\nvoid print (node *head)\n{\n while (head!=NULL)\n {\n std::cout&lt;&lt;head-&gt;ch&lt;&lt;\" \";\n head = head-&gt;next;\n }\n std::cout&lt;&lt;std::endl;\n}\n\nbool isVowel (char ch)\n{\n ch |= 32; // make it lowercase\n return (ch == 'a' || ch =='e' || ch=='i' || ch=='o' || ch=='u');\n}\n\nnode* segregateVowels (node *head, node *tail)\n{\n if (head == NULL || head-&gt;next == NULL)\n return head;\n\n node *temp = head;\n node *fin = tail;\n\n while (temp-&gt;next!=fin)\n {\n std::cout&lt;&lt;temp-&gt;ch&lt;&lt;\" \"&lt;&lt;fin-&gt;ch&lt;&lt;std::endl;\n if (isVowel(temp-&gt;next-&gt;ch))\n {\n node *shift = temp-&gt;next;\n temp-&gt;next = temp-&gt;next-&gt;next;\n tail-&gt;next = shift;\n shift-&gt;next = NULL;\n tail = shift;\n }\n else\n {\n temp = temp-&gt;next;\n }\n }\n\n if (temp-&gt;next!=NULL &amp;&amp; isVowel(temp-&gt;next-&gt;ch)) /* Handling the case where the last element is a vowel */\n {\n node *toMove = temp-&gt;next;\n temp-&gt;next = temp-&gt;next-&gt;next;\n tail-&gt;next = toMove;\n toMove-&gt;next = NULL;\n\n }\n else\n {\n temp = temp-&gt;next;\n }\n\n if (isVowel(head-&gt;ch)) /* Handling the case where the first element is a vowel */\n {\n node *toMove = head;\n head = head-&gt;next;\n toMove-&gt;next = temp-&gt;next;\n temp-&gt;next = toMove;\n }\n\n return head;\n}\n\n\nint main()\n{\n srand(time(NULL));\n\n node *head = NULL, *tail = NULL;\n\n for (int i=0; i&lt;21; i++)\n {\n enqueue (&amp;head, &amp;tail, rand()%26+'A');\n }\n\n print(head);\n\n head = segregateVowels (head, tail);\n\n print(head);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T16:47:52.077", "Id": "44849", "Score": "0", "body": "I am not really sure which two lists you are talking about. Because there is just one list in the program. Head is pointing to the head of the list and tail is pointing to the tail of the list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T17:22:19.430", "Id": "44852", "Score": "0", "body": "Why do you need two entry points for your list ? This is what is confusing me quite a lot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T17:39:35.417", "Id": "44855", "Score": "0", "body": "Well as I am adding at the end of a link list, I would have to traverse the entire length of the list before adding a new element. But if I save the tail pointer, I could just append at the end of the tail pointer, and update the tail pointer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T16:40:28.543", "Id": "28563", "ParentId": "28554", "Score": "2" } }, { "body": "<p>A few comments to add to those of @Josay</p>\n\n<p>The main one is that the program fails if there is a vowel at the end but no others (losing the trailing vowel), eg the list Z->Z->A is truncated to Z->Z. This happens (I think) because the code handling the vowel-at-end case assumes that a vowel has already been found - ie. that temp->next->next is not NULL. </p>\n\n<p><hr>\nSome minor points to add:</p>\n\n<p>In <code>segregateVowels</code>:</p>\n\n<ul>\n<li><p>Why the different variable names <code>shift</code> and <code>toMove</code> for things that do the same thing?</p></li>\n<li><p>The <code>tail</code> pointer in the caller is not updated.</p></li>\n<li><p>I think the <code>if (temp-&gt;next!=NULL ...</code> condition is redundant</p></li>\n<li><p>only the vowel-at-head case needs to be handled outside the loop, not the vowel-at-end case, for example</p>\n\n<pre><code>node *n = head;\nnode *prev = head;\nnode *last = tail;\nwhile (n != last) {\n if (isVowel(n-&gt;ch)) {\n tail-&gt;next = n;\n tail = n;\n if (head == n) {\n head = n-&gt;next;\n } else {\n prev-&gt;next = n-&gt;next;\n }\n n = n-&gt;next;\n tail-&gt;next = 0;\n } else {\n prev = n;\n n = n-&gt;next;\n }\n}\nif (isVowel(last-&gt;ch) &amp;&amp; (tail != last)) {\n tail-&gt;next = last;\n if (head == last) {\n head = last-&gt;next;\n } else {\n prev-&gt;next = last-&gt;next;\n }\n last-&gt;next = 0;\n tail = last;\n}\n</code></pre>\n\n<p>In this example I have used two pointers to walk through the list, <code>prev</code> (for 'previous') and <code>n</code>. <code>n</code> is no less meaningful than your <code>temp</code> and is shorter. This code fixes the error mentioned above. Note that the <code>(tail != last)</code> could be omitted (ie. it works without) but it is more clearly correct if present.</p></li>\n</ul>\n\n<p><hr>\n<strong>EDIT</strong> - actually if you pass in the size of the list, you can do everything in the loop:</p>\n\n<pre><code>node* segregateVowels (node *head, node *tail, int size)\n{\n if (head == NULL || head-&gt;next == NULL)\n return head;\n\n node *n = head;\n node *prev = head;\n\n for (int i = 0; (n != NULL) &amp;&amp; (i &lt; size); ++i) {\n if (isVowel(n-&gt;ch)) {\n tail-&gt;next = n;\n tail = n;\n if (head == n) {\n head = n-&gt;next;\n prev = head;\n } else {\n prev-&gt;next = n-&gt;next;\n }\n n = n-&gt;next;\n tail-&gt;next = 0;\n }\n else {\n prev = n;\n n = n-&gt;next;\n }\n }\n return head;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T03:19:42.883", "Id": "44897", "Score": "0", "body": "This is a helpful response, and a much cleaner and simplistic approach. But your program will go into an infinite loop when the list consists of only vowels." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T11:33:16.453", "Id": "44919", "Score": "0", "body": "It doesn't infinite-loop for me (tested by 'enqueue'ing a number of vowels explicitly instead of using random chars). But it did chop off all but the last vowel. I have fixed it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T19:56:33.810", "Id": "28585", "ParentId": "28554", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T14:00:19.243", "Id": "28554", "Score": "1", "Tags": [ "c++", "linked-list" ], "Title": "Shift vowels towards the end of a Single Linked List" }
28554
<p>I want to list the contents of a folder and mail the list using a shell script. I Came up with the following script, please let me know if it is okay:</p> <pre><code>for file in * do if [ -f "$file" ]; then echo "$file" | mail -s "List of files" Someone@somewhere.com fi done </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T16:06:28.967", "Id": "44844", "Score": "2", "body": "this will send a separate email for *each* file. Is that your intent?" } ]
[ { "body": "<p>As @Juaniyyoo already mentioned, <code>ls</code> is the usual way to list all the files in a directory. I'm not sure if you really want to send a separate email for each file. If you do, you can iterate over each file with a <code>while</code> loop.</p>\n\n<pre><code>ls | while read file; do mail ... &lt;&lt;&lt; \"$file\"; done\n</code></pre>\n\n<p>If what you really intended was to send the whole list in one go, this is even simpler.</p>\n\n<pre><code>ls | mail ...\n</code></pre>\n\n<p><code>ls</code> has a lot of options for controlling the output format. With no options, it will just write the name of each file. <code>ls -l</code> lists permissions, number of links, owner user, owner group, size, modification date and name. The date modified might be interesting, i.e. when it was received, but the other one are probably not.</p>\n\n<pre><code>ls -l | sed -E 's/([^ ]+ +){5}//' | mail ...\n</code></pre>\n\n<p>Use this command to filter out the first 5 columns, and thus only get the date and filename columns. You might also want to sort the output - for this use the option <code>--sort=time</code>.</p>\n\n<p>The first output line from <code>ls -l</code> is a header saying something like <code>total 8440</code>. You can skip this first line with <code>tail -n+2</code>.</p>\n\n<pre><code>ls -l | tail -n+2 | sed -E 's/([^ ]+ +){5}//' | mail ...\n</code></pre>\n\n<p>If you want the date and time in another format, use the <code>--time-style</code> option for <code>ls</code>.</p>\n\n<p>Using <code>ls</code> instead of your rolling with your own loop provides a lot of utility, and prevents you from \"reinventing the wheel\". </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-04T15:08:13.293", "Id": "227074", "Score": "0", "body": "It's probably safe in this specific case but in general, people with a lot more experience than I don't recommend parsing the output of `ls` : http://mywiki.wooledge.org/ParsingLs For an even more in-depth discussion of the issue, see http://unix.stackexchange.com/questions/128985/why-not-parse-ls" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-14T10:28:37.710", "Id": "96892", "ParentId": "28555", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T14:24:25.807", "Id": "28555", "Score": "4", "Tags": [ "email", "shell", "unix" ], "Title": "List contents of a folder using a shell script and mail the folder" }
28555
<p>This passes the value of true/false to model which I can use in my controller.</p> <p>How can this be cleaned up?</p> <pre><code>&lt;div data-role="fieldcontain" class="inline-toggle"&gt; &lt;label for="IsAuto"&gt;Auto &lt;a href="#"&gt;&lt;img class="smallInfo" src="/sites/dev-demo/mobile/assets/images/info@2x.png"&gt;&lt;/a&gt;:&lt;/label&gt; &lt;select name="IsAuto" class="togglehidden" id="IsAuto" data-role="slider" data-hidden-id="#autohidden"&gt; &lt;option value="false"&gt;No&lt;/option&gt; &lt;option value="true"&gt;Yes&lt;/option&gt; &lt;/select&gt; @Html.HiddenFor(m =&gt; m.IsAuto, new { id = "#IsAuto", value="#IsAuto" }) &lt;input type ="hidden" name ="autorel" id="autorel" value="@(Model.IsAuto = "#IsAuto".AsBool())" /&gt; </code></pre>
[]
[ { "body": "<p>None. However, it has several issues. Here it is, indented differently to avoid horizontal scroll:</p>\n\n<pre><code>&lt;div data-role=\"fieldcontain\" class=\"inline-toggle\"&gt;\n &lt;label for=\"IsAuto\"&gt;Auto\n &lt;a href=\"#\"&gt;\n &lt;img class=\"smallInfo\" src=\"/sites/dev-demo/mobile/assets/images/info@2x.png\"&gt;\n &lt;/a&gt;:\n &lt;/label&gt;\n &lt;select name=\"IsAuto\"\n class=\"togglehidden\"\n id=\"IsAuto\"\n data-role=\"slider\"\n data-hidden-id=\"#autohidden\"&gt;\n &lt;option value=\"false\"&gt;No&lt;/option&gt;\n &lt;option value=\"true\"&gt;Yes&lt;/option&gt;\n &lt;/select&gt;\n @Html.HiddenFor(m =&gt; m.IsAuto, new { id = \"#IsAuto\", value=\"#IsAuto\" })\n &lt;input\n type =\"hidden\"\n name =\"autorel\"\n id=\"autorel\"\n value=\"@(Model.IsAuto = \"#IsAuto\".AsBool())\" /&gt;\n</code></pre>\n\n<ol>\n<li><p>Where is the closing tag for <code>div</code>?</p></li>\n<li><p>What do you use, XHTML or HTML5? In the first case, you should close <code>img</code>. In the second case, you shouldn't close the last <code>input</code>.</p></li>\n<li><p><a href=\"http://msdn.microsoft.com/en-us/library/gg568994%28v=vs.111%29.aspx\" rel=\"nofollow\"><code>\"#IsAuto\".AsBool()</code></a> always returns false, since <code>\"#IsAuto\"</code> is never equal to <code>\"true\"</code>.</p></li>\n<li><p>Why are you assigning a value to a property of your model in a view in the last line? Maybe you expected <code>Model.IsAuto == ...</code>?</p></li>\n<li><p>An <code>id</code> of the hidden field which starts by <code>#</code> is weird.</p></li>\n<li><p>If you care about naming conventions, <code>m</code> is a poor name for a variable. Basically, any person who have never used ASP.NET MVC before wouldn't be able to know that it refers to a model.</p></li>\n<li><p>Given the actual syntax for the hidden field, wouldn't it be easier to simply write it in plain HTML?</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T11:55:57.807", "Id": "28599", "ParentId": "28559", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T15:46:54.923", "Id": "28559", "Score": "2", "Tags": [ "html", "asp.net", "mvc", "razor" ], "Title": "Passing a true/false value to a model used in a controller" }
28559
<p>I'm making a calendar and this is one part of the larger project. This adds a tooltip with more information when a calendar event is clicked. It then disappears after 10 seconds, or earlier if a click is detected. The exception being if the click in on the tooltip itself. This code works but feels kind of "cheaty" to me. I wanted a fresh pair of eyes to let me know if there's a better way of doing this all or a specific part I could do differently.</p> <pre><code>setUpCalendar: function() { var self = this; //Refers to the main Calendar Object //Render Calendar this.elem.fullCalendar({ height: this.options.elemHeight, events: this.entries, eventClick: function(event, jsEvent, view) { var left = parseInt($(this).css("left")) - 4; var top = parseInt($(this).css("top")) - 80; self.placeTooltip(left, top, event); return false; } }); }, placeTooltip: function(left, top, event) { var toolTip = $(".tooltip"), date = $.fullCalendar.formatDate(event.start, "MM dd yyyy hh TT"); //Format date date = date.replace(" ", "/"); date = date.replace(" ", "/"); toolTip .css({ "display": "block", "position": "absolute", "z-index": 10, "left": left, "top": top }) .html(event.title + "&lt;br /&gt;" + date) .on("click", function(e) { e.stopPropagation(); //Stop click from closing tooltip }); //Remove it later $(document).on("click", function() { toolTip.hide(); //Hide if clicked anywhere }); if(this.closeTool) clearTimeout(this.closeTool); this.closeTool = setTimeout(function() { toolTip.fadeOut(); //Run this timeout to hide tooltip if not clicked }, 10000); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T15:58:50.427", "Id": "44842", "Score": "0", "body": "are there any particular lines that look weird to you? all I can think of is, if you're using underscore.js you can use the `delay` function instead of `setTimeout`: http://underscorejs.org/#delay" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T16:00:43.950", "Id": "44843", "Score": "0", "body": "How does underscore's `delay` handle multiple calls? Does it cancel the previous ones, or add them all to a queue of sorts?" } ]
[ { "body": "<p>You could change the close tooltip fade out to use the jquery <a href=\"http://api.jquery.com/delay/\" rel=\"nofollow\">delay</a> method (assuming you're using jQuery 1.4+).</p>\n\n<p>Instead of this:</p>\n\n<pre><code>if(this.closeTool)\n clearTimeout(this.closeTool);\n\nthis.closeTool = setTimeout(function() {\n toolTip.fadeOut(); //Run this timeout to hide tooltip if not clicked\n}, 10000);\n</code></pre>\n\n<p>You can do this:</p>\n\n<pre><code>if (toolTip.queue().length &gt; 0) {\n toolTip.finish();\n} else {\n toolTip.delay(10000).fadeOut();\n}\n</code></pre>\n\n<p>When the user clicks the first time, <a href=\"http://api.jquery.com/queue/#queue1\" rel=\"nofollow\">the effects queue</a> will be empty (length will be 0), so we queue up the delay and the fade out.</p>\n\n<p>When the user clicks the second time, the effects queue length will be more than one, so we use <a href=\"http://api.jquery.com/finish/\" rel=\"nofollow\">finish</a> to stop the current animation (either the delay or the fade out) and to remove all effects in the effects queue (which will be the delay or both the delay and fade out).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T16:47:28.607", "Id": "44848", "Score": "0", "body": "I can't have more than one function call at a time or else the tooltip will disappear at a random time. So if the click event happens again, there needs to be a way to cancel the previously set delay/fadeOut call." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T18:01:21.343", "Id": "44863", "Score": "0", "body": "I like your edit! But I'm trying to understand the advantages of doing it like this over the setTimeout" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T18:27:56.147", "Id": "44869", "Score": "0", "body": "@JonnySooter if you're working within jquery you should use whatever it provides and it gives you a nice language to indicate what you actually want to do. You aren't just canceling a function timeout, what you really want to do is stop the animations." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T16:42:12.100", "Id": "28564", "ParentId": "28560", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T15:56:25.023", "Id": "28560", "Score": "1", "Tags": [ "javascript", "jquery", "optimization", "object-oriented" ], "Title": "Placing and removing a dynamic tooltip" }
28560
<p>Is this a good form validation script?</p> <pre><code>$(document).ready(function() { $("form").submit(function() { var shouldSubmit = true; $(this).children(":input:not(:button, [type=\"submit\"], [type=\"reset\"])").each(function() { if ($(this).val() == "") { shouldSubmit = false; return shouldSubmit; } }); if ($("input:checkbox").length &gt; 0) { if ($("input:checkbox:checked").length == 0) shouldSubmit = false; } if ($("input:radio").length &gt; 0) { if ($("input:radio:checked").length == 0) shouldSubmit = false; } if (shouldSubmit == false) alert("All form fields must be filled out."); return shouldSubmit; }); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T16:39:09.773", "Id": "44846", "Score": "0", "body": "Have a look at this method: http://api.jquery.com/is/\nYou can save some work by doing something like `if($(\"input:radio\").is(\"checked))`. Also you can just return false right away instead of setting a boolean then returning false." } ]
[ { "body": "<p>The if statements could be cleaner:</p>\n\n<pre><code> if ($(\"input:checkbox\").length &gt; 0 &amp;&amp; $(\"input:checkbox:checked\").length == 0)\n {\n shouldSubmit = false;\n }\n\n if ($(\"input:radio\").length &gt; 0 &amp;&amp; $(\"input:radio:checked\").length == 0)\n {\n shouldSubmit = false;\n }\n\n if (!shouldSubmit)\n {\n alert(\"All form fields must be filled out.\");\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T18:56:49.333", "Id": "28583", "ParentId": "28562", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T16:08:40.073", "Id": "28562", "Score": "1", "Tags": [ "javascript", "jquery", "validation", "form" ], "Title": "Basic form validation script" }
28562
<p>Is this try/catch block written correctly?</p> <pre><code>public String execute() throws Exception{ try{ //Do blah return "success"; //Assuming everything goes well, return success. }catch (Exception e){ e.printStackTrace(); } return "error"; } </code></pre> <p>Should the return "error" be inside the catch clause?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T17:52:48.423", "Id": "44858", "Score": "3", "body": "Why are you not returning a Boolean? Can you elaborate on what this code does? It looks like you should be either returning a bool silently in the case of failure (if the exception is expected), or you should be letting the exception propogate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T17:57:04.403", "Id": "44860", "Score": "0", "body": "I could return a boolean. My question though is, if the return should be inside the catch clause, or outside the try/catch block? Including it inside the catch clause of course will not return the message in case the exception doesn't occur. I am a little confused here on where the return message goes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T17:57:23.750", "Id": "44861", "Score": "0", "body": "The code is quite long. I just pasted what I felt was needed to ask my question :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T18:09:05.263", "Id": "44864", "Score": "3", "body": "Why are you using both a `try/catch` and a `throws` clause for the same exception? Seems a bit redundant." } ]
[ { "body": "<p>My style:</p>\n\n<pre><code>public String execute() throws Exception{\n String result=\"error\";\n try{\n //Do blah\n result=\"success\"; //Assuming everything goes well, return success.\n }catch (Exception e){\n e.printStackTrace();\n }\n return result; \n}\n</code></pre>\n\n<p>I wouldn't say, mine is better, but I prefer it this way:</p>\n\n<p>1) One entry, one exit</p>\n\n<p>2) One variable changed if needed.</p>\n\n<p>3) Easy to follow.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T17:40:16.990", "Id": "44856", "Score": "0", "body": "Thank you. My question is, shouldn't the return statement (the return error message) be inside the catch clause? I mean if the exception occurs, return error?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T20:22:14.893", "Id": "44881", "Score": "0", "body": "Also (and I don't know to what level this holds true in the face of exceptions), some JVMs perform instruction-reordering. Meaning `result=\"success\";` could be the _first_ thing in the `try {}` block, and it'd appear to succeed, even if it failed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T10:48:41.187", "Id": "44917", "Score": "0", "body": "@Clockwork-Muse: Instruction reordering are generally limited to those that have no externally observable behavior changes. I've got a really hard time believing that this particular reordering could ever happen unless there's a bug in the java (or jit-) compiler." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T17:36:37.830", "Id": "28571", "ParentId": "28570", "Score": "1" } }, { "body": "<p>I would leave the return where it is. What if, let's say, the catch block threw an exception? Not likely to happen with the <code>e.printStackTrace</code>, nevertheless.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T18:11:53.900", "Id": "44865", "Score": "0", "body": "What if, let's say, the catch block threw an exception? - Which is why I was thinking the return statement should go inside the catch clause." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T18:14:52.023", "Id": "44866", "Score": "0", "body": "If your catch block throws an exception, the exception will cease execution of the method, thus skipping the return statement" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T18:24:14.677", "Id": "44868", "Score": "0", "body": "Well, the code will behave identically for both placements of the return statement, but, placing it at the end gives you the opportunity to wrap the try/catch in another try/catch. But if you have to do that, I think there's bigger issues" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T18:03:16.923", "Id": "28576", "ParentId": "28570", "Score": "0" } }, { "body": "<p>I think you should return the error result in your catch clause, but it's a personal choice and it depends on your needs...</p>\n\n<pre><code>public String execute() throws Exception{\n try{\n //Do blah\n return \"success\"; //Assuming everything goes well, return success.\n }catch (Exception e){\n e.printStackTrace();\n return \"error\"\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T18:04:53.153", "Id": "28577", "ParentId": "28570", "Score": "0" } }, { "body": "<p>If you can process exception inside of your method, process it, otherwise throw it, to let the caller process it or throw further.</p>\n\n<p>Printing stack trace is not exception processing, it is more about logging. And there it is not necessary to return something. Below, there's my approach to handle errors. Please note that it is encouraged to throw more specific <code>Exception</code> class instances rather than <code>Exception</code> or <code>Throwable</code>. For instance: <code>IOException</code>, etc.</p>\n\n<pre><code>public void execute() throws IOException, MyCustomException {\n // Do something\n // if there's an error you can't process, throw a new or this exception\n // otherwise just return nothing.\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T08:09:38.920", "Id": "28594", "ParentId": "28570", "Score": "4" } }, { "body": "<p>I think you should place it inside the catch as it is in the catch that the \"error\" will be handled when an exception is thrown. Only when using a variable to return, there will be a return-statement at the end of the method. But it doesn't make a big difference, it's more of a personal choice actually.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T08:36:13.460", "Id": "28596", "ParentId": "28570", "Score": "0" } }, { "body": "<p>There nothing <em>wrong</em> with the code per se.</p>\n\n<p>I'd still prefer to have the error return statement inside the catch block to keep it close to where the condition is detected. I would also move the success return statement to the end of the method:</p>\n\n<pre><code>public String execute() throws Exception{\n\n try{\n //Do blah\n }catch (Exception e){\n e.printStackTrace();\n return \"error\"; \n }\n return \"success\";\n}\n</code></pre>\n\n<p>Looks cleaner to me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T10:58:35.610", "Id": "28597", "ParentId": "28570", "Score": "1" } }, { "body": "<p>There's no clear-cut answer to your question. What exceptions a method should catch and handle, and how, is entirely dependent on the contract and semantics of that particular method.</p>\n\n<p>Take for example Google Guava's <code>Ints.tryParse</code> method. It's implemented like this:</p>\n\n<pre><code>public static Integer tryParse(String s) {\n try {\n return Integer.parseInt(s);\n } catch (NumberFormatException e) {\n return null;\n }\n}\n</code></pre>\n\n<p>Since its contract specifies that it returns <code>null</code> for strings that can't be parsed, it <strong>must</strong> catch the exception.</p>\n\n<p>On the other hand, you might have some method that fetches a file on the Internet and writes its content to disk. If that method fails, it would make sense to throw <code>MalformedURLException</code>, <code>IOException</code> etc depending on what went wrong, so that the client code can act accordingly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T13:20:13.237", "Id": "28644", "ParentId": "28570", "Score": "0" } } ]
{ "AcceptedAnswerId": "28594", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T17:33:16.167", "Id": "28570", "Score": "0", "Tags": [ "java" ], "Title": "Try/catch block inside a method that returns String" }
28570
<p>I'm trying to see if there is a better way to do this when I just need one column with one row. Do not mind the lack of use of a prepared statement, I will put it in.</p> <pre><code>public &lt;T&gt; T getValueFromDb(String col, String table, String cond, Class&lt;T&gt; returnValueClass) { T val = null; try { ResultSet rs = getSet("SELECT " + col + " FROM " + table + " WHERE " + cond); if(rs.next()) { if(returnValueClass == Integer.class) { val = (T) (Integer) rs.getInt(col); } else if(returnValueClass == Double.class) { val = (T) (Double) rs.getDouble(col); } else if(returnValueClass == String.class) { val = (T) rs.getString(col); } } closeSetQuietly(rs); } catch(SQLException sql) { Log.logException(null, sql); } return val; } </code></pre> <p>Should I just perhaps do just:</p> <pre><code>returnValueClass.cast(rs.getInt(x)); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T09:04:28.240", "Id": "44914", "Score": "0", "body": "What should one do when a `null` is returned from this method? Does not a value meeting the passed in condition exist? Or did an exception occurred while trying to read from the DB? Or did the passed in class is not one of the few supported ones?" } ]
[ { "body": "<p>Using polymorphism is the way to get an great solution. You are receiving the class in your method just to infer the the return type while you could abstract the idea of conversion and use it to do the inference too. Let's create an interface to convert the result and its implementations:</p>\n\n<pre><code>interface ResultTransformer&lt;T&gt; {\n T transform(ResultSet rs, String column) throws SQLException;\n}\n\npublic class IntegerResultTransformer implements ResultTransformer&lt;Integer&gt; {\n public Integer transform(ResultSet rs, String column) throws SQLException {\n return rs.getInt(column);\n }\n}\n\npublic class StringResultTransformer implements ResultTransformer&lt;String&gt; {\n public String transform(ResultSet rs, String column) throws SQLException {\n return rs.getString(column);\n }\n}\n\npublic class DoubleResultTransformer implements ResultTransformer&lt;Double&gt; {\n public Double transform(ResultSet rs, String column) throws SQLException {\n return rs.getDouble(column);\n }\n}\n</code></pre>\n\n<p>Now the method will receive a ResultTransformer and just call its method transform:</p>\n\n<pre><code>public &lt;T&gt; T getValueFromDb2(String col, String table, String cond, ResultTransformer&lt;T&gt; transformer) {\n // concatenate strings isn't a good idea, \n // use the PreparedStatement methods: setString, setDouble and so on\n ResultSet rs = getSet(\"SELECT \" + col + \" FROM \" + table + \" WHERE \" + cond);\n try {\n return transformer.transform(rs, col);\n } catch (SQLException e) {\n throw new RuntimeException(e); // don't return null\n }\n}\n</code></pre>\n\n<p>Using the method:</p>\n\n<pre><code>Integer anInteger = getValueFromDb2(\"col\", \"table\", \"cond\", new IntegerResultTransformer());\nString aString = .getValueFromDb2(\"col\", \"table\", \"cond\", new StringResultTransformer());\nDouble aDouble = .getValueFromDb2(\"col\", \"table\", \"cond\", new DoubleResultTransformer());\n</code></pre>\n\n<p>For now on, you just need to create a new ResultTransform implementation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T20:21:02.513", "Id": "28586", "ParentId": "28572", "Score": "4" } } ]
{ "AcceptedAnswerId": "28586", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T17:42:21.050", "Id": "28572", "Score": "1", "Tags": [ "java", "jdbc" ], "Title": "Generic DB Value Getter" }
28572
<p>I have this data for the knapsack problem:</p> <ul> <li>List of product prices = <code>MENU</code></li> <li>Most popular product count = <code>MOST_POPULAR_COCKTAIL</code></li> <li>Knapsack price = <code>CASH</code></li> <li>Knapsack length = <code>CHECK_LEN</code></li> </ul> <p>I need get all knapsack combinations from a list of products prices which satisfy:</p> <ul> <li>List of product prices bigger or equal knapsack length</li> <li>Each price in combination must multiply on different natural number in range from 1 to most popular product price</li> <li>Total combination price must equal knapsack price</li> <li>Combination length must equal knapsack length</li> </ul> <p><strong>settings.py</strong></p> <pre><code>CASH = 6600 CHECK_LEN = 10 MOST_POPULAR_COCKTAIL = 12 MENU = [ {'Безалкогольные': [ { 'name': 'Мохито класический', 'buy_price': 40, 'sell_price': 150, 'sold_today': True, }, { 'name': 'Мохито клубничный', 'buy_price': 40, 'sell_price': 180, 'sold_today': True, }, { 'name': 'Мохито с сиропом', 'buy_price': 40, 'sell_price': 180, 'sold_today': True, }, ]}, {'Тропические': [ { 'name': 'Пляжный витамин', 'buy_price': 40, 'sell_price': 230, 'sold_today': True, }, { 'name': 'Пеликан', 'buy_price': 40, 'sell_price': 180, 'sold_today': True, }, { 'name': 'Наслаждение киви', 'buy_price': 40, 'sell_price': 200, 'sold_today': True, }, { 'name': 'Имбирный лимонад', 'buy_price': 40, 'sell_price': 150, 'sold_today': True, }, ]}, {'Молочные': [ { 'name': 'Молочный шейк', 'buy_price': 40, 'sell_price': 160, 'sold_today': True, }, ]}, {'Освежающие напитки': [ { 'name': 'Свежевыжатый сок', 'buy_price': 40, 'sell_price': 120, 'sold_today': True, }, { 'name': 'Лимонад', 'buy_price': 40, 'sell_price': 120, 'sold_today': True, }, ]}, {'Алкогольные': [ { 'name': 'Мохито классический', 'buy_price': 40, 'sell_price': 250, 'sold_today': True, }, { 'name': 'Мохито клубничный', 'buy_price': 40, 'sell_price': 250, 'sold_today': True, }, { 'name': 'Пина колада', 'buy_price': 40, 'sell_price': 280, 'sold_today': True, }, { 'name': 'Лонг айленд айс ти', 'buy_price': 40, 'sell_price': 350, 'sold_today': True, }, { 'name': 'Восход солнца', 'buy_price': 40, 'sell_price': 280, 'sold_today': True, }, { 'name': 'Секс на пляже', 'buy_price': 40, 'sell_price': 280, 'sold_today': True, }, { 'name': 'Дайкири клубничный', 'buy_price': 40, 'sell_price': 250, 'sold_today': True, }, { 'name': 'Голубая лагуна', 'buy_price': 40, 'sell_price': 250, 'sold_today': True, }, { 'name': 'Маргарита клубничная', 'buy_price': 40, 'sell_price': 250, 'sold_today': True, }, { 'name': 'Виски/ром кола', 'buy_price': 40, 'sell_price': 280, 'sold_today': True, }, ]}, {'Фьюжн': [ { 'name': 'Плантаторский пунш', 'buy_price': 40, 'sell_price': 250, 'sold_today': True, }, { 'name': 'Ураган', 'buy_price': 40, 'sell_price': 320, 'sold_today': True, }, { 'name': 'Май-тай', 'buy_price': 40, 'sell_price': 320, 'sold_today': True, }, { 'name': 'Джин физ клубничный', 'buy_price': 40, 'sell_price': 280, 'sold_today': True, }, { 'name': 'Московский мул', 'buy_price': 40, 'sell_price': 250, 'sold_today': True, }, ]}, ] </code></pre> <p><strong>knapsack.py</strong></p> <pre><code>from itertools import product, izip from decorators import timer import settings class Product(object): def __init__(self, group, name, buy_price, sell_price, count=0): self.group = group self.name = name self.buy_price = buy_price self.sell_price = sell_price self.count = count self.price = count * sell_price self.profit = count * (sell_price - buy_price) class Check(object): def __init__(self, cash, length, most_popular_count, products): self.cash = cash self.length = length self.most_popular = most_popular_count self.products = products self.checks = [] def create_check(self, products_count): check = [] for i, count in enumerate(products_count): check.append(Product( self.products[i].group, self.products[i].name, self.products[i].buy_price, self.products[i].sell_price, count )) return check def remove_zeros(self, check): return tuple(product for product in check if product) def total_value(self, products_count): check = sum(n * product.sell_price for n, product in izip(products_count, self.products)) if check == self.cash and len(self.remove_zeros(products_count)) == self.length: tmp = self.create_check(products_count) self.print_check(tmp) self.checks.append(tmp) return check else: return -1 def knapsack(self): max_1 = [self.most_popular for p in self.products] max(product(*[xrange(n + 1) for n in max_1]), key=self.total_value) def print_check(self, check): def check_str(value, i): value = str(value) len_value = len(value.decode('utf-8')) if len_value &lt; lengths[i]: value += ' ' * (lengths[i] - len_value) return value def print_header(): output_header = [] for i, name in enumerate(header): output_header.append(check_str(name, i)) print ' | '.join(output_header) def print_products(): for cocktail in check: if cocktail.count &gt; 0: print ' | '.join([ check_str(cocktail.name, 0), check_str(cocktail.buy, 1), check_str(cocktail.sell, 2), check_str(cocktail.count, 3), check_str(cocktail.price, 4), check_str(cocktail.profit, 5) ]) header = ('Наименование', 'Покупка', 'Продажа', 'Кол-во', 'Сумма', 'Прибыль') lengths = [len(name.decode('utf-8')) for name in header] spend_sum = 0 count = 0 for cocktail in check: spend_sum += cocktail.price count += cocktail.count lengths[0] = max(lengths[0], len(cocktail.name.decode('utf-8'))) lengths[1] = max(lengths[1], len(str(cocktail.buy_price))) lengths[2] = max(lengths[2], len(str(cocktail.sell_price))) lengths[3] = max(lengths[3], len(str(cocktail.count))) lengths[4] = max(lengths[4], len(str(cocktail.price))) lengths[5] = max(lengths[5], len(str(cocktail.profit))) print_header() print '-' * (sum(lengths) + 15) print_products() print '-' * (sum(lengths) + 15) print 'Закупка: %d руб.' % spend_sum print 'Продажи: %d шт. на %d руб.' % (count, self.cash) print 'Прибыль: %d руб.' % (self.cash - spend_sum) def main(): products = [] for group in settings.MENU: key = group.keys()[0] for cocktail in group[key]: if cocktail['sold_today']: products.append(Product(key, cocktail['name'], cocktail['buy_price'], cocktail['sell_price'])) check = Check(settings.CASH, settings.CHECK_LEN, settings.MOST_POPULAR_COCKTAIL, products) check.knapsack() main() </code></pre> <p>With that algorithm I'll die faster than program solve problem. Could anybody help make this faster?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T18:00:51.157", "Id": "28574", "Score": "3", "Tags": [ "python", "performance", "algorithm", "combinatorics" ], "Title": "Python knapsack program" }
28574
<p>I think the arrays here are slowing down my code due to incorrect usage. </p> <p>There is a lot of stuff going on here, it's understandable if nobody responds. Just looking for some pointers. Thanks.</p> <pre><code>for MN in xrange(RowModel,TotalModels): if(MN%5000==0):print 'Examining models', MN,'to', (MN+5000), '...' fobs=fobstemp fobserr=fobstemp*0.1 #10% error y=np.array([]) fmod=np.array([]) </code></pre> <p>I was reading that it can be memory exhaustive to run for loops and range functions over numpy arrays and it is better instead to run np.arange[]. Can anyone validate this statement? I'm not sure how to implement it here where RowModel and TotalModels are separate arrays. And assuming they are the same dimensions.</p> <p>Here's the section of that code (which starts off with the above snippet). Ultimately the values at the end are used in a statistical calculation. The code works but it's insanely slow at this portion.</p> <pre><code>for MN in xrange(RowModel,TotalModels): if(MN%5000==0):print 'Examining models', MN,'to', (MN+5000), '...' fobs=fobstemp fobserr=fobstemp*0.1 #10% error y=np.array([]) fmod=np.array([]) #Set the scale factor #units are already embedded in scalemult [mJy] if(modcalibrate&lt;=13): scale= (10**(convertStr(data[RowStar][calibrate])/-2.5)*10**(0.4*tau_mag[choice-1])*scalemult)/((convertStr(model[MN][modcalibrate])*1e+03*Fbol*1e+23)/(c/wavelengthmodel[modcalibrate-10])) else: scale= (convertStr(data[RowStar][calibrate])*10**(0.4*tau_mag[choice-1]))/(convertStr(model[MN][modcalibrate])*Fbol*1e+029/(c/wavelengthmodel[modcalibrate-10])) #Convert the model data into fluxes and insert into array fmod # for i in xrange(10+len(wavelength)-2):#2 repeats y=np.append(y,model[MN][i]) for i in xrange(10,10+len(wavelength)-2): #2 repeats Alambda=Ak/wavelength[i-10] fmod=np.append(fmod,convertStr(y[i])*Fbol*scale*1e+023*1e+03/(c/wavelengthmodel[i-10])) if i== 11: fmod=np.append(fmod,convertStr(y[i])*Fbol*scale*1e+023*1e+03/(c/wavelengthmodel[i-10])) if i== 13: fmod=np.append(fmod,convertStr(y[i])*Fbol*scale*1e+023*1e+03/(c/wavelengthmodel[i-10])) #Delete the components that are not shared between fobs and fmod # j=0 for i in xrange(len(wavelength)): if j&lt;=len(fobs)-1: if -10&lt;fobs[j]&lt;-9: fobs=np.delete(fobs,j,None) fobserr=np.delete(fobserr,j,None) fmod=np.delete(fmod,j,None) else: j=j+1 #Calculate Chi^2 for the model and insert into an array # scalefactor=np.append(scalefactor,scale) chi2_new=np.sum(((fobscaled-fmod)/(fobserr))**2)/(len(fobscaled)-1) chi2=np.append(chi2,chi2_new) if chi2_new&lt;ChiThresh: #User input required here for Chi threshold maximum. BestFitsModel=np.append(BestFitsModel,MN) BestFitsChi=np.append(BestFitsChi,chi2_new) BestFitsScale=np.append(BestFitsScale,scale) counter=counter+1 temp=np.sort(chi2) </code></pre> <p>wavelengthmodel is defined as an array of size 8. (8 entries, all floats).</p> <p>wavelength is defined as an array of size 11 (11 entries, all floats).</p> <p>modcalibrate is an index array which corresponds to a list imported elsewhere.</p> <p>MN is a numerical array starting at 0 and ending at some large number. This corresponds to TopModels and RowModel which starts at <code>0</code> (RowModel value) and ends at <code>n</code> (TopModels value).</p> <p>Anything else undefined in this script-section is an empty array until filled here, except 'ChiThresh' which is an integer of user input.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T19:05:26.670", "Id": "44875", "Score": "0", "body": "Where did you read that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T19:12:09.257", "Id": "44876", "Score": "0", "body": "Looks like you wrote it...maybe I misunderstood? Here's the [link](http://codereview.stackexchange.com/questions/3808/python-optimize-this-rolling-loop)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T19:23:23.160", "Id": "44877", "Score": "0", "body": "The concern is less memory and more processing time. Using arange instead of range won't really help. You need to avoid for loops. You can get help doing that here, but you'll need to actual show working code. i.e. show us code that does the right thing, even if its slow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T19:30:53.147", "Id": "44878", "Score": "0", "body": "I was afraid of that. I'll post the code via github and link it in the original post. It's long, ugly, and very slow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T19:32:13.280", "Id": "44879", "Score": "0", "body": "see the FAQ, you aren't allowed to just link code. You must at least include some portion of it in the question." } ]
[ { "body": "<p>You should almost never be using <code>np.append</code>, numpy arrays are designed to be used as fixed size arrays. <code>np.append</code> creates a whole new array each time and will thus fairly expensive. </p>\n\n<p>The first thing is that you should create the array at its full size. Then assign to the elements:</p>\n\n<pre><code>y = np.empty(10+len(wavelength)-2, int) # I don't know the type, guessing here\nfor i in xrange(10+len(wavelength)-2):#2 repeats\n y[i] = model[MN][i]\n</code></pre>\n\n<p>The second thing is that you should look for numpy operations to do the same thing your loop does. In this case, I can actually replace that code by:</p>\n\n<pre><code>y = model[MN, :10 + len(wavelength) - 2]\n</code></pre>\n\n<p>This assumes that model is a numpy array. If it is isn't, you should make it one.</p>\n\n<p>Let's look at the code for fmod</p>\n\n<pre><code>for i in xrange(10,10+len(wavelength)-2): #2 repeats\n Alambda=Ak/wavelength[i-10]\n fmod=np.append(fmod,convertStr(y[i])*Fbol*scale*1e+023*1e+03/(c/wavelengthmodel[i-10]))\n if i== 11:\n fmod=np.append(fmod,convertStr(y[i])*Fbol*scale*1e+023*1e+03/(c/wavelengthmodel[i-10]))\n if i== 13:\n fmod=np.append(fmod,convertStr(y[i])*Fbol*scale*1e+023*1e+03/(c/wavelengthmodel[i-10]))\n</code></pre>\n\n<p>It is not as obvious how to vectorize this code. Firstly, we can clean up the code a bit. Eliminate the unused Alambda, eliminate duplicate pieces of code, and change the loop to start with zero. (When trying to vectorize you pretty much always want to start by changing your loops to start with 0).</p>\n\n<pre><code>for i in xrange(len(wavelength)-2): #2 repeats\n value = convertStr(y[i+ 10])*Fbol*scale*1e+023*1e+03/(c/wavelengthmodel[i])\n fmod=np.append(fmod, value)\n if i == 11 or i == 13:\n fmod = np.append(fmod, value)\n</code></pre>\n\n<p>It is still not clear how to break up this loop, so we apply a general strategy of breaking up a loop. If a loop does multiple things, we break the loop up so that the loop only does one thing. Here is the first loop.</p>\n\n<pre><code>value = numpy.empty( len(wavelength) - 2)\nfor i in xrange(len(wavelength) - 2):\n value[i] = convertStr(y[i+10])*Fbol*scale*1e+023*1e+03/(c/wavelengthmodel[i])\n</code></pre>\n\n<p>Once we have the loop down to the simple level of assigning to each element, we want to vectorize it. I don't know what <code>convertStr</code> does, but I'll assume it can be adapted to vectorize whatever I pass into it. So I can replace this loop by:</p>\n\n<pre><code>value = convertStr(y[10:])*Fbol*scale*1e+023*1e+03/(c/wavelengthmodel)\n</code></pre>\n\n<p>Let's move onto the second loop</p>\n\n<pre><code>for i in xrange(len(wavelength)-2): #2 repeats\n fmod=np.append(fmod, value[i])\n if i == 11 or i == 13:\n fmod = np.append(fmod, value[i])\n</code></pre>\n\n<p>This essentially copies value, but introduces repeats. There are few ways this could be accomplished. Probability the simplest would be:</p>\n\n<pre><code>fmod = np.empty( len(wavelength), int)\nfmod[0:11] = value[0:11]\nfmod[11:13] = value[11]\nfmod[13] = value[12]\nfmod[14:17] = value[13]\nfmod[17:] = value[14:]\n</code></pre>\n\n<p>Hopefully that gives you an idea of how to approach improving the performance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T21:31:01.887", "Id": "44886", "Score": "0", "body": "Wow, thanks. I have to absorb all of this for sure. I'd give you a +1 but my minuscule reputations prevents it. THANKS!!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T21:33:47.287", "Id": "44887", "Score": "0", "body": "Question: In your first breakdown of my code where you show how to create the `y` array, would I still need to declare `y` as an array like I've done? Or is that created assigned automatically with np.empty?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T21:38:01.507", "Id": "44888", "Score": "1", "body": "@Matt, in python the syntax `y = ?` always throws away whatever was in `y`. So `y = numpy.empty(?)` creates a new array and doesn't need you to have created an array in y." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T21:23:21.783", "Id": "28589", "ParentId": "28582", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T18:53:43.797", "Id": "28582", "Score": "2", "Tags": [ "python", "array", "numpy" ], "Title": "What would be the optimal way to address these arrays" }
28582
A weak reference is a reference that does not protect the referenced object from deallocation
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T02:04:05.410", "Id": "28591", "Score": "0", "Tags": null, "Title": null }
28591
<p><strong>Edit:</strong> The method call discussed is a public extension method in a shared library. I'd like it to be safe for others to call.</p> <p>A little background: I'm maintaining an ancient system written in ASP.Net Webforms. There are lots of validation groups for different user controls, and we want to display the error messages from them in modal dialogs at the page level. Rather then deal with the complexities of having a ValidationSummary for each possible validation group, we're just getting all the validation messages from each user control, making one list of validation messages, and displaying the resulting list in a modal. Easy-peasy.</p> <p>A co-worker was writing the methods to return validation messages from ASP.Net Validator controls nested inside his user controls. He was writing the methods explicitly:</p> <pre><code>if (!Validator1.IsValid) { messages.Add(Validator1.ErrorMessage); } etc... </code></pre> <p>I decided to be slick and make an extension method to loop over the Controls collection of a given control (including pages and user controls) and just examine each validator encountered. This way I don't have to write and maintain lots of explicit "GetErrorMessages()" implementations. I don't have problems if somebody renames, removes, or adds a validator and forgets to include it explicitly:</p> <pre><code>public static IEnumerable&lt;string&gt; GetValidatorMessages(this Control control, string validationGroup) { var messages = new List&lt;string&gt;(); var validator = control as BaseValidator; if (validator != null &amp;&amp; IsInvalid(validator, validationGroup)) { messages.Add(validator.ErrorMessage); } if (control.Controls.Any()) { foreach (Control childControl in control.Controls) { messages.AddRange(GetValidatorMessages(childControl, validationGroup)); } } return messages; } </code></pre> <p>Still, this feels imperfect. I'm iterating EVERY CONTROL in the given control. If this is a page, we could be talking lots of nested things in a DataGrid, for example.</p> <p>Is there are faster way to get all the validation messages from a Page or UserControl?</p> <p><strong>Second Edit:</strong> @Abbas got me thinking along the lines of using a generic (see his answer) but I don't want to encourage using this method with unusual input types like DropDownList, RadioButton, or other ASP.Net controls that CAN have children in their Controls collection, but generally should not.</p> <p>But, thanks again to him, thinking along the lines of evaluating the minimum number of controls possible, I came up with using the control's Page property to reach the Page.Validators property, which is explicitly set when validators are created instantiated rather than recursively looking at children like my original method does. I wound up with something like the following. Called extension methods are included for clarity's sake:</p> <pre><code>public static IEnumerable&lt;string&gt; GetValidatorMessages(this Control control, string validationGroup) { var messages = new List&lt;string&gt;(); // If the given control is an invalid validator, get it's error message. var validator = control as BaseValidator; if (validator != null &amp;&amp; validator.IsValid == false) { messages.Add(validator.ErrorMessage); } // Get all the validators that are a child of the given control var childValidators = control.Page.Validators .Cast&lt;BaseValidator&gt;() .Where(v =&gt; v.IsChildOf(control) &amp;&amp; v.ValidationGroup == validationGroup); // Return messages from just those that are not valid. messages.AddRange(childValidators .Where(childValidator =&gt; childValidator.IsValid == false) .Select(childValidator =&gt; childValidator.ErrorMessage)); return messages; } public static bool IsChildOf(this Control control, Control parentControl) { // Recursively seek through the given control's parents until we either null out, or find the given parentControl. return control.Parent != null &amp;&amp; (control.Parent == parentControl || control.Parent.IsChildOf(parentControl)); } </code></pre> <p>This solution still uses recursion to determine if each validator is a child of the given control. But it only ever checks controls that are Validators to begin with, since it gets Control.Page.Validators and works from that collection rather than recursively looking at every child of Control and checking to see if the child is a validator.</p> <p>I feel I get a couple of things here:</p> <p>1) Much faster than the original in worst cases. 2) Simple API... No need for a generic parameter.</p> <p>Thoughts?</p>
[]
[ { "body": "<p>You could filter out the type of controls you do not want to iterate. Let's say for example that you only want to get the validationMessages from only a <code>UserControl</code>, you can filter them out of the <code>Controls</code> property by using a bit of LinQ:</p>\n\n<pre><code>public static IEnumerable&lt;string&gt; GetValidatorMessages(this Control control, string validationGroup)\n{\n var messages = new List&lt;string&gt;();\n var validator = control as BaseValidator;\n\n if (validator != null &amp;&amp; IsInvalid(validator, validationGroup))\n messages.Add(validator.ErrorMessage);\n\n foreach (var childControl in control.Controls.OfType&lt;UserControl&gt;())\n messages.AddRange(GetValidatorMessages(childControl, validationGroup));\n\n return messages;\n}\n</code></pre>\n\n<p><strong>Edit:</strong></p>\n\n<p>I found that in your original code in the method, when making the recursive call, you don't make use of the extension-call:</p>\n\n<pre><code>messages.AddRange(GetValidatorMessages(childControl, validationGroup));\n</code></pre>\n\n<p>This should/could be:</p>\n\n<pre><code>messages.AddRange(childControl.GetValidatorMessages(validationGroup));\n</code></pre>\n\n<p>Otherwise, what's the use of making an extension-method? ;)</p>\n\n<p>Anyway...\nAs you stated in your comment, one can indeed not assume that a person would always want to traverse only a <code>UserControl</code>. Thank God for generics! :D You keep your method but you make it a generic one. When calling the method you specify the type of control you want to traverse. Here's some code I came up with. Please mind that I haven't been able to test this as this is just written out of my head:</p>\n\n<pre><code>public static IEnumerable&lt;string&gt; GetValidatorMessages&lt;T&gt;(this Control control, string validationGroup)\n where T : Control\n{\n var messages = new List&lt;string&gt;();\n var validator = control as BaseValidator;\n\n if (validator != null &amp;&amp; IsInvalid(validator, validationGroup))\n messages.Add(validator.ErrorMessage);\n\n foreach (var childControl in control.Controls.OfType&lt;T&gt;())\n names.AddRange(childControl.GetValidatorMessages&lt;T&gt;(validationGroup));\n\n return names;\n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T17:14:46.770", "Id": "44927", "Score": "0", "body": "This is a good idea. For my current scope, I could do this. However, this is a public extension method in a shared library. I'd not be comfortable making the assumption that the caller only wants to traverse UserControls. Note: I'm sorry I didn't mention this in the original question. I'll go edit it now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T20:08:02.523", "Id": "44936", "Score": "0", "body": "Please check my updated answer for further help. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T21:41:49.253", "Id": "44946", "Score": "1", "body": "Thanks for the help! Couple of things:\n1) Extension methods can be called as a static method or with the extension syntax. For me the standard static call is clearer since I am used to seeing recursive methods called with this syntax. The extension syntax still applies to any outside caller. But honestly for me, either way is fine.\n\n2) Yes, everybody loves generics, but in this case I think it encourages some weird calls, like control.GetValidatorMessages<DropDownList>(groupName); I'm not sure I want to encourage that. You got me thinking though. I'll add a second \"Edit\" to my question." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T15:09:07.320", "Id": "28604", "ParentId": "28602", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T14:47:43.060", "Id": "28602", "Score": "2", "Tags": [ "c#", "asp.net", "validation" ], "Title": "Is there a faster way to get ASP.Net Validation messages in a Page or UserControl?" }
28602
<p>I'd like some opinions about my approach at using SQLite databases in android. Everything seems to work very well, but there may be something wrong that I hadn't noticed.</p> <p>I don't like working with create/alter table statements in code, so I prefer creating my database with some SQLite client out there and putting it in assets folder. I use some logic to decide when the database must be replaced and which records need to be kept, then use this code in a class called DbManager:</p> <pre><code>private static SQLiteDatabase _db = null; public static Object lock = new Object(); private static SQLiteDatabase getDB() { if (_db == null) { _db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE); } return _db; } //this is the approach used for insert operations, but is the same for update, delete etc public static boolean insert(String tableName, ContentValues values) { try { return getDB().insert(tableName, null, values) &gt;= 0; } catch (Exception e) { LogHelper.WriteLogError("error in DB_manager.insert function", e); return false; } } public static synchronized void beginTransaction(String who) { LogHelper.WriteLogDebug("starting transaction by " + (who == null ? "null" : who)); try { //in this way if a transaction is still executing it waits untill the previus ends. //obviously every time i call DbManager.beginTransaction the call at DbManager.endTransaction is in the finally statment if (_db.inTransaction()) { LogHelper.WriteLogInfo("DB IS IN TRANSACTION"); synchronized (lock) { lock.wait(); } } getDB().beginTransactionWithListener(new SQLiteTransactionListener() { @Override public void onRollback() { synchronized (lock) { LogHelper.WriteLogInfo("onRollback listener invoked"); lock.notifyAll(); } } @Override public void onCommit() { synchronized (lock) { LogHelper.WriteLogInfo("onCommit listener invoked"); lock.notifyAll(); } } @Override public void onBegin() { // TODO Auto-generated method stub } }); } catch (Exception e) { LogHelper.WriteLogError("error calling begin transaction by " + (who == null ? "null" : who), e); } } public static void endTransaction(boolean commitChanges, String who) { LogHelper.WriteLogDebug("ending transaction by " + (who == null ? "null" : who)); try { if (commitChanges) getDB().setTransactionSuccessful(); getDB().endTransaction(); } catch (Exception e) { LogHelper.WriteLogError("error calling end transaction by " + (who == null ? "null" : who), e); } } </code></pre>
[]
[ { "body": "<p>The code looks fine to me but it is a bit odd because <a href=\"http://developer.android.com/guide/topics/data/data-storage.html#db\">the official docs recommend creating a <code>SQLiteOpenHelper</code> subclass</a> to handle database interaction. And if you use one <code>SQLiteOpenHelper</code> instance across your application, it will be thread-safe so there's no need to add your own synchronization logic:</p>\n\n<pre><code>public class DatabaseHelper extends SQLiteOpenHelper {\n\n private static final String DATABASE_NAME = \"location_scout.db\";\n private static final int SCHEMA_VERSION = 1;\n\n // Singleton pattern\n private static DatabaseHelper instance;\n public synchronized static DatabaseHelper getInstance(Context context) {\n if(instance == null) {\n instance = new DatabaseHelper(context.getApplicationContext());\n }\n return instance;\n }\n\n private DatabaseHelper(Context context) {\n super(context, DATABASE_NAME, null, SCHEMA_VERSION);\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T00:48:28.940", "Id": "59379", "Score": "0", "body": "Could you add a link to the docs? Also, is it really necessary to use it as singleton?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T02:01:25.900", "Id": "59381", "Score": "1", "body": "@SimonAndréForsberg: It's not _required_ but it's the easiest way to make it thread-safe and not run into memory leak issues. More info: http://www.androiddesignpatterns.com/2012/05/correctly-managing-your-sqlite-database.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T20:48:49.503", "Id": "59509", "Score": "0", "body": "Damn yes! I use SQLight a lot on Android. But somehow I missed this... Thanks for this hint." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T17:51:36.680", "Id": "36230", "ParentId": "28605", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T15:21:57.873", "Id": "28605", "Score": "5", "Tags": [ "java", "android", "sqlite" ], "Title": "Android SQLite Database management" }
28605
<p>I've taken a stab at making a context menu using BackboneJS.</p> <p>Here's the overall structure:</p> <blockquote> <p>Collections:</p> <ul> <li>/collection/contextMenuGroups</li> <li>/collection/contextMenuItems</li> </ul> <p>Models:</p> <ul> <li>/model/contextMenu</li> <li>/model/contextMenuGroup</li> <li>/model/contextMenuItem</li> </ul> <p>Views:</p> <ul> <li>/view/contextMenuView</li> </ul> </blockquote> <p>To start off, lets take a look at my template:</p> <pre><code>&lt;script type="text/template" id="contextMenuTemplate"&gt; &lt;% groups.each(function(group){ %&gt; &lt;ul id="group_&lt;%= group.cid %&gt;"&gt; &lt;% group.get('items').each(function(item){ %&gt; &lt;li&gt; &lt;a id="groupItem_&lt;%= item.cid %&gt;" href="#"&gt;&lt;%= item.get('text') %&gt;&lt;/a&gt; &lt;/li&gt; &lt;% }); %&gt; &lt;/ul&gt; &lt;% }); %&gt; &lt;/script&gt; </code></pre> <p>My template is created such that each <code>contextMenuGroup</code> provided to it creates a new unordered list. Each item in each group creates a link inside of a <code>listItem</code> for the given unordered list.</p> <p>Here's my view:</p> <pre><code>define(['contextMenu'], function (ContextMenu) { 'use strict'; var ContextMenuView = Backbone.View.extend({ className: 'contextMenu', template: _.template($('#contextMenuTemplate').html()), parentSelector: 'body', render: function () { this.$el.html(this.template(this.model.toJSON())); // Prevent display outside viewport. var offsetTop = this.top; var needsVerticalFlip = offsetTop + this.$el.height() &gt; $(this.parentSelector).height(); if (needsVerticalFlip) { offsetTop = offsetTop - this.$el.height(); } var offsetLeft = this.left; var needsHorizontalFlip = offsetLeft + this.$el.width() &gt; $(this.parentSelector).width(); if (needsHorizontalFlip) { offsetLeft = offsetLeft - this.$el.width(); } // Show the element before setting offset to ensure correct positioning. this.$el.show().offset({ top: offsetTop, left: offsetLeft }); return this; }, initialize: function () { // TODO: If I implement Backbone View's more properly, then 'body' should be responsible for this, but for now this is fine. this.$el.appendTo(this.parentSelector); var self = this; // Hide the context menu whenever any click occurs not just when selecting an item. $(this.parentSelector).on('click contextmenu', function () { self.$el.hide(); }); }, show: function (options) { if (options.top === undefined || options.left === undefined) throw "ContextMenu must be shown with top/left coordinates."; if (options.groups === undefined) throw "ContextMenu needs ContextMenuGroups to be shown."; this.top = options.top; this.left = options.left; this.model = new ContextMenu({ groups: options.groups }); this.render(); } }); return ContextMenuView; }); </code></pre> <p>To display a <code>contextMenu</code>, I call <code>show</code> and pass to show top/left coordinates as well as a model to render inside of the context menu.</p> <p>Usage:</p> <pre><code>showContextMenu: function (event, queueItem) { var queueContextMenuGroups = [{ position: 0, items: [{ position: 0, text: 'Clear Queue' }] }]; if (queueItem) { queueContextMenuGroups.push({ position: 1, items: [{ position: 0, text: 'Remove ' + queueItem.get('title') }] }); } this.contextMenuView.show({ top: event.pageY, left: event.pageX + 1, groups: queueContextMenuGroups }); return false; } </code></pre> <p>Here, I create an anonymous array of objects (groups) which contains some items to render.</p> <p>This all works great, but I have no idea how to bind generic events! Should I be extending my <code>ContextMenuView</code> with a 'specific' implementation which can define its events?</p>
[]
[ { "body": "<p>I like the code as is,</p>\n\n<ul>\n<li>Use of <code>'use strict'</code></li>\n<li>JsHint cannot find anything</li>\n<li>Readable, well named variables</li>\n<li>No obvious copy pasting or repeated code</li>\n</ul>\n\n<p>As for events, I would </p>\n\n<ul>\n<li>Wait until everything is rendered</li>\n<li>Add a <code>$.click()</code> to each menu item, item by selecting on a classname used only by those menu items, or you could re-build the id's of each menu item and attach to each one individually ( first approach would be much better ).</li>\n<li>Then I would use <code>$.trigger()</code> to send out an event with the text of the button</li>\n<li>Register whoever needs to know that a menu item was clicked for that event</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-28T14:57:30.670", "Id": "48405", "ParentId": "28606", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T16:45:56.697", "Id": "28606", "Score": "3", "Tags": [ "javascript", "jquery", "backbone.js" ], "Title": "A generic context menu with generically bound events" }
28606
<p>Is this acceptable for readability or would it be better to refactor it into smaller methods?</p> <p>Tips? Comments? Examples?</p> <pre><code>def save_with_payment if valid? charge = Stripe::Charge.create(:amount =&gt; (self.plan.price * 100).to_i, :currency =&gt; 'usd', :card =&gt; stripe_card_token, :description =&gt; "Charge for #{user.email}") self.stripe_charge_id = charge.id self.starts_at = Date.today self.amount = plan.price self.expires_at = 1.years.from_now save! end rescue Stripe::InvalidRequestError =&gt; e logger.error "Stripe error while creating charge: #{e.message}" errors.add :base, "There was a problem with your credit card." false end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T03:37:20.617", "Id": "44959", "Score": "0", "body": "Is it a joke?.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T06:51:47.193", "Id": "44962", "Score": "0", "body": "@Nakilon, are you answering a deleted comment? otherwise I don't see the joke." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T11:13:13.473", "Id": "44981", "Score": "0", "body": "@tokland, I don't the complexity nor unreadability nor hugeness in this code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T11:35:55.110", "Id": "44982", "Score": "0", "body": "I see. Well, I think the OP was just being modest, indeed it's not complex nor unreadable, but of course it can be improved (as any other code), I'll post an answer later." } ]
[ { "body": "<p>I would refactor the <code>Charge.create</code> to a separate class.</p>\n\n<p>Because one the principies that we have respect is \"our code reader should not read the details of the implementation for understand the code\"</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T06:54:29.600", "Id": "44964", "Score": "0", "body": "Please explain why you would do this. (In the meantime -1)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T06:55:42.577", "Id": "44965", "Score": "0", "body": "I would extract it to a own method, just to get rid of the long line and give it a descriptive name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T09:35:55.817", "Id": "44979", "Score": "0", "body": "I explain it, it's my opinion" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T16:22:24.823", "Id": "45076", "Score": "0", "body": "That's a good point (the answer's point, not the comment's point)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T06:24:04.717", "Id": "28631", "ParentId": "28607", "Score": "0" } }, { "body": "<p>Some notes about your code:</p>\n\n<ul>\n<li>Indentation of a call with multi-line hash: That's subjective, but this style you use wastes a lot of space, and it's pretty hard to read (because of the longer lines). If the hash is long I prefer to use the one-line-per-key/value JSON style. More on this <a href=\"https://code.google.com/p/tokland/wiki/RubyIdioms#Multi-line_array/hashes\" rel=\"nofollow\">here</a>.</li>\n<li><code>self.stripe_charge_id = charge.id</code>: When you have a lot of sets + <code>save!</code> it is better just to use <code>update_attributes!</code>.</li>\n<li><code>save!</code>: The method is named <code>save_with_payment</code>, in a ActiveRecord context that means this method won't raise an exception, so you should call <code>save</code>. </li>\n<li><code>if valid?</code>: No <code>else</code> branch? The method seems to return a boolean so returning <code>false</code> in that case would be more consistent.</li>\n<li><code>rescue Stripe::InvalidRequestError =&gt; e</code>: That's a long and subjective topic. My opinion: don't wrap a whole method that is doing lots of things with a <code>rescue</code>, the logic forms now some kind of spaghetti. Wrap the specific parts of the code that may raise that particular exception.</li>\n<li><code>Stripe::Charge.create</code>: You asked if the code is too complex. I don't think so, at least not compared with typical Ruby practices, but it's probably more orthodox to create a separate method for this call.</li>\n<li><code>errors.add :base,</code>: I don't like this mixing of calls with parens and calls without, it looks messy. DSL-style code in Rails without parens -> ok, normal code in methods -> not so sure, I'd write them. Or at least be consistent.</li>\n<li><code>self.plan</code>: It's not idiomatic to write explicit <code>self.</code> to call instance methods.</li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>def save_with_payment\n if !valid?\n false\n elsif !(charge = create_stripe_charge)\n errors.add(:base, \"There was a problem with your credit card.\")\n false\n else\n update_attributes({\n :stripe_charge_id =&gt; charge.id,\n :starts_at =&gt; Date.today,\n :amount =&gt; plan.price,\n :expires_at =&gt; 1.years.from_now,\n })\n end\nend\n\ndef create_stripe_charge\n Stripe::Charge.create({\n :amount =&gt; (plan.price * 100).to_i,\n :currency =&gt; 'usd', \n :card =&gt; stripe_card_token, \n :description =&gt; \"Charge for #{user.email}\",\n })\nrescue Stripe::InvalidRequestError =&gt; e\n logger.error(\"Stripe error while creating charge: #{e.message}\")\n nil\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T16:17:08.277", "Id": "28655", "ParentId": "28607", "Score": "2" } } ]
{ "AcceptedAnswerId": "28655", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-07-17T16:48:42.710", "Id": "28607", "Score": "1", "Tags": [ "ruby", "e-commerce" ], "Title": "Saving a subscription plan with a payment" }
28607
<p>I frequently write Python scripts that require three command line arguments:</p> <ol> <li><code>config_file</code> — A CSV configuration file</li> <li><code>input_dir</code> — The directory containing the input files to be processed</li> <li><code>output_dir</code> — The directory where the output files should be stored</li> </ol> <p>I found myself copying/pasting two functions all the time: <code>is_valid_file</code> and <code>is_valid_directory</code>.</p> <h2>Questions</h2> <ol> <li>How can I consolidate the <code>is_valid_file</code> and <code>is_valid_directory</code> functions to eliminate duplicate code?</li> <li>Is there a better way to check that files/directories provided in CLI arguments actually exist?</li> </ol> <h2>Code</h2> <p>Here is the code for <code>process_the_data.py</code>:</p> <pre><code>if __name__ == "__main__": # Process the arguments import argparse import arghelper parser = argparse.ArgumentParser( description='Process the data.') parser.add_argument( 'config_file', help='CSV configuration file.', metavar='FILE', type=lambda x: arghelper.is_valid_file(parser, x)) parser.add_argument( 'input_dir', help='Directory containing the input files.', metavar='DIR', type=lambda x: arghelper.is_valid_directory(parser, x)) parser.add_argument( 'output_dir', help='Directory where the output files should be saved.', metavar='DIR', type=lambda x: arghelper.is_valid_directory(parser, x)) args = parser.parse_args() </code></pre> <p>Here is the code for <code>arghelper.py</code>:</p> <pre><code>import os def is_valid_file(parser, arg): if not os.path.isfile(arg): parser.error('The file {} does not exist!'.format(arg)) else: # File exists so return the filename return arg def is_valid_directory(parser, arg): if not os.path.isdir(arg): parser.error('The directory {} does not exist!'.format(arg)) else: # File exists so return the directory return arg </code></pre>
[]
[ { "body": "<p>You can address some of this by subclassing ArgumentParser. This will allow you hide the lambda calls that may turn off some and leave you scratching your head if you come back to that file later.</p>\n\n<p><strong>Your Script</strong> </p>\n\n<pre><code>if __name__ == \"__main__\":\n # Process the arguments\n #import argparse\n import arghelper\n parser = arghelper.FileArgumentParser(\n description='Process the data.')\n parser.add_argument_with_check(\n 'config_file',\n help='CSV configuration file.',\n metavar='FILE')\n parser.add_argument_with_check(\n 'input_dir',\n help='Directory containing the input files.',\n metavar='DIR')\n parser.add_argument_with_check(\n 'output_dir',\n help='Directory where the output files should be saved.',\n metavar='DIR')\n args = parser.parse_args()\n print args\n</code></pre>\n\n<p><strong>New ArgHelper</strong> </p>\n\n<pre><code>import argparse\nimport os\n\n\nclass FileArgumentParser(argparse.ArgumentParser):\n def __is_valid_file(self, parser, arg):\n if not os.path.isfile(arg):\n parser.error('The file {} does not exist!'.format(arg))\n else:\n # File exists so return the filename\n return arg\n\n def __is_valid_directory(self, parser, arg):\n if not os.path.isdir(arg):\n parser.error('The directory {} does not exist!'.format(arg))\n else:\n # File exists so return the directory\n return arg\n\n def add_argument_with_check(self, *args, **kwargs):\n # Look for your FILE or DIR settings\n if 'metavar' in kwargs and 'type' not in kwargs:\n if kwargs['metavar'] is 'FILE':\n type=lambda x: self.__is_valid_file(self, x)\n kwargs['type'] = type\n elif kwargs['metavar'] is 'DIR':\n type=lambda x: self.__is_valid_directory(self, x)\n kwargs['type'] = type\n self.add_argument(*args, **kwargs)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T15:08:17.283", "Id": "411299", "Score": "0", "body": "At line 8 self.error('The file {} does not exist!'.format(arg)) is enough. Line 9 \"else\" not needed. \"parser\" is same as self." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T19:33:33.983", "Id": "28614", "ParentId": "28608", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T17:06:31.357", "Id": "28608", "Score": "5", "Tags": [ "python" ], "Title": "Checking if CLI arguments are valid files/directories in Python" }
28608
<p>I've got a class with a property <code>TotalCost</code>, which is calculated by some simple math of two other properties, <code>CostOfFood</code> and <code>NumberOfPeople</code>. The code works the way I want it to, but I was wondering if this is a satisfactory method in the long run of application development, a bad idea to have one property that depends on another all together (I'm pretty sure this is the case, but sometimes it makes sense to), or if the informed reader would deem it acceptable. Helpful hints are in the comments.</p> <pre><code>class DinnerParty { private int numberOfPeople; public int NumberOfPeople { get { return numberOfPeople; } set { numberOfPeople = value; //TotalCost property is updated when more people are added to the party TotalCost =CalculateFoodCost(value); } } private decimal totalCost; public decimal TotalCost { get { return totalCost; } private set { totalCost = value; } } private decimal costOfFood; public decimal CostOfFood { get { return costOfFood; } set { costOfFood = value; //TotalCost property is updated when CostOfFood changes //directly below line was my initial idea //TotalCost = value * NumberOfPeople was my initial thought //before overloading the CalculateFoodCost method //this calls the CalculateFoodCost version that takes a decimal TotalCost = CalculateFoodCost(value); } } private decimal CalculateFoodCost(int costOfFood) { //the int coming in as a parameter is the 'value' of the NumberOfPeople property return this.costOfFood * NumberOfPeople; } private decimal CalculateFoodCost(decimal costOfFood) { return this.costOfFood * NumberOfPeople; } public DinnerParty() { //so food cost is never 0 CostOfFood = 10; } } </code></pre> <p>Testing</p> <pre><code>DinnerParty d = new DinnerParty(); d.NumberOfPeople = 1; Console.WriteLine(d.TotalCost);//output = 10 d.CostOfFood = 2; Console.WriteLine(d.TotalCost);//CostOfFood changed, output =2 d.NumberOfPeople = 2; Console.WriteLine(d.TotalCost);//output=4; d.CostOfFood = 3; Console.WriteLine(d.TotalCost); //output =6 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T18:11:20.793", "Id": "44930", "Score": "2", "body": "Your incoming parameter to the `CalculateFoodCost()` isn't doing anything, in either case; I'd probably remove it (especially as you're not actually obeying the contract, as your comment explains). Heck, for something that simple, I'd probably remove the backing variable, and just run the calculation in the getter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T18:13:15.170", "Id": "44931", "Score": "0", "body": "@Clockwork-Muse you're right, I kind of mangled it so I could get it to work by passing the parameter `value` in both instances." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T20:17:36.120", "Id": "44937", "Score": "0", "body": "Applying [Garry's excellent answer](http://codereview.stackexchange.com/a/28612/8243) renders the following advice moot, but the information is important for future reference. `TotalCost` would be cleaner if you used an [auto-implemented property](http://msdn.microsoft.com/en-us/library/bb384054.aspx) (Requires C# 3.0+). Auto-implemented properties are just syntactic sugar to generate and use a backing field. In your case, you would remove `totalCost` and would replace the `TotalCost` property with `public decimal TotalCost {get;private set;}`." } ]
[ { "body": "<p>The C# property model allows external classes to inspect (or set) a given member as though it were a public 'field', and the implementation details are left to the property's accessor and mutator. In your case, you want to expose TotalCost and hide the implementation details about how it is derived. And your code reflects best practices. </p>\n\n<p>Following the comment from Clockwork-Muse, your implementation can be made more elegant by...</p>\n\n<pre><code> public decimal TotalCost\n {\n get { return CostOfFood * NumberOfPeople; }\n }\n</code></pre>\n\n<p>This avoids the calculation penalty for setting either of the calculation ingredients and performs the calculation only when called upon to do so. It's also a bit more readable and transparent. In this particular case, there's no need for an asymmetric mutator, so it's been removed. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T18:57:17.837", "Id": "44933", "Score": "0", "body": "I wasn't aware that you could leave out the backing variable and still use a return statement in the get clause. I actually just returned to this question to find that you had the exact same idea as me. :) +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T18:59:14.417", "Id": "44934", "Score": "0", "body": "Remember that if you eventually go to WPF, it's a whole new ball game where setters are vital to making it work. But for this question, you're doing fine" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T19:03:47.083", "Id": "44935", "Score": "0", "body": "Appreciate it. I'm slowly but surely getting down the nitty gritty with C# and I'm always trying to toe the tenuous line of 'it's good enough for right now' vs. 'don't get into bad habits!'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-25T16:03:52.133", "Id": "385485", "Score": "1", "body": "I realize it's an old answer, but FYI you can now use the expression-bodied property syntax `public decimal TotalCost => CostOfFood * NumberOfPeople;`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T18:48:59.077", "Id": "28612", "ParentId": "28609", "Score": "18" } }, { "body": "<p>How about something more along these lines:</p>\n\n<pre><code>class DinnerParty\n{\n public DinnerParty(int people = 4, decimal price = 3.99)\n {\n this.NumberOfPeople = people;\n this.CostOfFood = price;\n }\n\n public int NumberOfPeople { get; private set;}\n public decimal CostOfFood { get; private set;}\n public decimal TotalCost { get { return CalculateFoodCost();} }\n\n public void UpdateNumberOfPeople(int people)\n {\n if (people &lt;= 0) {\n throw InvalidArgumentException(\"Can't have Zero or Fewer people.\");\n }\n this.NumberOfPeople = people;\n }\n\n public void UpdateCostOfFood(decimal price)\n {\n if (price &lt;= 0.0) {\n throw InvalidArgumentException(\"Can't have Zero or Negative Price.\");\n }\n this.CostOfFood = price; \n }\n\n private decimal CalculateFoodCost()\n {\n return this.CostOfFood * NumberOfPeople;\n }\n}\n</code></pre>\n\n<ul>\n<li>Default Values in Constructor (instead of down below \"somewhere\").</li>\n<li>Validation of updated values</li>\n<li>As other answer, only calculates price when needed.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T07:46:45.300", "Id": "44973", "Score": "3", "body": "this is a viable solution, yes, but it ignores the great flexibility of property accessors. The `Update*` methods could be refactored into the `set` accessors easily, and still expose the same functionality (but with a cleaner interface)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T01:35:20.223", "Id": "28626", "ParentId": "28609", "Score": "4" } } ]
{ "AcceptedAnswerId": "28612", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T18:01:07.087", "Id": "28609", "Score": "16", "Tags": [ "c#" ], "Title": "When one property is calculated from another" }
28609
<p>Yesterday, I introduced a bug into our codebase by calling <code>#titleize</code> on a string that could possibly come in as <code>nil</code>:</p> <pre><code>def route medication.route_name.titleize end </code></pre> <p>This threw an error on production and a coworker fixed this by adding <code>try</code>:</p> <pre><code>def route medication.route_name.try(:titleize) end </code></pre> <p>I'm not totally happy with this solution, after being really influenced by <a href="http://devblog.avdi.org/2011/06/28/do-or-do-not-there-is-no-try/" rel="noreferrer">Avdi's article on <code>#try</code></a>, and I've been trying to come up with something I like better. Here are two possibilities.</p> <p>Firstly, in Avdi's talk <a href="http://cloud.nickcox.me/QIgl" rel="noreferrer">"Confident Code"</a>, he talks about asking for the data type you need: if you need a string, ask for a string. So I thought about this:</p> <pre><code>def route medication.route_name.to_s.titleize end </code></pre> <p>This way, <code>nil</code> will be converted to empty string, and <code>#titleize</code> will be called, which will not error. The obvious issue with this is that you're calling <code>#to_s</code> on something which is only ever an instance of <code>String</code> or <code>NilClass</code>.</p> <p>The only other approach I could think of was this:</p> <pre><code>def route medication.route_name.present? medication.route_name.titleize : '' end </code></pre> <p>The issue here is the <code>if/else</code> parading around as prettier code through the use of a ternary operator, and the repetition of <code>medication.route_name</code>. This could be minified by delegating <code>route_name</code> to <code>medication</code>, or some other work around. But there's still the <code>if/else</code> conditional. And that's more code.</p> <p>The bigger question here is how to handle <code>nil</code> values. This method is a pretty typical example of how this comes up. How would you handle it?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-18T20:35:38.720", "Id": "247176", "Score": "0", "body": "Smiley for you :-D just for 'Trying to avoid #try'" } ]
[ { "body": "<blockquote>\n <p>I introduced a bug into our codebase by calling #titleize on a string that could possibly come in as nil</p>\n</blockquote>\n\n<p>When a problem is so pervasive, it's usually a sign that there is a conceptual problem with the language itself, some call it <a href=\"http://en.wikipedia.org/wiki/Void_safety\" rel=\"nofollow noreferrer\">void safety</a>, also dubbed \"the billion-dollar mistake\". Some languages, specially the functional ones, use an <a href=\"http://en.wikipedia.org/wiki/Option_type\" rel=\"nofollow noreferrer\">Option type</a>. Let's see the options in Ruby:</p>\n\n<ul>\n<li><p><code>medication.route_name.try(:titleize)</code>. This is probably the most idiomatic approach in Rails. You say you're not totally happy, yes, it's ugly that a method name ended up being a symbol. Note, however, that if you want an empty string as fallback, you should write <code>medication.route_name.try(:titleize) || \"\"</code>. </p></li>\n<li><p>Very similar to <code>try</code>, I prefer the proxy approach of <a href=\"https://github.com/raganwald/andand\" rel=\"nofollow noreferrer\">andand</a>/<a href=\"http://ick.rubyforge.org/\" rel=\"nofollow noreferrer\">maybe</a>: <code>medication.route_name.maybe.titleize || \"\"</code>. </p></li>\n<li><p><code>medication.route_name.to_s.titleize</code>. IMO, that's dubious. You are calling <code>to_s</code> to a <code>nil</code> object. Yes, it happens to return <code>\"\"</code>, but it could as well return <code>\"nil\"</code> (see for example Python: <code>str(None) #=&gt; 'None'</code>). Too implicit.</p></li>\n<li><p><code>medication.route_name.present? medication.route_name.titleize : ''</code>. You are protecting yourself against <code>nil</code> objects, not empty strings, so there is no need to use <code>present?</code>: <code>medication.route_name ? medication.route_name.titleize : ''</code>. As you say, this is simple but verbose. Also, imagine you have a chain of nullable values, it becomes a real mess. That's why <code>andand</code> and similar libraries were created.</p></li>\n</ul>\n\n<p>By the way, I've wrote about this subject at <a href=\"https://github.com/tokland/tokland/wiki/RubyIdioms#user-content-managing-nils-the-maybe-pattern\" rel=\"nofollow noreferrer\">RubyIdioms</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T19:01:35.113", "Id": "28613", "ParentId": "28610", "Score": "10" } }, { "body": "<p>Another solid option is to use the <a href=\"https://en.wikipedia.org/wiki/Safe_navigation_operator#Ruby\" rel=\"nofollow noreferrer\">Safe Navigation Operator</a> <strong>&amp;.</strong> like this:</p>\n\n<pre><code>def route\n medication.route_name&amp;.titleize\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T21:33:47.157", "Id": "424656", "Score": "0", "body": "Your linked reference says, that this is available with Ruby 2.3 which was released at the end of 2015, two years after the original question. I would invite you to add a note on this in your answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T21:18:44.080", "Id": "219830", "ParentId": "28610", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T18:06:44.123", "Id": "28610", "Score": "8", "Tags": [ "ruby", "ruby-on-rails", "error-handling", "null" ], "Title": "Handling nil: Trying to avoid #try" }
28610
<p>Straight to the point: Can you give me pointers on how to make this code more maintainable? In the future, I want to add more more things to this, but first it should be easy to maintain/read. Should making a library be considered?</p> <p>What it does:</p> <p>Takes input from the serial line and converts it to servo commands + all the bells and whistles added.</p> <pre><code>#include &lt;NewPing.h&gt; #include &lt;Servo.h&gt; #define errorLED 13 #define ThrottlePin 2 #define RollPin 3 #define PitchPin 5 #define YawPin 4 #define Aux1Pin 6 #define Trigger 18 #define Echo 19 #define HEADING_PIN 15 NewPing sonar(Trigger, Echo); Servo Throttle; Servo Roll; Servo Pitch; Servo Yaw; Servo Aux1; unsigned int throttle = DEFAULT_THROTTLE; unsigned int roll = DEFAULT_ROLL; unsigned int pitch = DEFAULT_PITCH; unsigned int yaw = DEFAULT_YAW; unsigned int aux1 = DEFAULT_AUX1; unsigned int temp = 0; unsigned int range = 7; unsigned long lastSerialData = 0; unsigned long lastThrottleUpdate = 0; unsigned long ledPreviousMillis = 0; const int DEFAULT_THROTTLE = 45; const int DEFAULT_ROLL = 70; const int DEFAULT_PITCH = 70; const int DEFAULT_YAW = 70; const int DEFAULT_AUX1 = 45; boolean isLedOn = false; //Pins 7-12 power //A0-A3 pin 13-16 boolean index = 7; boolean circleIndex = 14; void setup() { Throttle.attach(ThrottlePin); Roll.attach(RollPin); Pitch.attach(PitchPin); Yaw.attach(YawPin); Aux1.attach(Aux1Pin); Serial.begin(115200); for (byte x = 7; x &lt;= 12; x++) pinMode(x, OUTPUT); for (byte xy = 14; xy &lt;= 17; xy++) pinMode(xy, OUTPUT); setPowerPinsOn(false); setGroundPinsOn(true); pinMode(errorLED, OUTPUT); } int GetFromSerial() { // wait until we have some serial data while (Serial.available() == 0) { if (millis() - lastSerialData &gt; 1000) { digitalWrite(errorLED, HIGH); readSonar(); blinkingLed(); autoLand(); } } lastSerialData = millis(); digitalWrite(errorLED, LOW); return Serial.read(); } void loop() { switch (GetFromSerial()) { case 't': temp = 0; temp = GetFromSerial() + 45; if (temp &gt;= 45 &amp;&amp; temp &lt;= 141) throttle = temp; //45 to 141 Throttle.write(throttle); break; case 'r': temp = 0; temp = GetFromSerial() + 45; if (temp &gt;= 45 &amp;&amp; temp &lt;= 141) roll = map(temp, 45, 141, 69, 117); //45 to 141 if (roll &lt; (93 + range) &amp;&amp; roll &gt; (93 - range)) roll = 93; Roll.write(roll); break; case 'p': temp = 0; temp = GetFromSerial() + 45; if (temp &gt;= 45 &amp;&amp; temp &lt;= 141) pitch = map(temp, 45, 141, 69, 117); //45 to 141 if (pitch &lt; (93 + range) &amp;&amp; pitch &gt; (93 - range)) pitch = 93; Pitch.write(pitch); break; case 'y': temp = 0; temp = GetFromSerial() + 45; if (temp &gt;= 45 &amp;&amp; temp &lt;= 141) yaw = map(temp, 45, 141, 68, 117); //45 to 141 Yaw.write(yaw); break; case 'a': temp = 0; temp = GetFromSerial() + 45; if (temp &gt;= 45 &amp;&amp; temp &lt;= 141) aux1 = temp; //45 to 141 Aux1.write(aux1); break; } // end switch if (throttle &lt;= 45) //Connected but not flying circleLed(); else if (throttle &gt;= 45 &amp;&amp; aux1 &gt; 45) headingLed(); } void autoLand() { if (throttle &lt;= 60 &amp;&amp; aux1 &gt;= 50) { throttle = 45; aux1 = 45; } else if (throttle &gt;= 45) if (millis() - lastThrottleUpdate &gt; 400) { throttle = throttle * .95; aux1 = 45; lastThrottleUpdate = millis(); } writeAllValues(); } void writeAllValues() { Throttle.write(throttle); Roll.write(roll); Pitch.write(pitch); Yaw.write(yaw); Aux1.write(aux1); } void setPowerPinsOn(boolean on) { if (on) { for (byte x = 7; x &lt;= 12; x++) digitalWrite(x, HIGH); } else for (byte x = 7; x &lt;= 12; x++) digitalWrite(x, LOW); } void setGroundPinsOn(boolean on) { if (on) { for (byte x = 14; x &lt;= 17; x++) digitalWrite(x, LOW); } else for (byte x = 14; x &lt;= 17; x++) digitalWrite(x, HIGH); } void circleLed() { if (millis() - ledPreviousMillis &gt; 400) { if (circleIndex == 18) circleIndex = 14; ledPreviousMillis = millis(); setPowerPinsOn(true); setGroundPinsOn(false); digitalWrite(circleIndex, LOW); circleIndex++; } } void blinkingLed() { if (millis() - ledPreviousMillis &gt; 1000) { ledPreviousMillis = millis(); isLedOn = !isLedOn; setPowerPinsOn(isLedOn); setGroundPinsOn(true); } } void headingLed() { if (millis() - ledPreviousMillis &gt; 300 - (throttle - 45) * 2) { ledPreviousMillis = millis(); if (index == 13) index = 7; setPowerPinsOn(false); setGroundPinsOn(false); digitalWrite(HEADING_PIN, LOW); digitalWrite(index, HIGH); index++; } } void readSonar() { int uS = sonar.ping_median(); Serial.println(uS / US_ROUNDTRIP_CM); } </code></pre> <p>Summary: How can this code be more maintainable? Should making a library be considered?</p>
[]
[ { "body": "<p>I'll start by breaking the code down into different files. There are a many <code>#define</code> and <code>const int</code> here. If I am correct that will definitely grow with your project. Having all the constants in a different file is always a good idea if you are considering making it even moderately big. So to your question </p>\n\n<blockquote>\n <p>Should making a library be considered?</p>\n</blockquote>\n\n<p>I would say you should definitely make a library.</p>\n\n<p>After that I'll go and indent this code properly. I couldn't understand where the <code>loop()</code> function started and where it ended in the first go. If you want readability that is a something that you must seriously consider. All of your functions need proper indentation but for the <code>loop()</code> function it is a must.</p>\n\n<p>There is a lot of redundancy in your <code>loop()</code> function. </p>\n\n<ul>\n<li>The first 2 lines of each of your <code>case</code> is same. That is really bad programming. It made your code so big that you had to write comments to note down the end of your braces.</li>\n<li>You are writing same comments over and over again with no actual use. If you needed to change these you'll be getting a headache.</li>\n</ul>\n\n<p>I'll write your <code>loop()</code> function something like this</p>\n\n<pre><code>#define TEMP_RANGE(x,y) (temp &gt;= x &amp;&amp; temp &lt;= y)\n#define CHECK_RANGE(x, y, z) ((y + z) &gt; x &amp;&amp; x &gt; (y - z))\n\nvoid loop()\n{\n temp = 0;\n temp = GetFromSerial() + 45;\n switch (GetFromSerial()) \n {\n case 't':\n if (TEMP_RANGE(45,141))\n throttle = temp;\n Throttle.write(throttle);\n break;\n case 'r':\n if (TEMP_RANGE(45,141))\n roll = map(temp, 45, 141, 69, 117);\n if (CHECK_RANGE(roll, 93, range))\n roll = 93;\n Roll.write(roll);\n break;\n case 'p':\n if (TEMP_RANGE(45,141))\n pitch = map(temp, 45, 141, 69, 117);\n if (CHECK_RANGE(pitch, 93, range))\n pitch = 93;\n Pitch.write(pitch);\n break;\n case 'y':\n if (TEMP_RANGE(45,141))\n yaw = map(temp, 45, 141, 68, 117);\n Yaw.write(yaw);\n break;\n case 'a':\n if (TEMP_RANGE(45,141))\n aux1 = temp;\n Aux1.write(aux1);\n break;\n }\n\n if (throttle &lt;= 45) //Connected but not flying\n circleLed();\n else if (aux1 &gt; 45)\n headingLed();\n}\n</code></pre>\n\n<p>Note these</p>\n\n<ul>\n<li>I placed the range checks which were being done more than once into their own <code>define</code>. This made them much easier to read and change. You can make better names based on the context. I didn't use functions but you can use them for even better abstraction and readability.</li>\n<li>Due to proper indentation people will be able to read this much faster. That is very important if you want maintainability.</li>\n<li>Took out redundancy from your code. You were checking whether a number was <code>&lt;= 45</code> something and in the <code>else if</code> you were checking whether it was <code>&gt;=</code>. Obviously it is <code>&gt; 45</code> otherwise the fist condition would have executed.</li>\n<li>It can be improve more if you use functions or a bit more little complex macros. Functions might be preferable.</li>\n</ul>\n\n<p>I think I covered the biggest issues. </p>\n\n<ul>\n<li>Use a proper indentation in your whole code. That is essential. </li>\n<li>Maybe add function prototypes at the top to make it easier to find what is where. </li>\n<li>If you are thinking of making it big try to break it down into logical parts first.</li>\n<li>Use braces consistently. Sometimes you are using braces for containing single statements but sometimes you are not. That is a source of many bugs.</li>\n</ul>\n\n<p>Hope this helped.\nIf you want more feedback I suggest you to fix these problems and ask another question with the updated code for more feedback.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T12:11:35.350", "Id": "44984", "Score": "0", "body": "Just what I was looking for :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T21:57:03.753", "Id": "28618", "ParentId": "28611", "Score": "3" } } ]
{ "AcceptedAnswerId": "28618", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T18:15:02.473", "Id": "28611", "Score": "3", "Tags": [ "c", "arduino", "serial-port", "device-driver" ], "Title": "Servo commands based on serial port input" }
28611
<p>I'm trying to re-learn some JS fundamentals and wondered if anyone knowledgabe could tell me if I'm doing something very wrong in my approach to this simple word counting class. </p> <p>I want to create a class that takes arbitrary text and returns information about its wordcount, frequency of words, etc. One of the methods I have so far returns a hash where each key coresponding to a word has an element called count which is its frequency in the text.</p> <p>One usage is to produce an output that will be printed to a file with WORD COUNT on each line.</p> <pre><code>function WordCounter(){ this.text = new String() } WordCounter.prototype.addWords = function(words){ this.text += words } WordCounter.prototype.count = function(){ return this.text.split(" ").length } WordCounter.prototype.getFrequenciesAsHash = function(){ var words = this.text.split(" ") var frequencies = {} while(words.length &gt; 0){ var word = words.pop() if(typeof frequencies[word] == "undefined"){ frequencies[word] = {} frequencies[word].count = 0 } frequencies[word].count++ } return frequencies } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T21:11:16.757", "Id": "44939", "Score": "0", "body": "I am not sure what you are trying to do really..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T21:14:52.360", "Id": "44940", "Score": "0", "body": "Thanks for looking. I guess I could have described better. I want to create a class that takes arbitrary text and returns information about its wordcount, frequency of words, etc. One of the methods I have so far returns a hash where each key coresponding to a word has an element called count which is its frequency in the text." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T21:16:36.720", "Id": "44941", "Score": "0", "body": "@maninjeans: Go ahead and edit that into the question for everyone else to see." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T21:18:58.870", "Id": "44942", "Score": "0", "body": "@jamal man you guys are fast, edited in as you typed :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T21:20:50.103", "Id": "44944", "Score": "0", "body": "@maninjeans: I have a lot of free time. :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T21:30:15.623", "Id": "44945", "Score": "0", "body": "`WordCounter.prototype.getFrequenciesAsHash` ... `return words.split(\" \").reduce(function(a,b){ a[b] ? a[b]++ : a[b] = 1; return a;},{});`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T19:10:23.530", "Id": "45009", "Score": "0", "body": "``\" \".split(\" \")`` -> ``['', '', '', '', '', '', '', '']``. Probably not what you want." } ]
[ { "body": "<p>Conceptually, I feel like you are doing this backwards. You should be storing an array of strings instead of repeatedly splitting a string into an array.</p>\n\n<p>Here's my take on it:</p>\n\n<pre><code>function WordCounter(){\n this.words = []; // You should just use an array. It makes more sense here.\n}\n\nWordCounter.prototype.addWords = function(){\n // this allows you to pass in words as multiple arguments, or as an array of words\n // i.e.: \n // myWordCounter.addWords([\"one\",\"two\",\"three\"]); \n // or \n // myWordCounter.addWords(\"one\", \"two\", \"three\");\n this.words = this.words.concat([].slice.call(arguments));\n}\nWordCounter.prototype.count = function(){\n return this.words.length;\n}\nWordCounter.prototype.toString = function(){\n //this replaces the text property\n return this.words.join(\" \");\n}\nWordCounter.prototype.getFrequenciesAsHash = function(){\n // reduce is much more elegant here. \n // if you have to support older browsers, just use a shim to fill in array method support\n return this.words.reduce(function(hash, word){\n // no need to do a typeof.\n if(hash[word] === undefined) \n hash[word] = 0; // no reason to create an object\n\n hash[word]++;\n\n return hash;\n }, {});\n}\n</code></pre>\n\n<p>If you want to be able to add words from a multi-word string, I would suggest a separate method for clarity:</p>\n\n<pre><code>WordCounter.prototype.extractWords = function(string){\n this.addWords(string.match(/\\w+/g));\n}\n</code></pre>\n\n<p>The naming could be better. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T07:13:46.443", "Id": "44967", "Score": "0", "body": "Thanks, I was thinking the same thing yesterday, that I sould maintain an array of strings instead of creating one each time the getFrequencies is called, but I was unsure how to best go about it. The reduce method also seems to be the way to go. I'll play around with this tonight." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T21:47:51.460", "Id": "28617", "ParentId": "28615", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T20:52:20.477", "Id": "28615", "Score": "0", "Tags": [ "javascript" ], "Title": "Critique wanted on JS" }
28615
<p>I like to keep my code organized, usually in several files. It is good for CSS. For instance:</p> <p>I have three files:</p> <ul> <li>First - <code>layout.html</code>, this is the main template.</li> <li>Second - <code>grid.css</code> is style sheet where I decribe position of all elements.</li> <li>Third - <code>style.css</code> is where I describe appearence of elements.</li> </ul> <p>Listings: </p> <pre><code>&lt;!DOCTYPE html&gt; &lt;!--layout.html--&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;The best title ever&lt;/title&gt; &lt;link rel="stylesheet" href="grid.css" type="text/css"/&gt; &lt;/head&gt; &lt;body&gt; &lt;!--The top part of site --&gt; &lt;div id="header"&gt; &lt;h1&gt;Header&lt;/h1&gt; &lt;/div&gt; &lt;!--The main part of site, where al information is--&gt; &lt;div id="main"&gt; &lt;!--Container with floating tabs. --&gt; &lt;ul id="tabs"&gt; &lt;!--Floating tabs--&gt; &lt;li id="tab1"&gt;Tab 1&lt;/li&gt; &lt;li id="tab2"&gt;Tab 2&lt;/li&gt; &lt;li id="tab3"&gt;Tab 3&lt;/li&gt; &lt;/ul&gt; &lt;!--Container where we see content of ACTIVE tab--&gt; &lt;div id="content"&gt; Content &lt;/div&gt; &lt;/div&gt; &lt;!--The bottom part of site --&gt; &lt;div id="footer"&gt; Footer. &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>grid.css</p> <pre><code>/* Rules for three base blocks. */ #header,#main,#footer{ width:990px; margin: 0 auto; padding:0; } /* Rules for tabs. */ #tabs{ diplay:block; overflow:auto; padding:0; margin:0; } #tabs li{ display:block; float:left; width:330px; height:50px; border: 1px solid silver;/*Uncomment it for debugging */ box-sizing:border-box; -moz-box-sizing:border-box; padding-top:10px; text-align:center; } /* Rules for content block. */ #content{ width:990px; height:700px; box-sizing:border-box; -moz-box-sizing:border-box; border:1px solid silver;/*Uncomment it for debugging */ } </code></pre> <p>style.css</p> <pre><code>body{ background-color:silver; /*And all things like that, colors,fonts,etc..*/ } </code></pre> <p>What do you think of this code organization? </p> <p>How do you organize your style sheets?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T19:48:44.907", "Id": "45010", "Score": "0", "body": "This question seems a little off topic for CR: [your answer is provided along with the question, and you expect more answers: “I use ______ for ______, what do you use?”](http://codereview.stackexchange.com/help/dont-ask). Proper code organization *always* makes sense, but how I organize code might not make sense for you." } ]
[ { "body": "<p>Here is my directory structure:</p>\n\n<pre><code>./\n app/\n theme/\n</code></pre>\n\n<p>Here is my CSS build script:</p>\n\n<pre><code>#!/bin/bash\n\n# Directory to write the minified CSS files.\nOUTPUT_DIR=../css\n\nmkdir -p $OUTPUT_DIR/app\n\nlessc -x ui.less &gt; $OUTPUT_DIR/ui.css\n\n# Create minified CSS files for the applications.\nfor i in app/*; do\n lessc -x $i &gt; $OUTPUT_DIR/app/$(basename $i .less).css\ndone\n</code></pre>\n\n<p>Here are the main files I use (relatively located in <code>./</code>):</p>\n\n<pre><code>colour.less\nconstant.less\nfieldset.less\nfont.less\nlayout.less\nsprite.less\nmaster.less\n</code></pre>\n\n<p>Each <code>.less</code> file under the <code>app/</code> directory contains overrides for any of the above styles. The <code>theme/</code> directory contains constants for colour themes. For example:</p>\n\n<pre><code>@header-nav-search : #1abc9c;\n@header-nav-book : #e67e22;\n@header-nav-account: #e74c3c;\n</code></pre>\n\n<p>The <code>master.less</code> file ropes them all together:</p>\n\n<pre><code>@import \"constant.less\";\n@import \"fieldset.less\";\n@import \"layout.less\";\n@import \"font.less\";\n@import \"colour.less\";\n</code></pre>\n\n<p>Each app-specific file starts with a reference to the theme:</p>\n\n<pre><code>@import \"../theme/peaceful.less\";\n</code></pre>\n\n<p>I welcome improvements. The short answer is: use <a href=\"http://lesscss.org/\" rel=\"nofollow\">LESSCSS</a> or an equivalent language that compiles into CSS. Having variables and functions to use for generating CSS is extremely useful.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T22:47:08.617", "Id": "28619", "ParentId": "28616", "Score": "5" } }, { "body": "<p>Yes, using multiple CSS files is a common practice. And since they're CSS files, the files don't take long for the browser to render.</p>\n\n<p>You can use the <code>@import</code> CSS rule to 'sew' them all together, if you wish, but I tend to just leave them.</p>\n\n<p>Often, I use four CSS files together;</p>\n\n<ul>\n<li><code>reset.css</code> - reset all user agents</li>\n<li><code>default.css</code> - modern browsers</li>\n<li><code>ui.css</code> - I personally like to keep the user interface aesthetics separate</li>\n<li><code>mobile.css</code> - an easy way to alter the page for mobile devices, without having to maintain two versions of your website. This is inserted in via CSS <code>@media</code> queries.</li>\n</ul>\n\n<p>And if older versions of Internet Explorer need separate CSS, they can be given using IE conditional comments. For example;</p>\n\n<p><strong>If you want to target stale browsers like IE8 and below, you can use this:</strong></p>\n\n<pre><code>&lt;!--[if lte IE 8]&gt;\n &lt;link rel=\"stylesheet\" href=\"ie8.css\"&gt;\n&lt;![endif]--&gt;\n</code></pre>\n\n<p><strong>And for more modern browsers that include <em>decent</em> HTML5 and CSS3 support, you can target IE9 and above, plus browsers that are not IE, with this:</strong></p>\n\n<pre><code>&lt;!--[if gte IE 9|!IE]&gt;&lt;!--&gt;\n &lt;link rel=\"stylesheet\" href=\"default.css\"&gt;\n&lt;!--&lt;![endif]--&gt;\n</code></pre>\n\n<p>That's my usual setup.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T07:23:23.787", "Id": "35581", "ParentId": "28616", "Score": "2" } } ]
{ "AcceptedAnswerId": "28619", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T21:21:13.070", "Id": "28616", "Score": "6", "Tags": [ "html", "css", "html5" ], "Title": "CSS code organizing" }
28616
<p>I am trying to return a value (<code>a.tnAddress</code>) from a custom class based on a lookup (<code>foreach</code> loop). Depending on the type of transaction, I will need to do the <code>foreach</code> loop based on different properties (<code>sExecID</code>, <code>iMsgSeqNum, or</code>sClOrderID<code>). I prefer to not have 3 different</code>foreach` loops just but I am not sure how else to re-write this.</p> <p>Keep in mind that the code is working fine; I just want to simplify it.</p> <pre><code>private TreeNode GetNodeAddress(cls_Transactions trPassedInTransaction) { switch (trPassedInTransaction.sMessageType) { case "Q": case "8b": foreach (cls_Transactions a in cls_GlobalVariables.transList) { if (trPassedInTransaction.sExecID == a.sExecID) { return a.tnAddress; } } break; case "3": foreach (cls_Transactions a in cls_GlobalVariables.transList) { if (trPassedInTransaction.iMsgSeqNum == a.iMsgSeqNum) { return a.tnAddress; } } break; default: foreach (cls_Transactions a in cls_GlobalVariables.transList) { if (trPassedInTransaction.sClOrderID == a.sClOrderID) { return a.tnAddress; } } break; } return null; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T00:39:58.333", "Id": "44950", "Score": "0", "body": "Do you think the performance is poor? Your code seems good." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T00:49:53.967", "Id": "44951", "Score": "0", "body": "I just didn't want to replicate the foreach loop 3x. Plus if I wanted to add messages types in the future, i thought there would be an easier way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T00:51:04.647", "Id": "44952", "Score": "0", "body": "Switch statements are good here. It could be simplified using LINQ but won't be of much help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T13:45:56.123", "Id": "44991", "Score": "0", "body": "I would avoid switch statements in favour of polymorphism where possible, and in this case it looks easily possible..." } ]
[ { "body": "<p>This will add the use of <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/bb397926.aspx\">LINQ</a> to clean up the code the way you want:</p>\n\n<pre><code>private TreeNode GetNodeAddress(cls_Transactions trPassedInTransaction)\n{\n //a predicate to pass to the FirstOrDefault method\n Func&lt;cls_Transactions,Boolean&gt; filter = null;\n switch (trPassedInTransaction.sMessageType)\n {\n\n case \"Q\":\n case \"8b\":\n filter = x =&gt; trPassedInTransaction.sExecID == x.sExecID;\n break;\n case \"3\":\n filter = x =&gt; trPassedInTransaction.iMsgSeqNum == x.iMsgSeqNum;\n break;\n default:\n filter = x =&gt; trPassedInTransaction.sClOrderID == x.sClOrderID; \n break;\n }\n\n cls_Transactions result = cls_GlobalVariables.transList.FirstOrDefault(filter);\n return result != null ? result.tnAddress : null;\n}\n</code></pre>\n\n<p>As an explanation, the switch statement has just been converted to use a predicate, which is a function type where it passes one parameter (in this case a cls_Transactions) and returns true/false.</p>\n\n<p>The <code>FirstOrDefault</code> method is shorthand for the foreach loop and return, foreach-ing through the elements and using the predicate to determine if it meets the required condition, if none meet the required condition it will return a default value (in the case null).</p>\n\n<p>You can use the <code>First</code> method also, which will throw an exception if nothing is found :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T01:00:10.943", "Id": "44953", "Score": "0", "body": "Ok....I think I will have to study my LINQ before I implement this, but Thank You." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T05:48:41.240", "Id": "44961", "Score": "0", "body": "Func<cls_Transactions,Boolean> filter = null; --> in case of Q it will throw an ArgumentNullException so change null to: () => true" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T08:04:21.027", "Id": "44976", "Score": "0", "body": "In case of 'Q' (as there is no 'break;') it will fall through to '8b' and use it's filter. There should be no condition here that filter is null, as there is a default on the switch statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T13:17:24.893", "Id": "44988", "Score": "0", "body": "@m.t.bennett: I think you should change `Func<cls_Transactions,Boolean> filter = null;` to `Func<cls_Transactions,Boolean> filter;` . This makes it more obvious that `filter` can never be null. The C# compiler does not allow possibly unassigned variables to be used, but in this case `filter` is always assigned. When I see you assign `filter` to `null`, my first inclination is to wonder if there is a code path where that value is used (because otherwise, why assign it at all?)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T23:00:45.177", "Id": "45015", "Score": "0", "body": "@Brian I look at this the other way - if I know the original variable is null (Filter) then I immediately know it needs to be handled at a later date. I think in this situation specifically we know the switch statement is the control path that assigns the variable, and any new code must adhere to this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T23:17:53.920", "Id": "45017", "Score": "1", "body": "@m.t.bennett : If you don't assign the variable at all, the compiler will **enforce** that it needs to be handled at a later date. Any new code which introduces new switch elements will fail to compile unless those elements assign filter (since filter must be definitively assigned before it can be used)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T00:52:10.570", "Id": "28623", "ParentId": "28622", "Score": "10" } }, { "body": "<p>I like using a dictionary because to me it looks like tighter cleaner code and you can easily add to the dictionary or if you want later pull the logic from another source and put into the dictionary.</p>\n\n<pre><code> var dictionary = new Dictionary&lt;string, Predicate&lt;cls_Transactions&gt;&gt;();\n dictionary.Add(\"Q\", x =&gt; x.sExecID == trPassedInTransaction.sExecID);\n dictionary.Add(\"8b\", x =&gt; x.sExecID == trPassedInTransaction.sExecID);\n dictionary.Add(\"3\", x =&gt; x.iMsgSeqNum == trPassedInTransaction.iMsgSeqNum);\n dictionary.Add(\"default\", x =&gt; x.sClOrderID == trPassedInTransaction.sClOrderID);\n\n var switchValue = dictionary[trPassedInTransaction.sMessageType] != null\n ? trPassedInTransaction.sMessageType\n : \"default\";\n var result = cls_GlobalVariables.transList.FirstOrDefault(t =&gt; dictionary[switchValue](t));\n return result != null ? result.tnAddress : null;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T00:38:15.083", "Id": "28762", "ParentId": "28622", "Score": "2" } } ]
{ "AcceptedAnswerId": "28623", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T00:38:11.047", "Id": "28622", "Score": "3", "Tags": [ "c#", "lookup" ], "Title": "Returning a value based on a lookup" }
28622
<p>I am trying to find the best way to structure this. I want to avoid <code>if</code>-<code>else</code> statements and reduce the number of code lines.</p> <pre><code>def get_parent(relationships,GU) parent = [] if relationships.class == Array relationships.each do |y| if y[:relationship_roles][:relationship_role][:to_role][:name] == type parent &lt;&lt; y[:party][:party_id][:id] end end else if relationships[:relationship_roles][:relationship_role][:to_role][:name] == type parent &lt;&lt; relationships[:party][:party_id][:id] end end return parent end </code></pre> <p>Input:</p> <pre><code>:relationship=&gt;{:name=&gt;nil, :party=&gt;{:party_id=&gt;{:id=&gt;"12344", :id_type=&gt;"abc"}, :name=&gt;"XYZ", :@active=&gt;"true", :@type=&gt;"Organization"}, :relationship_roles=&gt;{:relationship_role=&gt;{:to_role=&gt;{:name=&gt;"GU"}}}} </code></pre> <p>The input could be only one relationship or multiple ones, which is why I have the <code>if</code>/<code>else</code> loop.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T02:49:40.797", "Id": "44958", "Score": "2", "body": "You say you have a loop, but you have no loop. You must mean something else. If you had a loop, you would have `loop..do..end`. What are you trying to get rid of? Nested if statements?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T13:06:15.590", "Id": "44987", "Score": "1", "body": "No doubt the question is poorly worded, but closing it for this reason... The code is clearly messy, it's not that important how the OP tries to explain it." } ]
[ { "body": "<p><em>disclaimer: my ruby knowledge is practically nonexistent so the code below might be completely rubbish ruby-wise.</em></p>\n\n<p>I see two code smells in this code: <a href=\"http://c2.com/cgi/wiki?DuplicatedCode\" rel=\"nofollow\">duplicate code</a> and <a href=\"http://c2.com/cgi/wiki?SwitchStatementsSmell\" rel=\"nofollow\">switch on type</a>.</p>\n\n<p>To eliminate the duplicate code we can apply the extract method refactoring:</p>\n\n<pre><code>def get_parent_for_relationship(relationship, parent)\n if relationship[:relationship_roles][:relationship_role][:to_role][:name] == type\n parent &lt;&lt; relationship[:party][:party_id][:id]\n end\nend\n\ndef get_parent(relationships)\n parent = []\n if relationships.class == Array\n relationships.each do |y|\n get_parent_for_relationship(y, parent)\n end\n else\n get_parent_for_relationship(relationship, parent) end\n return parent\nend\n</code></pre>\n\n<p>To make the switch on type even more visible, we can extract another method:</p>\n\n<pre><code>def get_parent_for_relationship(relationship, parent)\n if relationship[:relationship_roles][:relationship_role][:to_role][:name] == type\n parent &lt;&lt; relationship[:party][:party_id][:id]\n end\nend\n\ndef get_parent_for_array_of_relationships(relationships, parent)\n relationships.each do |y|\n get_parent_for_relationship(y, parent)\n end\nend\n\ndef get_parent(relationships)\n parent = []\n if relationships.class == Array\n get_parent_for_array_of_relationships(relationships, parent)\n else\n get_parent_for_relationship(relationship, parent) end\n return parent\nend\n</code></pre>\n\n<p>Where you go from here is largely dependent on the calling code. An extensive discussion on switch on type, including strategies on dealing with it if it is really a problem can be found <a href=\"http://c2.com/cgi/wiki?SwitchStatementsSmell\" rel=\"nofollow\">here</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T07:30:43.093", "Id": "28677", "ParentId": "28627", "Score": "0" } }, { "body": "<p>Some notes:</p>\n\n<ul>\n<li>It would be debatable whether it's good practice to have arguments which may contain either single elements or collections. </li>\n<li>If you convert whatever you get to an array (using <code>Array</code>), there is no need to repeat code.</li>\n<li>Don't use <code>each</code> + <code>&lt;&lt;</code> (imperative), use <code>map</code> + <code>compact</code> (functional).</li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>def get_parent(relationship_item_or_collection)\n Array(relationship_item_or_collection).map do |relationship|\n if relationship[:relationship_roles][:relationship_role][:to_role][:name] == type\n relationship[:party][:party_id][:id]\n end\n end.compact\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T16:02:06.287", "Id": "45072", "Score": "0", "body": "I would say using `map`/`compact` here is questionable, `inject` could be a better alternative if it was not so slow (in R1.8 at least, comparing to `each`). Totally agree with `Array()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T16:07:24.563", "Id": "45073", "Score": "0", "body": "Victor, I agree that map+compact is space-inefficient and slower. However, changing the right abstraction for the job with an `inject` or `each` (which are lower in the abstraction layer, speciall `each`) would be a pity, wouldn't it? For me the real solution would be to have an efficient abstraction (a pity it's not in the core). So in my projects I always have `compact_map` available, either my own implementation or from Facets: https://github.com/rubyworks/facets/blob/master/lib/core/facets/enumerable/compact_map.rb" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T11:57:55.993", "Id": "28692", "ParentId": "28627", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T01:50:23.183", "Id": "28627", "Score": "1", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Getting parent relationship" }
28627
<p>In this code, I'm getting the json from backend. Once I find the json availability, I loop and make 5 columns. Once the columns are made, I append after the legend of my form.</p> <p>Can this be improved any further?</p> <pre><code>if(data.hasOwnProperty("allLocales")){ var col0 = $("&lt;fieldset /&gt;"), col1 = $("&lt;fieldset /&gt;"), col2 = $("&lt;fieldset /&gt;"), col3 = $("&lt;fieldset /&gt;"), col4 = $("&lt;fieldset /&gt;"); $.map(data["allLocales"], function(value, i){ var name = value.name; if(i % 5 === 0 ){ col0.append($("&lt;label /&gt;").text(name).prepend($("&lt;input type='checkbox' /&gt;").attr("value", name))); }else if(i % 5 === 1){ col1.append($("&lt;label /&gt;").text(name).prepend($("&lt;input type='checkbox' /&gt;").attr("value", name))); }else if(i % 5 === 2){ col2.append($("&lt;label /&gt;").text(name).prepend($("&lt;input type='checkbox' /&gt;").attr("value", name))); }else if(i % 5 === 3){ col3.append($("&lt;label /&gt;").text(name).prepend($("&lt;input type='checkbox' /&gt;").attr("value", name))); }else if(i % 5 === 4){ col4.append($("&lt;label /&gt;").text(name).prepend($("&lt;input type='checkbox' /&gt;").attr("value", name))); } }) $("form legend").after(col0,col1,col2,col3,col4).end().find("span.submit").css({display:"block"}); } </code></pre>
[]
[ { "body": "<p>First you should not create on function for each column.\nIn place of :</p>\n\n<pre><code>var col0 = $(\"&lt;fieldset /&gt;\"), \n col1 = $(\"&lt;fieldset /&gt;\"),\n col2 = $(\"&lt;fieldset /&gt;\"),\n col3 = $(\"&lt;fieldset /&gt;\"),\n col4 = $(\"&lt;fieldset /&gt;\");\n</code></pre>\n\n<p>You should use :</p>\n\n<pre><code>var col_type = \"&lt;fieldset /&gt;\";\n</code></pre>\n\n<p><strike></p>\n\n<pre><code>var cols = {}\n</code></pre>\n\n<p>And then add it to your JSON :</p>\n\n<pre><code>cols[\"col\"+ i % 5] = $(col_type)...\n</code></pre>\n\n<p>So, you'll get a JSON object of this form :</p>\n\n<pre><code>{\n \"col0\": &lt;YOUR_jQuery element&gt;,\n \"col1\": &lt;YOUR_jQuery element&gt;,\n \"col2\": &lt;YOUR_jQuery element&gt;,\n \"col3\": &lt;YOUR_jQuery element&gt;,\n \"col4\": &lt;YOUR_jQuery element&gt;\n}\n</code></pre>\n\n<p></strike></p>\n\n<p>JSON are not support in jQuery for after() iteration. You must use an Array.</p>\n\n<pre><code>cols.push($(col_type)...)\n</code></pre>\n\n<p>And you won't need one variable for each new column.</p>\n\n<p><strike>\nCould you give a sample of your data.allLocales ?\nAnd a sample of your HTML code ?\n</strike></p>\n\n<p>And no <strong>if(data.hasOwnProperty(\"allLocales\"))</strong> is needed</p>\n\n<p>Described :</p>\n\n<pre><code>for( column in data[\"allLocales\"] ) {\n var name = data[\"allLocales\"][column].name\n\n $(\"form legend\").after(\n $(\"&lt;fieldset /&gt;\")\n .append(\n $(\"&lt;label /&gt;\")\n .text(name)\n .prepend(\n $(\"&lt;input type='checkbox' /&gt;\")\n .attr(\"value\", name)\n )\n )\n )\n .end()\n .find(\"span.submit\")\n .css({display: \"block\"});\n}\n</code></pre>\n\n<p>Shorter :</p>\n\n<pre><code>for( column in data[\"allLocales\"] ) {\n var name = data[\"allLocales\"][column].name\n $(\"form legend\").after($(\"&lt;fieldset /&gt;\").append(\n $(\"&lt;label /&gt;\").text(name).prepend($(\"&lt;input type='checkbox' /&gt;\").attr(\"value\", name)))).end().find(\"span.submit\").css({display: \"block\"}\n )\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T12:28:34.557", "Id": "28642", "ParentId": "28640", "Score": "2" } }, { "body": "<p>Rather use an array. This allows you to write the following:</p>\n\n<pre><code>if (data.hasOwnProperty(\"allLocales\")) {\n var col = [];\n for(var i = 0; i &lt; 5; i++) {\n col[i] = $(\"&lt;fieldset /&gt;\");\n }\n $.map(data[\"allLocales\"], function (value, i) {\n var name = value.name;\n $col[i % 5].append($(\"&lt;label /&gt;\").text(name).prepend($(\"&lt;input type='checkbox' /&gt;\").attr(\"value\", name)));\n })\n $(\"form legend\").after(col).end().find(\"span.submit\").css({display: \"block\"});\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T12:34:23.913", "Id": "28643", "ParentId": "28640", "Score": "2" } } ]
{ "AcceptedAnswerId": "28643", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T11:28:44.283", "Id": "28640", "Score": "1", "Tags": [ "javascript", "jquery", "json" ], "Title": "Object iteration and appending to form" }
28640
<p>I have the next bilinear resizing algorithm, and even though I use fixed point is still quite slow for my requirements. In the past I tried to cache some values in tables but the improvement was of a few not noticeable milliseconds.</p> <p>Is any other way I can improve the speed? As this is intended for ARM processors, I know I could write it with NEON instructions, but unfortunately I don't have the knowledge for such task.</p> <pre><code>void resize_bilinear(const unsigned int *input, unsigned int *output, const unsigned int sourceWidth, const unsigned int sourceHeight, const unsigned int targetWidth, const unsigned int targetHeight) { unsigned int widthCoefficient, heightCoefficient, x, y; unsigned int pixel1, pixel2, pixel3, pixel4; unsigned int hc1, hc2, wc1, wc2, offsetX, offsetY; unsigned int r, g, b, a; const unsigned int wStepFixed16b = ((sourceWidth - 1) &lt;&lt; 16) / ((unsigned int)(targetWidth - 1)); const unsigned int hStepFixed16b = ((sourceHeight - 1) &lt;&lt; 16) / ((unsigned int)(targetHeight - 1)); heightCoefficient = 0; int offsetPixelY; int offsetPixelY1; int offsetX1; for (y = 0; y &lt; targetHeight; y++) { offsetY = (heightCoefficient &gt;&gt; 16); hc2 = (heightCoefficient &gt;&gt; 9) &amp; (unsigned char)127; hc1 = 128 - hc2; widthCoefficient = 0; offsetPixelY = offsetY * sourceWidth; offsetPixelY1 = (offsetY + 1) * sourceWidth; for (x = 0; x &lt; targetWidth; x++) { offsetX = (widthCoefficient &gt;&gt; 16); wc2 = (widthCoefficient &gt;&gt; 9) &amp; (unsigned char)127; wc1 = 128 - wc2; offsetX1 = offsetX + 1; pixel1 = *(input + (offsetPixelY + offsetX)); pixel2 = *(input + (offsetPixelY1 + offsetX)); pixel3 = *(input + (offsetPixelY + offsetX1)); pixel4 = *(input + (offsetPixelY1 + offsetX1)); a = ((((pixel1 &gt;&gt; 24) &amp; 0xff) * hc1 + ((pixel2 &gt;&gt; 24) &amp; 0xff) * hc2) * wc1 + (((pixel3 &gt;&gt; 24) &amp; 0xff) * hc1 + ((pixel4 &gt;&gt; 24) &amp; 0xff) * hc2) * wc2) &gt;&gt; 14; r = ((((pixel1 &gt;&gt; 16) &amp; 0xff) * hc1 + ((pixel2 &gt;&gt; 16) &amp; 0xff) * hc2) * wc1 + (((pixel3 &gt;&gt; 16) &amp; 0xff) * hc1 + ((pixel4 &gt;&gt; 16) &amp; 0xff) * hc2) * wc2) &gt;&gt; 14; g = ((((pixel1 &gt;&gt; 8) &amp; 0xff) * hc1 + ((pixel2 &gt;&gt; 8) &amp; 0xff) * hc2) * wc1 + (((pixel3 &gt;&gt; 8) &amp; 0xff) * hc1 + ((pixel4 &gt;&gt; 8) &amp; 0xff) * hc2) * wc2) &gt;&gt; 14; b = ((((pixel1) &amp; 0xff) * hc1 + ((pixel2) &amp; 0xff) * hc2) * wc1 + (((pixel3) &amp; 0xff) * hc1 + ((pixel4) &amp; 0xff) * hc2) * wc2) &gt;&gt; 14; *output++ = (a &lt;&lt; 24) | (r &lt;&lt; 16) | (g &lt;&lt; 8) | b; widthCoefficient += wStepFixed16b; } heightCoefficient += hStepFixed16b; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-10T19:53:26.093", "Id": "46819", "Score": "0", "body": "Why are you declaring all the variables which are only used in the loop at the beginning of the function? You know that this doesn't change anything reagding performance? Parallelizing the image processing with NEON instructions sounds like a very good thing to do in your case, maybe it would be worth the time to learn how to use them." } ]
[ { "body": "<p>You could be saving important variables that are being used frequently in the register like the following:</p>\n\n<pre><code>register const unsigned int targetWidth\n</code></pre>\n\n<p>Make sure memory accesses are cache-optimized, i.e. clumped together.</p>\n\n<p>Investigate if signed/unsigned for integer operations have performance costs on your platform.</p>\n\n<p>Investigate if look-up tables rather than computations gain you anything (but these can blow the caches, so be careful).</p>\n\n<p>Even though you've already avoided floats I'm going to post this anyway:\nIf you can avoid double and float variables, use int. On most architectures, int would be test faster type for computations because of the memory model. You can still achieve decent precision by simply shifting your units like you've been doing (ie use 1026 as int instead of 1.026 as double or float).</p>\n\n<p>And, of course, do lots of profiling and measurements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-13T01:22:19.413", "Id": "37273", "ParentId": "28645", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T13:24:55.490", "Id": "28645", "Score": "6", "Tags": [ "optimization", "performance", "c", "image" ], "Title": "Bilinear resizing algorithm" }
28645
<p>As explained in my <a href="http://cfmlblog.adamcameron.me/2013/07/replacewithcallback-udf-for-cflib-and.html">blog article</a>…</p> <blockquote> <p>I was looking up the docs for <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace">Javascript's String replace()</a> function the other day (because, no, I could not remember the vagaries of its syntax!). And whilst being relieved I had remembered it correctly for my immediate requirements, I also noticed it can take a callback instead of a string for its replacement argument. How cool is that?</p> <p>I figured this could be handy for CFML's <code>reReplace()</code> function too, so decided to look at how it would work before raising the enhancement request, and in the process wrote a reasonable UDF which does the business, by way of proof of concept.</p> <p>I'll submit <a href="http://www.cflib.org/udf/replaceWithCallback"><code>replaceWithCallback()</code> to CFLib</a>, but I am wary of self-approving stuff, so I'll get you lot to cast yer eyes over it too, by way of community driven code review.</p> </blockquote> <pre><code>/** @hint Analogous to reReplace()/reReplaceNoCase(), except the replacement is the result of a callback, not a hard-coded string @string The string to process @regex The regular expression to match @callback A UDF which takes arguments match (substring matched), found (a struct of keys pos,len,substring, which is subexpression breakdown of the match), offset (where in the string the match was found), string (the string the match was found within) @scope Number of replacements to make: either ONE or ALL @caseSensitive Whether the regex is handled case-sensitively */ string function replaceWithCallback(required string string, required string regex, required any callback, string scope="ONE", boolean caseSensitive=true){ if (!isCustomFunction(callback)){ // for CF10 we could specify a type of "function", but not in CF9 throw(type="Application", message="Invalid callback argument value", detail="The callback argument of the replaceWithCallback() function must itself be a function reference."); } if (!isValid("regex", scope, "(?i)ONE|ALL")){ throw(type="Application", message="The scope argument of the replaceWithCallback() function has an invalid value #scope#.", detail="Allowed values are ONE, ALL."); } var startAt = 1; while (true){ // there's multiple exit conditions in multiple places in the loop, so deal with exit conditions when appropriate rather than here if (caseSensitive){ var found = reFind(regex, string, startAt, true); }else{ var found = reFindNoCase(regex, string, startAt, true); } if (!found.pos[1]){ // ie: it didn't find anything break; } found.substring=[]; // as well as the usual pos and len that CF gives us, we're gonna pass the actual substrings too for (var i=1; i &lt;= arrayLen(found.pos); i++){ found.substring[i] = mid(string, found.pos[i], found.len[i]); } var match = mid(string, found.pos[1], found.len[1]); var offset = found.pos[1]; var replacement = callback(match, found, offset, string); string = removeChars(string, found.pos[1], found.len[1]); string = insert(replacement, string, found.pos[1]-1); if (scope=="ONE"){ break; } startAt = found.pos[1] + len(replacement); } return string; } </code></pre> <p>Tests / samples:</p> <pre><code>function reverseEm(required string match, required struct found, required numeric offset, required string string){ return reverse(match); } input = "abCDefGHij"; result = replaceWithCallback(input, "[a-z]{2}", reverseEm, "ALL", true); writeOutput(input &amp; "&lt;br&gt;" &amp; result &amp; "&lt;br&gt;&lt;hr&gt;"); function oddOrEven(required string match, required struct found, required numeric offset, required string string){ var oddOrEven = match MOD 2 ? "odd" : "even"; return match &amp; " (#oddOrEven#)"; } input = "1, 6, 12, 17, 20"; result = replaceWithCallback(input, "\d+", oddOrEven, "ALL", true); writeOutput(input &amp; "&lt;br&gt;" &amp; result &amp; "&lt;br&gt;&lt;hr&gt;"); function messWithUuid(required string match, required struct found, required numeric offset, required string string){ var firstEight = reverse(found.substring[2]); var nextFour = lcase(found.substring[3]); var secondSetOfFour = "&lt;strong&gt;" &amp; found.substring[4] &amp; "&lt;/strong&gt;"; var lastBit = reReplace(found.substring[5], "\d", "x", "all"); return "#firstEight#-#nextFour#-#secondSetOfFour#-#lastBit#"; } input = "#createUuid()#,XXXXXXXXX-XXXX-XXXX-XXXXXXXXXXXXXXXX,#createUuid()#"; result = replaceWithCallback(input, "([0-9A-F]{8})-([0-9A-F]{4})-([0-9A-F]{4})-([0-9A-F]{16})", messWithUuid, "ALL", true); writeOutput(input &amp; "&lt;br&gt;" &amp; result &amp; "&lt;br&gt;&lt;hr&gt;"); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T21:48:07.657", "Id": "45014", "Score": "2", "body": "I find it odd that you don't scope your arguments, any reason for that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-25T12:43:37.123", "Id": "45604", "Score": "2", "body": "Hi @Busches, good observation. I wrote up my position on this on my [blog][1]. Thanks for the inspiration for the article. Bottom line: I think the code is clearer that way.\n\n [1]: http://cfmlblog.adamcameron.me/2013/07/scoping-or-not-scoping.html" } ]
[ { "body": "<p>If the idea is to model this function on JavaScript's <code>String.replace()</code>, then there is a \"bug\". In JavaScript, when doing a global replace, the last argument passed to the callback is always the <em>original unmodified string</em>, not the string that may have had some of the replacements already applied to it, which is what you've written. The same should be true of the offsets passed to the callback: they should indicate the original positions.</p>\n\n<p>Keeping in mind that I'm a complete newbie to CFML… I'd make a few minor tweaks to the loop. </p>\n\n<p>By converting <code>while (true) { … }</code> to <code>do { … } while (scope == \"ALL\");</code>, you can avoid one of the inelegant <code>break;</code> statements.</p>\n\n<p>When defining <code>match</code>, you can just reuse <code>found.substring[1]</code>, and save a call to <code>mid()</code>.</p>\n\n<p>In the following few lines, you can reuse <code>offset</code> instead of <code>found.pos[1]</code> for a slight improvement in readability.</p>\n\n<pre><code>var lengthDiff = 0;\nvar origString = string;\ndo {\n var found = caseSensitive ? REFind(regex, string, startAt, true)\n : REFindNoCase(regex, string, startAt, true);\n if (!found.pos[1]) { // ie: it didn't find anything\n break;\n }\n found.substring=[]; // as well as the usual pos and len that CF gives us, we're gonna pass the actual substrings too\n for (var i=1; i &lt;= arrayLen(found.pos); i++){\n found.substring[i] = mid(string, found.pos[i], found.len[i]);\n }\n var match = found.substring[1];\n var offset = found.pos[1];\n var length = found.len[1];\n\n var replacement = callback(match, found, offset - lengthDiff, origString);\n string = removeChars(string, offset, length);\n string = insert(replacement, string, offset-1);\n\n lengthDiff += len(replacement) - length;\n startAt = offset + len(replacement);\n} while (scope == \"ALL\");\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-29T11:08:09.883", "Id": "130089", "Score": "0", "body": "Nice one! Thanks for spotting the bug and my brain fart in re-calling `mid()`. Also nice adjustment with the loop exit condition: much cleaner." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-29T10:25:08.713", "Id": "71153", "ParentId": "28646", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T13:27:05.717", "Id": "28646", "Score": "6", "Tags": [ "regex", "callback", "coldfusion", "cfml" ], "Title": "replaceWithCallback() UDF" }
28646
<p>I am porting a linear optimization model for power plants from <a href="http://gams.com/" rel="nofollow">GAMS</a> to <a href="https://software.sandia.gov/trac/coopr/wiki/Pyomo" rel="nofollow">Pyomo</a>. Models in both frameworks are a collection of sets (both elementary or tuple sets), parameters (fixed values, defined over sets), variables (unknowns, defined over sets, value to be determined by optimization) and equations (defining relationships between variables and parameters).</p> <p>In the following example, I am asking for ideas on how to make the following inequality more readable:</p> <pre><code>def res_stock_total_rule(m, co, co_type): if co in m.co_stock: return sum(m.e_pro_in[(tm,)+ p] for tm in m.tm for p in m.pro_tuples if p[1] == co) + \ sum(m.e_pro_out[(tm,)+ p] for tm in m.tm for p in m.pro_tuples if p[2] == co) + \ sum(m.e_sto_out[(tm,)+ s] for tm in m.tm for s in m.sto_tuples if s[1] == co) - \ sum(m.e_sto_in[(tm,)+ s] for tm in m.tm for s in m.sto_tuples if s[1] == co) &lt;= \ m.commodity.loc[co, co_type]['max'] else: return Constraint.Skip </code></pre> <p><strong>Context:</strong></p> <ul> <li><code>m</code> is a model object, which contains all of the above elements (sets, params, variables, equations) as attributes.</li> <li><code>m.e_pro_in</code> for example is a 4-dimensional variable defined over the tuple set <em>(time, process name, input commodity, output commodity)</em>.</li> <li><code>m.tm</code> is a set of timesteps <em>t = {1, 2, ...}</em>, <code>m.co_stock</code> the set of stock commodity, for which this rule will apply only (otherwise, no Constraint is generated via Skip).</li> <li><code>m.pro_tuples</code> is a set of all valid (i.e. realisable) tuples <em>(process name, input commodity, output commodity)</em>.</li> <li><code>m.commodity</code> is a Pandas DataFrame that effectively acts as a model parameter.</li> </ul> <p><strong>My question now is this:</strong></p> <p>Can you give me some hints on how to improve the readability of this fragment? The combination of tuple concatenation, two nested list comprehensions with conditional clause, Pandas DataFrame indexing, and a multiline expression with line breaks all make it less than easy to read for someone who might just be learning Python while using this model.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T11:18:49.763", "Id": "45246", "Score": "0", "body": "Is there any necessity for it to be an expression?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T15:51:30.360", "Id": "45338", "Score": "0", "body": "No, as I found out in the meantime. The revised version is added to the question." } ]
[ { "body": "<p>First of all, use helper functions or explicit for loops.</p>\n\n<p>E.g. you're looping over <code>m.tm</code> four times. This can be done in a single loop. It might need more lines of code, but it will get much more readable.</p>\n\n<p>E.g.</p>\n\n<pre><code>def res_stock_total_rule(m, co, co_type):\n if not co in m.co_stock:\n return Constraint.Skip\n\n val = 0\n for tm in m.tm: # one single loop instead of four\n for p in m.pro_tuples:\n if p[1] == co:\n val += m.e_pro_in[(tm,) + p)]\n if p[2] == co:\n val += m.e_pro_out[(tm,) + p)]\n for s in m.sto_tuples: # one single loop instead of two\n if s[1] == co:\n val += m.e_sto_out[(tm,) + p)] - m.e_sto_in[(tm,) + p)]\n return val &lt;= m.commodity.loc[co, co_type]['max']\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T14:47:11.220", "Id": "28649", "ParentId": "28647", "Score": "4" } }, { "body": "<p>Wrapping with parentheses is often preferable to newline escapes:</p>\n\n<pre><code>def res_stock_total_rule(m, co, co_type):\n if co in m.co_stock:\n return (\n sum(m.e_pro_in [(tm,) + p] for tm in m.tm for p in m.pro_tuples if p[1] == co) +\n sum(m.e_pro_out[(tm,) + p] for tm in m.tm for p in m.pro_tuples if p[2] == co) +\n sum(m.e_sto_out[(tm,) + s] for tm in m.tm for s in m.sto_tuples if s[1] == co) -\n sum(m.e_sto_in [(tm,) + s] for tm in m.tm for s in m.sto_tuples if s[1] == co)\n ) &lt;= m.commodity.loc[co, co_type]['max']\n else:\n return Constraint.Skip\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-28T07:21:34.247", "Id": "180099", "Score": "0", "body": "Indeed, but in case of an expression *that* long, omitting the line continuation character `\\` does not help much." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-27T22:01:27.320", "Id": "98268", "ParentId": "28647", "Score": "1" } } ]
{ "AcceptedAnswerId": "28649", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T14:16:10.587", "Id": "28647", "Score": "4", "Tags": [ "python", "matrix", "pandas" ], "Title": "Long expression to sum data in a multi-dimensional model" }
28647
<p>I've written a little function that iterates over two iterables. The first one returns an object which is used to convert an object of the second iterable. I've got a working implementation, but would like to get some feedback.</p> <p>A simple use case would look like this:</p> <pre><code>list(serialize([String(), String()], [1, 2])) # should work list(serialize([String(), String()], range(3))) # should fail, too many values list(serialize([String(), String()], range(1))) # should fail, too few values </code></pre> <p>But sometimes the number of values is not known but the type is the same. Therefore infinite iterators should be allowed as types argument:</p> <pre><code>list(serialize(it.repeat(String()), range(3))) # should work </code></pre> <p>Of course finite iterators are allowed as well:</p> <pre><code>list(serialize(it.repeat(String(), times=3), range(3))) # should work list(serialize(it.repeat(String(), times=4), range(5))) # should fail # should fail, but probably not that easy to do. list(serialize(it.repeat(String(), times=4), range(3))) </code></pre> <p>My working implementation (except for the last case) looks like this:</p> <pre><code>class String(object): def dump(self, value): return str(value) def serialize(types, values): class Stop(object): """Since None can be valid value we use it as fillvalue.""" if isinstance(types, collections.Sized): # Since None is a valid value, use a different fillvalue. tv_pairs = it.izip_longest(types, values, fillvalue=Stop) else: tv_pairs = it.izip(it.chain(types, (Stop,)), values) for type, value in tv_pairs: if type is Stop: raise ValueError('Too many values.') if value is Stop: raise ValueError('Too few values.') yield type.dump(value) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T15:25:27.507", "Id": "44993", "Score": "0", "body": "you could be checking to see if the lengths of the two lists match instead of messing around with `izip`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T15:35:50.723", "Id": "44996", "Score": "0", "body": "@omouse This won't work if a generator is used." } ]
[ { "body": "<p>There is no (general) way of telling the difference between an infinite and a finite iterator.</p>\n\n<p><code>types</code> might be a generator that stops yielding after a million items have been yielded. The only fool-proof way of telling would be to consume the generator up to the point where it stops yielding items. Of course, even if we've consumed a billion items and it hasn't stopped, we can't be sure it wouldn't stop at a later point.</p>\n\n<p>This is why I recommend you change the specification for your function. The new version will yield items until <code>values</code> have been up. If there are too few <code>types</code>, it raises <code>ValueError</code>.</p>\n\n<pre><code>def serialize(types, values):\n types_iter = iter(types)\n for value in values:\n try:\n type = next(types_iter)\n except StopIteration:\n raise ValueError(\"Too few types.\")\n yield type.dump(value)\n</code></pre>\n\n<p>If you really want to, you can check with <code>len()</code> that the lengths of <code>types</code> and <code>values</code> are the same, but as you have said, this will only work for some iterables.</p>\n\n<pre><code>def serialize(types, values):\n try:\n len_types, len_values = len(types), len(values)\n except TypeError:\n pass\n else:\n if len_values &gt; len_types:\n raise ValueError(\"Too many values.\")\n if len_values &lt; len_types:\n raise ValueError('Too few values.')\n\n for type, value in itertools.izip(types, values):\n yield type.dump(value)\n return\n\n types_iter = iter(types)\n for value in values:\n try:\n type = next(types_iter)\n except StopIteration:\n raise ValueError(\"Too many values.\")\n yield type.dump(value)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T17:50:06.220", "Id": "28658", "ParentId": "28648", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T14:30:07.373", "Id": "28648", "Score": "1", "Tags": [ "python", "serialization" ], "Title": "Iterating over two iterables" }
28648
<p>I'm trying to learn how to use threads to generate lots of random numbers. In particular, I'd like know:</p> <ul> <li><p>Is the following code thread safe? (I think the histogram class is the only one that requires special attention)</p></li> <li><p>Are there implication for the 'randomness' of my numbers when they are generated from different threads?</p></li> <li><p>Is my timing giving me meaningful results?</p></li> </ul> <p>Currently, I can't use a std::vector as my container type, because my histogram class relies on the container being initialised with zeroed elements. Is it possible to allow both fixed length and variable length containers?</p> <pre><code>#include &lt;random&gt; #include &lt;array&gt; #include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;thread&gt; #include &lt;algorithm&gt; #include &lt;mutex&gt; #include &lt;chrono&gt; //class to produce random numbers from a poisson distribution class poisson_generator { public: poisson_generator( int seed, double mean) :engine{ seed }, poisson{ mean } {} int operator()() { return sample(); } int sample() { return poisson(engine) ; } private: std::default_random_engine engine; std::poisson_distribution&lt;int&gt; poisson; }; //class to store random numbers template &lt; class Container&gt; class histogram { public: histogram() :fData{} {} void fill( int val ) { std::lock_guard&lt;std::mutex&gt; guard(fMutex); ++fData[val]; } typename Container::iterator begin() { return fData.begin(); } typename Container::iterator end() { return fData.end(); } typename Container::value_type at(typename Container::size_type pos) { std::lock_guard&lt;std::mutex&gt; guard(fMutex); return fData.at(pos); } private: Container fData; std::mutex fMutex; }; //Function to gnenerate events template &lt;class Generator, class Storage&gt; void generate_events( Generator&amp; g , Storage&amp; store, int nEvents ) { std::cout &lt;&lt; "Generating " + std::to_string(nEvents) + " events.\n"; while ( nEvents-- ) { store.fill( g() ); } } //Printer for the histogram template &lt;class H&gt; void printHistogram( H&amp; h, unsigned int min, unsigned int max, int peak = 30 ) { auto total = std::accumulate( begin(h), end(h), 0 ); std::cout &lt;&lt; "There were " &lt;&lt; total &lt;&lt; " events" &lt;&lt; '\n' ; auto dmax = *std::max_element( begin(h), end(h) ); auto denom = (dmax &gt; peak ? dmax : peak ) / peak; auto length = end(h) - begin(h); for ( unsigned int i = min ; i != max ; ++ i) { std::cout &lt;&lt; std::setw(4) &lt;&lt; i &lt;&lt; ' ' &lt;&lt; (i &gt; length ? 0 : std::string( h.at(i) / denom, '*' ) ) &lt;&lt; '\n'; } } int main( int argc, char * argv[] ) { //Set up histogram&lt;std::array&lt;int, 100&gt; &gt; h; int sample_size = 1000000; std::random_device rd; //Create threads std::vector&lt;std::thread&gt; threads; auto nThreads = 8; //default //Read number of threads from command line if (argc == 2 ) {nThreads = std::stoi(argv[1]) ; } auto start = std::chrono::monotonic_clock::now(); for( int t = 0 ; t != nThreads ; ++t ) { //Divide sample size between nThreads int sample_t = sample_size / nThreads; if ( t == nThreads - 1 ) { sample_t = sample_size - ( nThreads - 1 ) * sample_t ; } //Generate random events threads.push_back(std::thread( [&amp;h, t, sample_t, &amp;rd] () { poisson_generator pg ( rd(), 10 ); generate_events( pg, h, sample_t); } ) ); } for (auto&amp; thread : threads ) { thread.join() ; } //Timing print out auto finish = std::chrono::monotonic_clock::now(); auto time_period = finish - start; std::cout &lt;&lt; "Processing took " &lt;&lt; std::chrono::duration&lt;double, std::milli&gt;(time_period).count() &lt;&lt; " ms .\n" ; //Histogram print out printHistogram( h, 0, 25); return 0; } </code></pre>
[]
[ { "body": "<p>There are a couple of things to worry about wrt to shared memory.</p>\n\n<p>First, <code>histogram&lt;T&gt;::begin</code> and <code>histogram&lt;T&gt;::end</code> provide unguarded access to the container. You're using them safely here, but you should generally not provide such unguarded access. One possible solution is a friend <code>histogram_range</code>, which has a <code>std::lock_guard</code> against <code>fMutex</code> as a member and provides <code>begin</code> and <code>end</code> functions that return <code>Container::const_iterator</code>.</p>\n\n<p>Second, you provide shared access to <code>rd</code>. The standard doesn't require (as far as I can tell) that <code>rd::operator()</code> be thread-safe. Better would be to add the following line to your for loop: <code>const auto seed = rd();</code> and capture <code>seed</code> instead of <code>&amp;rd</code> in the lambda expression.</p>\n\n<p>Otherwise, your thread safety seems OK.</p>\n\n<hr>\n\n<p>I can't imagine that generating random numbers from different threads would have a deleterious effect on the randomness of the numbers. In fact, the excellent <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3551.pdf\" rel=\"nofollow\"><code>&lt;random&gt;</code> primer</a> released by the C++ standards committee explicitly mentions (approvingly) that applications may create thread-local engines (see footnote 14 on pg 5).</p>\n\n<hr>\n\n<p>You appear to be measuring time correctly (except see below), and in particular you appear to be printing the number of milliseconds that your program takes to generate the random data you care about. Beyond that, I'm not sure what you mean by meaningful.</p>\n\n<p><code>std::monotonic_clock</code> was present in some drafts, but was removed from the final standard. Use <code>std::steady_clock</code> instead.</p>\n\n<hr>\n\n<p>Some general notes:</p>\n\n<p>In <code>histogram</code>: I suggest that <code>at</code> be declared <code>const</code>, and <code>fMutex</code> be declared <code>mutable</code>. Read-only access to a <code>const histogram&lt;T&gt;&amp;</code> should be possible.</p>\n\n<p>Your code has undefined behavior whenever your generator generates a number larger than 100 (because you use a <code>std::array&lt;int, 100&gt;</code> as your backing store). Consider using <code>at</code> instead of <code>operator[]</code> to access the data, as <code>at</code> does bounds checking. Probably a better solution is to use a <code>std::vector</code> as your storage instead of templatizing on the <code>Container</code> type, and doing explicit bounds checking yourself in <code>fill</code>. You can then expand the <code>vector</code> (e.g. with</p>\n\n<pre><code>if (val &gt; fData.size()) fData.insert(fData.end(), val - fData.size(), 0);\n</code></pre>\n\n<p>Your spacing and indentation are inconsistent. That makes your code more difficult to read.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T19:17:59.337", "Id": "45190", "Score": "0", "body": "Thanks. The indentation is the result of my poor copy and paste skills :(. Your comments on shared access and constness are really useful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T19:21:40.477", "Id": "45191", "Score": "0", "body": "Ideally, I would like allow std::array (silently ignoring numbers out of range) AND std::vector( resizing if necessary ). Do you think it's possible/sensible to have one class do this or should I just write two classes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T22:06:21.913", "Id": "45208", "Score": "0", "body": "@paco_uk There's a lot of shared code between the two. You could keep it as a template with a partial specialization of `template <typename T> histogram<std::vector<T>>::fill(int)`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T13:55:05.387", "Id": "28711", "ParentId": "28650", "Score": "4" } }, { "body": "<p>I just have a few minor points:</p>\n\n<ul>\n<li><p>C++11 now supports <a href=\"http://www.stroustrup.com/C++11FAQ.html#brackets\" rel=\"nofollow\">right-angle brackets for templates</a>, so instead of this:</p>\n\n<blockquote>\n<pre><code>histogram&lt;std::array&lt;int, 100&gt; &gt; h;\n</code></pre>\n</blockquote>\n\n<p>you can now have this (with them together):</p>\n\n<pre><code>histogram&lt;std::array&lt;int, 100&gt;&gt; h;\n</code></pre></li>\n<li><p>This is not very maintainable:</p>\n\n<blockquote>\n<pre><code>if (argc == 2 )\n{nThreads = std::stoi(argv[1]) ; }\n</code></pre>\n</blockquote>\n\n<p>If you're going to use curly braces for possible additional lines, it may look misleading to arrange them in such a way. Just do it the same way you're already doing with existing multi-line statements.</p></li>\n<li><p>Your indentation within <code>main()</code> is inconsistent. Specifically, the two <code>for</code> loops are left-aligned, making it look like they're separate functions. Make sure all of this stays consistent.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-10T00:03:01.040", "Id": "62478", "ParentId": "28650", "Score": "3" } } ]
{ "AcceptedAnswerId": "28711", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T15:40:58.613", "Id": "28650", "Score": "6", "Tags": [ "c++", "multithreading", "c++11", "random" ], "Title": "Generating random numbers in multiple threads" }
28650
<p>I have an unusual data structure that I need to search - the structure is the result of parsing a JSON file returned from an HTTP request.</p> <p>The top-level object is an Array, but from top to bottom I have <code>Array-&gt;Hash-&gt;Array-&gt;Hash</code>.</p> <p>I'm writing code to check the value of a given key in the innermost hash, across the entire data structure.</p> <p>As it stands, my code is like this:</p> <pre><code>json = JSON.parse(File.read(file)) json.each do |hash1| hash1.keys.each do |key| hash1[key].each do |inner_hash| # search in the inner hash end end end </code></pre> <p>I know this is ugly. I know there are better ways to iterate over collections and to combine selections together. I'm just not sure what I should do in this instance given the repeated sliding from array to hash.</p> <p><strong>What I'm Searching</strong></p> <p>In the above code, I have the search snipped out. My goal with this iteration structure is to skim through entries (the hashes at the <code>entry_id</code> level) for various conditions and either immediately act on or return the Hash object when the conditions are met. For example, if the condition is that <code>field1</code> contains <code>something</code>, I might want to return </p> <pre><code>[ { "entry_id": 544, "field1": "something", "field2": "something else", "field3": 456 }, { "entry_id": 546, "field1": "something!", "field2": "something else!", "field3": 012 } ] </code></pre> <p><strong>Example of Data Structure</strong></p> <pre><code>[ { "12345": [ { "entry_id": 543, "field1": "value", "field2": "other value", "field3": 123 }, { "entry_id": 544, "field1": "something", "field2": "something else", "field3": 456 } ], "23456": [ { "entry_id": 545, "field1": "new value", "field2": "other new value", "field3": 789 }, { "entry_id": 546, "field1": "something!", "field2": "something else!", "field3": 012 } ] } ] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T16:26:42.387", "Id": "45000", "Score": "0", "body": "Please paste a short (but complete) example of that data-structure, otherwise you are forcing everyone to prepare one for testing purposes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T17:12:20.303", "Id": "45004", "Score": "0", "body": "D'oh, I should have done that! Thanks, example added." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T17:16:15.730", "Id": "45006", "Score": "0", "body": "thanks. More questions: what's in the search? what value must be returned?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T17:26:57.367", "Id": "45007", "Score": "0", "body": "Edited question to address your question. This is an example - there is more than one potential use and more than one potential return result. At times I may want to collect an array of objects, at times I may want to handle matching objects inline." } ]
[ { "body": "<p>You can iterate over the hashes/arrays using a custom enumerator (modified from a StackOverflow answer <a href=\"https://stackoverflow.com/a/3748761/1614607\">here</a>):</p>\n\n<pre><code>def dfs(obj, &amp;blk)\n return enum_for(:dfs, obj) unless blk \n yield obj if obj.is_a? Hash\n if obj.is_a?(Hash) || obj.is_a?(Array)\n obj.each do |*a|\n dfs(a.last, &amp;blk)\n end\n end\nend\n</code></pre>\n\n<p>You can then use this enumerator builder method in any number of other helper methods for whatever you need. For example, to perform your example search, you could define:</p>\n\n<pre><code>def find_node_with_value(obj, key, value)\n dfs(obj).select do |node|\n node[key].respond_to?(:include?) &amp;&amp; node[key].include?(value)\n end\nend\n</code></pre>\n\n<p>And then use it like:</p>\n\n<pre><code>find_node_with_value(json_data, \"field1\", \"something\")\n# [{\"entry_id\"=&gt;544, \"field1\"=&gt;\"something\" ...}, {\"entry_id\"=&gt;546, \"field1\"=&gt;\"something!\" ...}]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T17:09:27.697", "Id": "28844", "ParentId": "28652", "Score": "2" } }, { "body": "<p>You could do something like this...</p>\n\n<pre><code>json = JSON.parse(File.read(file))\ninner_hashes = json.lazy.map{|hash| hash.values }.flatten\nresults = inner_hashes.select{|x| ... }\n</code></pre>\n\n<p><code>lazy</code> is from ruby 2.0. It's just there to let you deal with the items one at a time as they are found.</p>\n\n<p>This solution assumes you don't care about the keys of the first level of hashes. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-29T12:38:24.490", "Id": "29125", "ParentId": "28652", "Score": "0" } }, { "body": "<p>You may want to look into <a href=\"https://github.com/joshbuddy/jsonpath\" rel=\"nofollow\">JSONPath</a>, which gives you XPath-like querying of JSON objects.</p>\n\n<p>Note that the leading zero in your sample JSON makes it invalid.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-18T12:31:56.487", "Id": "29923", "ParentId": "28652", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T16:00:23.090", "Id": "28652", "Score": "2", "Tags": [ "ruby", "iteration" ], "Title": "Eliminating nested each" }
28652
<p>As a part of a job test, I wrote following implementation of the Actor execution model:</p> <pre><code>import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.Executor; public abstract class Actor implements Runnable { private final Executor executor; /** current token */ private Message message=null; /** rest of tokens */ private Queue&lt;Message&gt; queue = new LinkedList&lt;Message&gt;(); private boolean isFired=false; public Actor(Executor executor) { this.executor = executor; } /** * Frontend method which may be called from other Thread or Actor. * Saves the message and initiates Actor's execution. */ protected void post(Message message) { synchronized(this) { if (isFired) { queue.add(message); return; } this.message=message; isFired=true; // to prevent multiple concurrent firings } executor.execute(this); } @Override public void run() { for (;;) { this.message.run(); synchronized(this) { this.message = queue.poll(); // consume token if (this.message==null) { isFired=false; // allow firing return; } } } } protected abstract class Message { protected abstract void run(); } } </code></pre> <p>Reviewers concluded, in particular, that "Actor class have synchronization issues", but did not want to explain why.</p> <p>Can you see any synchronization problems here?</p> <p>The code, along with a test, can be downloaded from <a href="https://github.com/rfqu/CodeSamples/tree/master/src/simpleactor" rel="nofollow">https://github.com/rfqu/CodeSamples/tree/master/src/simpleactor</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T13:24:13.990", "Id": "49136", "Score": "0", "body": "You aren't being consistent with when you use `this.` to access a member variable. `run()` does not require `this.` to access message since there is not local variable with that name." } ]
[ { "body": "<p>I don't see any immediate synchronization issues. However that does not necessarily mean there aren't any. One synchronization design flaw is that you lock on <code>this</code>, which basically allows other classes to also acquire the lock, and screw with the inner workings of your implementation. Sometimes, you want to design a class like that, this is not such a case.</p>\n\n<p>Secondly, you make things a bit complicated by having a <code>message</code> field, which basically acts as the head of the queue. The entire implemntation can do without it, and then also the need for <code>isFired</code> disappears.</p>\n\n<p>Java also comes with a variety of Queue implementations that do synchronizing for you. In this case I'd replace the Linked List with a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html\" rel=\"nofollow\"><code>ConcurrentLinkedQueue</code></a>, as it is also unbounded.</p>\n\n<p>An internal lock can be used to make sure messages are not run concurrently.</p>\n\n<p>So run() and post() would look like this : </p>\n\n<pre><code>private final Object lock = new Object();\n\n@Override\npublic void run() {\n synchronized (lock) {\n Message message = queue.poll();\n if (message != null) {\n message.run();\n }\n }\n}\n\nprotected final void post(Message message) {\n queue.add(message);\n executor.execute(this);\n}\n</code></pre>\n\n<p>Note that I've also made <code>post()</code> and <code>run()</code> final, so subclasses cannot mess with the proper functioning of the <code>Actor</code> behavior.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T16:41:19.513", "Id": "45079", "Score": "0", "body": "The way you did post() make executing of different messages parallel, which does not comply with the Actor model. I used own synchronization instead of synchronized queue in order to avoid parallel executions of the same actor instance. The isFired variable used as an indicator that this instance is being executed and should not be submitted to the executor once again. Indeed, synchronizing on an internal object, inaccessible outside the actor instance, would be better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T16:41:55.673", "Id": "45080", "Score": "0", "body": "In fact, isFired==true just when message!=null, so one of them (but not both) can be eliminated. I preferred to retain message to avoid linking/delinking when message rate is low - see updated version on github." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T17:39:50.677", "Id": "45084", "Score": "0", "body": "I've edited the answer to address avoiding concurrent execution of messages. Avoiding linking/delinking sounds like premature optimization." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T18:16:39.297", "Id": "45087", "Score": "0", "body": "the edited answer has severe drawback - it calls message.run() under closed lock, blocking all threads in the thread pool except one, thus making any pool a single-threaded one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T18:34:18.997", "Id": "45089", "Score": "0", "body": "It will only block other threads that attempt to acquire the same lock. The pool is fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T18:57:39.940", "Id": "45090", "Score": "0", "body": "Let you have N threads in the pool, and send M>N messages to the same actor. Then all threads except one would be blocked." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T19:46:24.247", "Id": "45091", "Score": "0", "body": "I thought you wanted it so, that messages on the same actor do not execute concurrently, in fact, what you describe is true for your original solution as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T19:54:55.027", "Id": "45092", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9724/discussion-between-bowmore-and-alexei-kaigorodov)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T16:09:25.830", "Id": "28720", "ParentId": "28653", "Score": "2" } }, { "body": "<p>As your code is now, the following can happen: </p>\n\n<ol>\n<li><code>post(Message message)</code> is called and completes. </li>\n<li><code>post(Message message)</code> is called again. </li>\n<li>The thread started by 1. (in <code>executor.execute(this)</code>) starts -- and processes the message from 2. However, it does <strong>not</strong> get a chance to enter the synchronized block. </li>\n<li>The thread started by 2. (in <code>executor.execute(this)</code>) starts -- and <strong>reprocesses</strong> the message from 2. </li>\n</ol>\n\n<p>and so forth. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-03T08:44:39.147", "Id": "46316", "Score": "0", "body": "I cannot agree with your scenario. First, messages are processed in order, so the thread started from 1) first processes the message saved in the variable `message` by the step 1), not by the step 2). Second, step 2 does not start new thread because `isFired==true`. This variable guarantees that at most one thread at a time processes messages. And after `message.run();`, processing thread unconditionally enters synchronized block - why do you claim that `it does not get a chance to enter the synchronized block`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-03T10:17:59.770", "Id": "46319", "Score": "0", "body": "There is no guarantee as to when a thread will execute, or sleep." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-03T14:03:01.503", "Id": "46332", "Score": "0", "body": "If you want to prove the code assumes some timing, then place Thread.sleep() everywhere, construct desired timing and show that, say, second message is processed twice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T13:41:25.983", "Id": "49137", "Score": "0", "body": "I agree with Alexei. If you are at step 3 then it means that `isFired` is true, so if another message arrives (step 4), it will never call `executor.execute(this)`. Look at `post(message)` more carefully." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-02T19:36:38.710", "Id": "29312", "ParentId": "28653", "Score": "0" } }, { "body": "<p>I don't see a major synchronization flaw.</p>\n\n<p><strong>However</strong>, your code won't run all messages on the same thread if there is some long pauses between messages. Then <code>executor.execute(this)</code> will be called many times and it could start any thread if the <code>executor</code> has more than one thread.</p>\n\n<p>I believe that an actor should run on the same thread all the time. I'm not sure about this, and the documentation in wikipedia does not seem to support this. That would be relevant for example if the actor maintains a counter of all messages it received. </p>\n\n<p><strong>Anti-However</strong>: I don't even see how your code would fail even in such a case because of the Java memory model: every time you call <code>synchronized</code> the memory is flushed, so the counter (or whatever) would be kept current across all (sequentially executed) threads nonetheless.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T14:55:58.050", "Id": "49140", "Score": "0", "body": "\"actor should run on the same thread all the time\" - very intriguing statement. Do you have any reason for this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T15:18:43.560", "Id": "49141", "Score": "0", "body": "I gave the example with the counter and I guess there are many similar cases. However, if it is possible an actor should not keep any inner state." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T17:17:51.310", "Id": "49156", "Score": "0", "body": "Do you think actor's state is saved in a thread? This is simply wrong. Actor's state and executing thread have no connection (unless connection organized artificially), so changing threads does not affect actor's state. And, stateless actors have little sense." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T19:36:32.683", "Id": "49169", "Score": "0", "body": "If your actors have some state then you must explicitly synchronize that too. It might be simpler to then just run an actor in the same thread (maybe many actors on one thread). But as I explained in my post, I believe the synchronization will be correct in your code, even if there is state, just from the Java memory model and your calls to `synchronized`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T13:57:41.197", "Id": "30877", "ParentId": "28653", "Score": "0" } }, { "body": "<p>There is a problem.. You <code>post()</code> your message and it gets assigned in <code>synchronized</code> block, but it gets <em>accessed</em> in non-synchronized block. The field is not <code>volatile</code> therefore even though the reference to <code>this.message</code> might be visible to ThreadB, the inner state of the object might be still invisible. So <code>message.run()</code> may get you into a trouble.</p>\n\n<p>In order to make things right <code>this.message</code> should be marked as volatile. Read about <a href=\"https://www.google.com/#q=java+safe+publishing\" rel=\"nofollow\">safe publishing in Java</a> for more details.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T21:22:19.050", "Id": "70516", "Score": "0", "body": "I've upvoted your post, it's a nice catch, but LMGTFY is rather rude so I've retraced my vote." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T21:22:45.350", "Id": "70517", "Score": "1", "body": "Another reference: *Java Concurrency in Practice*, *3.1.1. Stale Data*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T05:02:16.333", "Id": "70569", "Score": "0", "body": "When you suggest to make `this.message` volatile, you mean to make sure assigment to message `happens before` reading it. But as http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executor.html reads, `Actions in a thread prior to submitting a Runnable object to an Executor happen-before its execution begins, perhaps in another thread`, so no need to make it volatile or put another synchronized block." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T19:25:17.483", "Id": "70671", "Score": "0", "body": "@AlexeiKaigorodov, nice catch!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T20:20:49.190", "Id": "41108", "ParentId": "28653", "Score": "3" } }, { "body": "<p>There is unsafe publication problem exists. You create \"queue\" in unsynchronized block and read it in synchronized block, so due to reordering \"queue\" maybe null or uncomplettly initialized when execution of \"post\" method happen. </p>\n\n<p>To solve this problem just make \"queue\" final(<a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5\" rel=\"nofollow\">JMM 17.5. final Field Semantics</a>) or do on-demand initalization in \"post\" method. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-24T21:30:48.497", "Id": "42701", "ParentId": "28653", "Score": "1" } } ]
{ "AcceptedAnswerId": "41108", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T16:01:51.797", "Id": "28653", "Score": "3", "Tags": [ "java", "multithreading", "actor" ], "Title": "Does this Actor implementation has synchronization problems?" }
28653
<p>I've got the imperative styled solution working perfectly. What I'm wondering is how to make a recursive branch and bound.</p> <p>This is my code below. Evaluate function returns the optimistic estimate, the largest possible value for the set of items which fit into the knapsack (linear relaxation).</p> <p>For some inputs this outputs an optimal solution, for some it comes really close, for every input it is extremely fast, so it doesn't seem that it hangs anywhere in the search space. So, maybe I'm not branching where I have to or I did something wrong. I'm sure optVal is optimal.</p> <pre><code>def branch(items: List[Item], taken: List[Item], capacity: Int, eval: Long): (List[Item], Boolean) = items match { case x :: xs if x.weight &lt;= capacity =&gt; { val (bestLeft, opt) = branch(xs, x :: taken, capacity - x.weight, eval) if (opt) (bestLeft, opt) // if solution is optimal get out of the tree else { val evalWithout = evaluate(taken.reverse_:::(xs)) if (evalWithout &lt; optVal) (bestLeft, opt) else branch(xs, taken, capacity, evalWithout) } } case x :: xs =&gt; branch(xs, taken, capacity, evaluate(taken.reverse_:::(xs))) case Nil =&gt; if ((taken map (_.value) sum) == optVal) (taken, true) else (taken, false) } </code></pre>
[]
[ { "body": "<p>Here is a 'wanna-be functional' solution in java which might help you (it has gone through a set of test cases so I believe it works correctly)</p>\n\n<pre><code>private double bestBound;\n\npublic Knapsack.KnapsackResult solve() {\n Cons&lt;Knapsack.Item&gt; list = Cons.from(items);\n bestBound = 0.0;\n\n double bound = calcBound(list, capacity, 0.0);\n Solution res = dfs(list, 0, capacity, bound, null);\n\n return buildSolution(res);\n}\n\npublic Solution dfs(Cons&lt;Knapsack.Item&gt; list, int value, int weight, double bound,\n Cons&lt;Knapsack.Item&gt; taken) {\n if (bound &lt; bestBound) {\n return null;\n }\n if (list == null) {\n bestBound = bound;\n return new Solution(bound, taken);\n }\n Knapsack.Item item = list.head();\n if (item.weight &gt; weight) {\n return notTaking(list, value, weight, taken);\n }\n\n // taking the item\n Solution left = dfs(list.tail(), value + item.value, weight - item.weight, \n bound, Cons.cons(item, taken));\n\n // not taking the item\n Solution right = notTaking(list, value, weight, taken);\n\n if (left == null) {\n return right;\n }\n if (right == null) {\n return left;\n }\n if (right.bound &gt; left.bound) {\n return right;\n } else {\n return left;\n }\n}\n\nprivate Solution notTaking(Cons&lt;Knapsack.Item&gt; list, int value, int weight, \n Cons&lt;Knapsack.Item&gt; taken) {\n Cons&lt;Knapsack.Item&gt; tail = list.tail();\n Cons&lt;Knapsack.Item&gt; without;\n if (taken != null) {\n without = taken.reverse().append(tail);\n } else {\n without = tail;\n }\n double newBound = calcBound(without, capacity, 0.0);\n if (newBound &lt;= bestBound) {\n return null;\n }\n return dfs(tail, value, weight, newBound, taken);\n}\n\npublic static double calcBound(Cons&lt;Knapsack.Item&gt; list, int k, double acc) {\n if (list == null) {\n return acc;\n }\n\n Knapsack.Item head = list.head();\n if (head.weight &lt;= k) {\n return calcBound(list.tail(), k - head.weight, acc + head.value);\n } else {\n return acc + head.relativeValue() * k;\n }\n}\n</code></pre>\n\n<p>Here I used <code>cons</code> for lists - so it's the same as lists in Scala. There's only one \"global\" variable - <code>bestBound</code> - which, I know, not very functional, but it was just simpler than passing it around.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-07T15:18:55.353", "Id": "46664", "Score": "0", "body": "Thanks for the algorithm, the thing is, it's exactly as same as mine. I did eventually discover that for some unknown reason, taken.reverse_:::(xs) is incorrect. By changing it to taken ::: xs the algorithm finds the solution almost instantly for my test cases." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-26T11:02:51.000", "Id": "29019", "ParentId": "28656", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T16:56:02.267", "Id": "28656", "Score": "4", "Tags": [ "recursion", "scala", "knapsack-problem" ], "Title": "Recursive branch and bound Knapsack solution" }
28656
<p>I have written the following algorithm (for Android/NDK) to apply levels to a bitmap. The problem is that it is really very slow. On a fast device such as the SGSIII, it can take up to 4 seconds for an 8MP image. And on devices with ARMv6 takes ages (over 10 seconds). I know that can be speed up with NEON instructions, but I don't have such knowledge.</p> <p>Is there any way to optimize it?</p> <pre><code>void applyLevels(unsigned int *rgb, const unsigned int width, const unsigned int height, const float exposure, const float brightness, const float contrast, const float saturation) { float R, G, B; unsigned int pixelIndex = 0; float exposureFactor = powf(2.0f, exposure); float brightnessFactor = brightness / 10.0f; float contrastFactor = contrast &gt; 0.0f ? contrast : 0.0f; float saturationFactor = 1.0f - saturation; for (int y = 0; y &lt; height; y++) { for (int x = 0; x &lt; width; x++) { const int pixelValue = buffer[pixelIndex]; R = ((pixelValue &amp; 0xff0000) &gt;&gt; 16) / 255.0f; G = ((pixelValue &amp; 0xff00) &gt;&gt; 8) / 255.0f; B = (pixelValue &amp; 0xff) / 255.0f; // Clamp values R = R &gt; 1.0f ? 1.0f : R &lt; 0.0f ? 0.0f : R; G = G &gt; 1.0f ? 1.0f : G &lt; 0.0f ? 0.0f : G; B = B &gt; 1.0f ? 1.0f : B &lt; 0.0f ? 0.0f : B; // Exposure R *= exposureFactor; G *= exposureFactor; B *= exposureFactor; // Contrast R = (((R - 0.5f) * contrastFactor) + 0.5f); G = (((G - 0.5f) * contrastFactor) + 0.5f); B = (((B - 0.5f) * contrastFactor) + 0.5f); // Saturation float gray = (R * 0.3f) + (G * 0.59f) + (B * 0.11f); R = (gray * saturationFactor) + R * saturation; G = (gray * saturationFactor) + G * saturation; B = (gray * saturationFactor) + B * saturation; // Brightness R += brightnessFactor; G += brightnessFactor; B += brightnessFactor; // Clamp values R = R &gt; 1.0f ? 1.0f : R &lt; 0.0f ? 0.0f : R; G = G &gt; 1.0f ? 1.0f : G &lt; 0.0f ? 0.0f : G; B = B &gt; 1.0f ? 1.0f : B &lt; 0.0f ? 0.0f : B; // Store new pixel value R *= 255.0f; G *= 255.0f; B *= 255.0f; buffer[pixelIndex] = ((int)R &lt;&lt; 16) | ((int)G &lt;&lt; 8) | (int)B; pixelIndex++; } } } </code></pre>
[]
[ { "body": "<p>Depending on your compiler, this advice might or might not have an effect. As a rule of thumb, let's try to give the compiler and the reader as many hints as possible and let's make things as simple as it can be.</p>\n\n<pre><code>unsigned int pixelIndex = 0;\nfor (int y = 0; y &lt; height; y++)\n{\n for (int x = 0; x &lt; width; x++)\n {\n some_function(pixelIndex);\n pixelIndex++;\n }\n}\n</code></pre>\n\n<p>could be written with a single-loop, thus saving some comparisons and the update of 3 different variables :</p>\n\n<pre><code>const unsigned int limit = height*width; // your compiler should notice that this is const and does not need being re-evaluated at each iteration but let's give him a bigger hint.\nfor (unsigned int pixelIndex = 0; pixelIndex &lt; limit; pixelIndex++)\n{\n some_function(pixelIndex);\n}\n</code></pre>\n\n<p>You could define <code>exposureFactor</code>, <code>brightnessFactor</code>, <code>contrastFactor</code> and <code>saturationFactor</code>, <code>gray</code> as constants.</p>\n\n<p>You could declare and define <code>R</code>, <code>G</code>, <code>B</code> inside the loop to limit their scope.</p>\n\n<p>You could compute <code>gray * saturationFactor</code> only once if you were storing the result.</p>\n\n<p>You could also try to limit the number of accesses to R,G,B by packing the evaluation. The drawback is that you might lose readibility by doing do.</p>\n\n<p>At the end, my version of the code is </p>\n\n<pre><code>void applyLevels(unsigned int *rgb, const unsigned int width, const unsigned int height, const float exposure, const float brightness, const float contrast, const float saturation)\n{\n const float exposureFactor = powf(2.0f, exposure);\n const float brightnessFactor = brightness / 10.0f;\n const float contrastFactor = contrast &gt; 0.0f ? contrast : 0.0f;\n const float saturationFactor = 1.0f - saturation;\n\n const unsigned int limit = height*width;\n for (unsigned int pixelIndex = 0; pixelIndex &lt; limit; pixelIndex++)\n {\n const int pixelValue = buffer[pixelIndex];\n\n float R = ((pixelValue &amp; 0xff0000) &gt;&gt; 16) / 255.0f;\n float G = ((pixelValue &amp; 0xff00) &gt;&gt; 8) / 255.0f;\n float B = (pixelValue &amp; 0xff) / 255.0f;\n\n // Clamp values + exposure factor + contrast\n R = (((R &gt; 1.0f ? exposureFactor : R &lt; 0.0f ? 0.0f : exposureFactor*R) - 0.5f) * contrastFactor) + 0.5f;\n G = (((G &gt; 1.0f ? exposureFactor : G &lt; 0.0f ? 0.0f : exposureFactor*G) - 0.5f) * contrastFactor) + 0.5f;\n B = (((B &gt; 1.0f ? exposureFactor : B &lt; 0.0f ? 0.0f : exposureFactor*B) - 0.5f) * contrastFactor) + 0.5f;\n\n // Saturation + Brightness\n const float graySaturFactorPlusBrightness = brightnessFactor + ((R * 0.3f) + (G * 0.59f) + (B * 0.11f)) * saturationFactor;\n R = graySaturFactorPlusBrightness + R * saturation;\n G = graySaturFactorPlusBrightness + G * saturation;\n B = graySaturFactorPlusBrightness + B * saturation;\n\n // Clamp values\n R = R &gt; 1.0f ? 255.0f : R &lt; 0.0f ? 0.0f : 255.0f*R;\n G = G &gt; 1.0f ? 255.0f : G &lt; 0.0f ? 0.0f : 255.0f*G;\n B = B &gt; 1.0f ? 255.0f : B &lt; 0.0f ? 0.0f : 255.0f*B;\n\n buffer[pixelIndex] = ((int)R &lt;&lt; 16) | ((int)G &lt;&lt; 8) | (int)B;\n }\n}\n</code></pre>\n\n<p>I am convinced it is <strong>slightly</strong> better than yours from a performance point of view but I'm not sure you'll be able to notice any actual difference in the run time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T22:48:48.247", "Id": "79266", "Score": "1", "body": "The first `R > 1.0f` expressions are always false, because they're a byte value (max 255) divided by `255.0f`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T08:44:59.383", "Id": "79319", "Score": "0", "body": "Pretty clever comment! Thanks for the idea. As you've added an answer yourself, I'll let you add it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T20:08:50.780", "Id": "28662", "ParentId": "28661", "Score": "3" } }, { "body": "<ul>\n<li>Just loop over the index.</li>\n<li>The first clamp is unnecessary. (X &amp; 0xff) will always be between 0 and 255.</li>\n<li>Look at it algebraically. There are some expressions that do not depend on R, B, or B that you can extract from the loop.</li>\n<li>You can extract some common expressions and calculate them at the same time as grey.</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>void applyLevels(unsigned int *rgb, const unsigned int width, const unsigned int height, const float exposure, const float brightness, const float contrast, const float saturation)\n{\n const float exposureFactor = powf(2.0f, exposure);\n const float brightnessFactor = brightness / 10.0f;\n const float contrastFactor = contrast &gt; 0.0f ? contrast : 0.0f;\n const float saturationFactor = 1.0f - saturation;\n\n const float f01 = exposureFactor / 255.0f * contrastFactor;\n const float f02 = 0.5f * (1.0f - contrastFactor);\n\n const unsigned int nPixel = width * height;\n for(unsigned int pixelIndex = 0; pixelIndex &lt; nPixel; ++pixelIndex)\n {\n const unsigned int pixelValue = rgb[pixelIndex];\n float R = static_cast&lt;float&gt;((pixelValue &gt;&gt; 16) &amp; 0xff);\n float G = static_cast&lt;float&gt;((pixelValue &gt;&gt; 8) &amp; 0xff);\n float B = static_cast&lt;float&gt;((pixelValue ) &amp; 0xff);\n\n R = R * f01 + f02;\n G = G * f01 + f02;\n B = B * f01 + f02;\n\n const float f03 = ((R * 0.3f) + (G * 0.59f) + (B * 0.11f)) * saturationFactor + brightnessFactor;\n\n R = (R * saturation + f03) * 255.0f;\n G = (G * saturation + f03) * 255.0f;\n B = (B * saturation + f03) * 255.0f;\n\n R = R &gt; 255.0f ? 255.0f : R &lt; 0.0f ? 0.0f : R;\n G = G &gt; 255.0f ? 255.0f : G &lt; 0.0f ? 0.0f : G;\n B = B &gt; 255.0f ? 255.0f : B &lt; 0.0f ? 0.0f : B;\n\n rgb[pixelIndex] =\n (static_cast&lt;unsigned int&gt;(R) &lt;&lt; 16) |\n (static_cast&lt;unsigned int&gt;(G) &lt;&lt; 8) |\n (static_cast&lt;unsigned int&gt;(B) );\n }\n}\n</code></pre>\n\n<p>Other optimizations:</p>\n\n<ul>\n<li>Do you need an entire 8MP image? Can you downscale the image or even grab a portion?</li>\n<li>How often do you need to apply all four operations to an image? If it is common for some images to only require exposure and saturation then make separate functions.</li>\n<li>Convert the for to a parallel for and use neon and other intrinsics.</li>\n<li>Rather than doing the previous suggestion I would recommend using <a href=\"http://developer.android.com/guide/topics/renderscript/index.html\">Renderscript</a>. It will use your GPU if it can. If it uses the CPU it is automatically multithreaded.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:23:58.610", "Id": "79340", "Score": "0", "body": "About the 8MP, the answer is yes. Users get very annoyed when they edit an image and it gets size reduced. Is like if you edit in Photoshop and after you realize Photoshop reduces your image metrics if you do any change to it. Second question, levels are applied by the user as they wish. I'll check on renderscript." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T21:31:00.920", "Id": "45442", "ParentId": "28661", "Score": "5" } }, { "body": "<p>Depending on the content of the image, you might get an improvement with:</p>\n\n<pre><code>const int pixelPrevious = buffer[0] ^ 1; // A value guaranteed to not match buffer[0].\nfor (unsigned int pixelIndex = 0; pixelIndex &lt; limit; pixelIndex++)\n{\n const int pixelValue = buffer[pixelIndex];\n if (pixelPrevious == pixelValue)\n {\n buffer[pixelIndex] = buffer[pixelIndex - 1];\n continue;\n }\n pixelPrevious = pixelValue;\n</code></pre>\n\n<p>The idea is to skip the recalculation where consecutive pixel values are identical.</p>\n\n<p>I expect that would improve performance iff consecutive pixel values are often identical in the image.</p>\n\n<hr>\n\n<blockquote>\n <p>I know that can be speed up with NEON instructions, but I don't have such knowledge.</p>\n</blockquote>\n\n<p>Here is <a href=\"http://peterdn.com/post/an-introduction-to-ARM-NEON.aspx\" rel=\"nofollow\">an article which talks about using NEON for image processing</a>.</p>\n\n<p>One of the things it says is,</p>\n\n<blockquote>\n <p>It turns out that floating point operations are slow<sup>1</sup> and an immediate improvement can be made by modifying the algorithm slightly to process integers instead of floats.</p>\n</blockquote>\n\n<p>So, firstly, you might get better performance by multiplying everything by 255.</p>\n\n<p>Second, it introduces how to use NEON.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T23:12:02.767", "Id": "45448", "ParentId": "28661", "Score": "5" } }, { "body": "<p>Try change float to double. There are some devices based on ARM architecture that works 40 times slower using floats. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-14T09:41:04.213", "Id": "122803", "ParentId": "28661", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T18:54:22.693", "Id": "28661", "Score": "5", "Tags": [ "c++", "algorithm", "performance", "android", "image" ], "Title": "Image-processing algorithm on mobile device" }
28661
<p>I am currently migrating a large backbone application over to Marionette and am curious as to the opinions on what is a better design for mediating activity between modules.</p> <p>I have an Application that have several Modules where an action in one module might cause activity to happen in other modules.</p> <p>Since these all are coupled to the Application I could simply use the Wreqr interface where:</p> <p><strong>Module 1:</strong></p> <pre><code>someActivity: -&gt; App.vent.trigger("skyFalling") </code></pre> <p><strong>Module 2:</strong></p> <pre><code>initialize: -&gt; App.vent.on("skyFalling", @closeOrSomething) </code></pre> <p><strong>Module 3:</strong></p> <pre><code>initialize: -&gt; App.vent.on("skyFalling", @blinkRapidly) </code></pre> <hr> <p>Or would it be better to trigger an event in Module1 where the Application (or a controller tied to the App) listens and then calls the 'closeOrSomething' and the 'blinkRapidly' functions directly on the modules (since the App is aware of all the modules that it is loading).</p> <p><strong>Application:</strong></p> <pre><code>skyFallingEventHandler: -&gt; Module2.closeOrSomething() Module3.blinkRapidly() </code></pre>
[]
[ { "body": "<p>I have the exact same quandary (and found this question googling for answers). On first read through my opinion was that triggering events on the modules themselves was the best approach on the basis that this loosens any coupling between the modules and other components. However, having given it more thought it seems that this is exactly what the Wreqr interface has been designed for, so actually my approach would be to use the aggregator to handle events. I’d be interested to know which approach you decide to take.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T22:23:36.530", "Id": "28851", "ParentId": "28663", "Score": "1" } }, { "body": "<p>I also came across this googling for answers to this..</p>\n\n<p>I would say that your second version is the way to go. I don't think Module 2, for example, should know that it has to listen to Module 1 events (if even through the app aggregator). If I were to use this module in another system.. that extra listening code doesn't make sense in the new context where I use Module 2. Put it on the application and call into the controller from there.</p>\n\n<p>The following makes way more sense to me currently, and it's what I will go with. </p>\n\n<p><strong>Application</strong></p>\n\n<pre><code>skyFallingEventHandler: -&gt;\n Module2.closeOrSomething()\n Module3.blinkRapidly()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T17:54:40.097", "Id": "34010", "ParentId": "28663", "Score": "1" } }, { "body": "<p>I like to have my cake and eat it too. What I do for these situations is have a real mediator. The app publishes an event that the sky has fallen. Other modules shouldn't have to listen as it's not really their business. I then create a plugin that glues the too. Listens for sky is falling, and directly calls the other modules.</p>\n\n<p>What I like is this plugin is it's own module, which can sit at a top level near your app (probably inside a plugins folder). I create plugins for my app for all different glue behavior. It's very easy to turn off some of this if they are no longer needed, and easy to change as they are isolated, and easy to find as one file per plugin.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T21:39:25.783", "Id": "42812", "ParentId": "28663", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T21:45:57.763", "Id": "28663", "Score": "1", "Tags": [ "javascript", "design-patterns", "backbone.js", "mediator" ], "Title": "Marionette.js Mediator ('global' commands vs app controller)" }
28663
<p>I tried to write a naive Bayes classifier to classify OkCupid profiles, and I was wondering if you could give me feedback on my code. The classifier performs no better than chance and the coding style is probably not great either. I had a training set of 20 good profiles and 20 bad profiles, and a test set of 16 good and 29 bad, so I don't know if I am classifying poorly or if I just don't have enough data.</p> <pre><code>#!/usr/bin/python # Naive Bayes classifier for OkCupid data. The features are the words in # the profile and the classes are HIGH and LOW. This is used to # predict the rating I would give a profile. # TODO: tweak the classifier so it works better. from subprocess import call from math import sqrt # File containing training data in the form "&lt;rating&gt; &lt;username&gt;" TRAINING_DATA = "train.dta" # File containing test set in the form "&lt;rating&gt; &lt;username&gt;" TEST_DATA = "test.dta" # Dictionary dictionary = "TWL06.txt" # Hash table containing words in highly-ranked profiles. HIGH_WORDS = {} # Hash table containing words in low-ranked profiles. LOW_WORDS = {} # Number of users in each category hi = 0 low = 0 # Add training data to the hash tables. t = open(TRAINING_DATA, 'r') for user in t: rating = int(user.split(" ")[0]) name = user.split(" ")[1] # Count users if rating == 1: hi += 1 else: low += 1 # Get data for each user call(["curl", "-o", "tmp.dta", "http://www.okcupid.com/profile/" + name]) d = open("tmp.dta", 'r') # Get word list from user words = {} for line in d: for word in line.split(" "): if "/" in word or "=" in word or "&lt;" in word or "&gt;" in word or "()" in word or "&amp;" in word or len(word) &gt; 10: continue words[word.rstrip().lower()] = None d.close() # Add words in this word list to our master word lists for word in words: if rating == 1: if word in HIGH_WORDS: HIGH_WORDS[word] += 1 else: HIGH_WORDS[word] = 1 else: if word in LOW_WORDS: LOW_WORDS[word] += 1 else: LOW_WORDS[word] = 1 t.close() print HIGH_WORDS print LOW_WORDS # Classify a point, assuming training has already happened. # P(C | F1 ... Fn) proportionate to P(C) * P(F1 | C) * ... * P(Fn | C) def classify(username): # P(C) Phi = float(hi) / float(hi + low) Plow = float(low) / float(hi + low) ratio = Phi / Plow # Get data call(["curl", "-o", "tmp.dta", "http://www.okcupid.com/profile/" + username]) d = open("tmp.dta", 'r') for line in d: for word in line.split(" "): # Calculate the probability of the feature given a class if word in HIGH_WORDS: numHi = float(HIGH_WORDS[word]) else: numHi = 1 if word in LOW_WORDS: numLow = float(LOW_WORDS[word]) else: numLow = 1 ratio = ratio * (numHi / float(hi)) / (numLow / float(low)) # if word in HIGH_WORDS: ## Phi = Phi * float(HIGH_WORDS[word]) / float(hi) ## else: ## Phi = Phi * (1 / float(hi)) # # if word in LOW_WORDS: ## Plow = Plow * float(LOW_WORDS[word]) / float(low) ## else: ## Plow = Plow * (1 / float(low)) print ratio if ratio &gt; 1: return 1 else: return 0 # Compute out of sample error on test set. def getError(): t = open(TEST_DATA, 'r') numUsers = 0.0 total = 0.0 for line in t: user = line.split(" ")[1] rating = int(line.split(" ")[0]) prediction = classify(user) numUsers += 1.0 if rating != prediction: total += 1.0 print str(rating) + " " + str(prediction) + " " + user return total / numUsers print getError() </code></pre>
[]
[ { "body": "<pre><code>#!/usr/bin/python\n\n# Naive Bayes classifier for OkCupid data. The features are the words in\n# the profile and the classes are HIGH and LOW. This is used to\n# predict the rating I would give a profile.\n\n# TODO: tweak the classifier so it works better.\n\nfrom subprocess import call\nfrom math import sqrt\n\n# File containing training data in the form \"&lt;rating&gt; &lt;username&gt;\"\nTRAINING_DATA = \"train.dta\"\n\n# File containing test set in the form \"&lt;rating&gt; &lt;username&gt;\"\nTEST_DATA = \"test.dta\"\n\n# Dictionary\ndictionary = \"TWL06.txt\"\n</code></pre>\n\n<p>Why is this not in ALL_CAPS like the others?</p>\n\n<pre><code># Hash table containing words in highly-ranked profiles.\nHIGH_WORDS = {}\n\n# Hash table containing words in low-ranked profiles.\nLOW_WORDS = {}\n</code></pre>\n\n<p>These aren't constants, so they shouldn't be global or in ALL_CAPS</p>\n\n<pre><code># Number of users in each category\nhi = 0\nlow = 0\n</code></pre>\n\n<p>Once you actually start logic, its best to do it inside a function except for really simply scripts.</p>\n\n<pre><code># Add training data to the hash tables.\nt = open(TRAINING_DATA, 'r')\n</code></pre>\n\n<p>Don't use single letter variable names, it results in difficult to follow code. Also, you should open a file using the with statement, to make sure it closes in all circumstances.</p>\n\n<pre><code>for user in t:\n rating = int(user.split(\" \")[0])\n name = user.split(\" \")[1]\n</code></pre>\n\n<p>Why are you passing the \" \" to slit instead of trusting the default. This approach is a little wasteful because you split the input twice.</p>\n\n<pre><code> # Count users\n if rating == 1:\n hi += 1\n else:\n low += 1\n\n # Get data for each user\n call([\"curl\", \"-o\", \"tmp.dta\", \"http://www.okcupid.com/profile/\" + name])\n</code></pre>\n\n<p>Use <code>urllib.urlopen</code> to fetch urls. That you can avoid the temporary file.</p>\n\n<pre><code> d = open(\"tmp.dta\", 'r')\n\n # Get word list from user\n words = {}\n for line in d:\n for word in line.split(\" \"):\n if \"/\" in word or \"=\" in word or \"&lt;\" in word or \"&gt;\" in word or \"()\" in word or \"&amp;\" in word or len(word) &gt; 10:\n</code></pre>\n\n<p>Make a list of blocked characters rather then duplicating your logic so much here. And I suspect that \"()\" in word wasn't what you wanted.</p>\n\n<pre><code> continue\n</code></pre>\n\n<p>I try to almost always avoid continue. I suggest rewriting the logic so the following line in the if block.</p>\n\n<pre><code> words[word.rstrip().lower()] = None\n</code></pre>\n\n<p>You seem to be using words as a set. Use a set.</p>\n\n<pre><code> d.close()\n\n # Add words in this word list to our master word lists\n for word in words:\n if rating == 1:\n if word in HIGH_WORDS:\n HIGH_WORDS[word] += 1\n else:\n HIGH_WORDS[word] = 1\n</code></pre>\n\n<p>Look at <code>collections.Counter</code> to simplify this.</p>\n\n<pre><code> else:\n if word in LOW_WORDS:\n LOW_WORDS[word] += 1\n else:\n LOW_WORDS[word] = 1\nt.close()\n\nprint HIGH_WORDS\nprint LOW_WORDS\n\n# Classify a point, assuming training has already happened.\n# P(C | F1 ... Fn) proportionate to P(C) * P(F1 | C) * ... * P(Fn | C)\ndef classify(username):\n # P(C)\n Phi = float(hi) / float(hi + low)\n Plow = float(low) / float(hi + low)\n</code></pre>\n\n<p>Add <code>from __future__ import division</code> so that all division produce floats. Then you don't have to cast to float. I also suggest calling the variable: <code>probaility_high</code> for greater clarity.</p>\n\n<pre><code> ratio = Phi / Plow\n # Get data\n call([\"curl\", \"-o\", \"tmp.dta\", \"http://www.okcupid.com/profile/\" + username])\n d = open(\"tmp.dta\", 'r')\n for line in d:\n for word in line.split(\" \"):\n</code></pre>\n\n<p>There is some duplication here. You should be able to write a function that returns the words from the url.</p>\n\n<pre><code> # Calculate the probability of the feature given a class\n if word in HIGH_WORDS:\n numHi = float(HIGH_WORDS[word])\n else:\n numHi = 1\n if word in LOW_WORDS:\n numLow = float(LOW_WORDS[word])\n else:\n numLow = 1\n\n ratio = ratio * (numHi / float(hi)) / (numLow / float(low))\n# if word in HIGH_WORDS:\n## Phi = Phi * float(HIGH_WORDS[word]) / float(hi)\n## else:\n## Phi = Phi * (1 / float(hi))\n#\n# if word in LOW_WORDS:\n## Plow = Plow * float(LOW_WORDS[word]) / float(low)\n## else:\n## Plow = Plow * (1 / float(low))\n</code></pre>\n\n<p>Don't leave dead code. Delete it.</p>\n\n<pre><code> print ratio\n if ratio &gt; 1:\n return 1\n else:\n return 0\n\n# Compute out of sample error on test set.\ndef getError():\n t = open(TEST_DATA, 'r')\n numUsers = 0.0\n total = 0.0\n for line in t:\n user = line.split(\" \")[1]\n rating = int(line.split(\" \")[0])\n prediction = classify(user)\n numUsers += 1.0\n if rating != prediction:\n total += 1.0\n</code></pre>\n\n<p>Total seems a confusing name, because its only the mismatches.</p>\n\n<pre><code> print str(rating) + \" \" + str(prediction) + \" \" + user\n\n return total / numUsers\n\n\n\nprint getError()\n</code></pre>\n\n<p>You may want to look into numpy. It'll allow much more efficient operations on large amounts of data like this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T14:37:52.140", "Id": "45062", "Score": "0", "body": "Wow you have taught me so much. I did not know about Counter or urlopen or a lot of the other stuff. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T23:41:01.330", "Id": "28667", "ParentId": "28664", "Score": "2" } }, { "body": "<p>Winston Ewert makes some excellent comments. I'd like to add a few.</p>\n\n<hr>\n\n<p>At a high level, it's hard to get a good idea of what's going on your program. Compare these two pieces of code:</p>\n\n<pre><code>import sys\np = 1\nfor n in xrange(sys.argv[1]):\n p *= n + 1\nfor n in xrange(sys.argv[2]):\n p *= (n + 1)\nfor n in xrange(sys.argv[1] - sys.argv[2]):\n p /= (n + 1)\nprint p\n</code></pre>\n\n<p>Can you spot the bug? Maybe. But it's far easier in this next piece of code:</p>\n\n<pre><code>import sys\ndef factorial(n):\n product = 1\n for i in xrange(1, n + 1):\n product *= i\n return product\ndef n_choose_k(n, k):\n return factorial(n) * factorial(k) / factorial(n - k)\nprint n_choose_k(sys.argv[1], sys.argv[2])\n</code></pre>\n\n<p>The main difference is that the second piece of code has well-named functions, and that concepts on the same level of abstraction are grouped, while concepts at a lower level of abstraction are hidden (in functions).</p>\n\n<p>Similarly, it's a bit hard to see what's going on in <code>classify</code> because so many things are going on at once: you're downloading a file, splitting it into words, looking up some things, multiplying some things, etc.</p>\n\n<p>In the end, I suspect the classifier isn't very useful because it's being dominated by (Phi/Plow)^n, where n is the number of words in the profile that aren't in the training set. Try ignoring words that are in 0 (or perhaps &lt;= 1) of your training profiles.</p>\n\n<hr>\n\n<pre><code>rating = int(user.split(\" \")[0])\nname = user.split(\" \")[1]\n</code></pre>\n\n<p>can be rewritten</p>\n\n<pre><code>rating_text, name = user.split()\nrating = int(rating_text)\n</code></pre>\n\n<p>This has an advantage that it will cause an exception to be raised if the input is not in the expected format instead of ignoring lines with more than two fields.</p>\n\n<hr>\n\n<p>If you find yourself counting with a float (e.g. <code>f = 0.0; for w in ws: f += 1.0</code>), you're doing something wrong. Count with an integer, and convert to float later if necessary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T12:24:04.867", "Id": "28696", "ParentId": "28664", "Score": "2" } } ]
{ "AcceptedAnswerId": "28667", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T21:48:10.773", "Id": "28664", "Score": "0", "Tags": [ "python" ], "Title": "Naive Bayes classifier for OKCupid profiles" }
28664
<p>The code below is designed to deal with this situation:</p> <blockquote> <p>There is a <strong>Battle</strong> environment with <strong>Characters</strong>; these Characters obviously have certain characteristics and abilities, and they need to be able to use <strong>Items</strong> from an inventory.</p> </blockquote> <p>I would like as much feedback as possible on the various aspects of the code:</p> <ul> <li><strong>The approach to the problem</strong>: did I make something that was simple, overly complex?</li> <li><strong>The cleanliness/readability of the code</strong>: is the code readable and understandable? Am I following the best practices? (Spaces/Tabs/Operator alignment/Brackets…)</li> <li><strong>Code syntax</strong>: am I <code>return</code>ing correctly? Am I missing some tests that I should do?</li> </ul> <p>On the other hand, I have some very specific questions:</p> <ol> <li>Am I handling closures correctly? My approach has been to try to be as modular as possible, creating one <code>global object</code> to hold all my properties, and creating modules inside *iife*s.</li> <li>I had encountered a problem especially when dealing with <strong>Constructors</strong> inside the closures. Obviously they are not accessible from the outside with the usual syntax, making it impossible for me to create new Objects in different modules. I solved this problem in the <code>Character</code> constructor by actually adding the function to a variable of the <code>Battle</code> global object, as I would do for a <em>method</em>. That, however, <strong>doesn't feel right</strong>.</li> <li>In the <strong>Items module</strong> the goal is to define the various available items in a <em>dictionary</em>-like <code>object</code> or <code>array</code> to later add to the <code>Battle</code> global object. Does this approach make sense? Adding objects to the <code>array</code> the way I do, poses a little problem, though, as the variables lose their name.</li> <li>That brings me to the way I solved this problem (which perhaps is unnecessary in the first place) in the <strong>Character module</strong>. Because I want the syntax of the <code>useItem(item)</code> method to accept <code>item</code> as a <code>string</code> of the name of the item, I go a bit around in loops to find out the corresponding object using the array <code>filter()</code> method. Is this the right way of finding what I am looking for? Would I just be better off by referring to the items as their <code>array index</code> in the <em>dictionary</em>?</li> <li><strong>Redundancy</strong>: in the <code>useItem()</code> method, after checking if the character owns the particular item he's trying to use inside an <code>if</code> statement which <code>returns false</code>, I add an <code>else</code>. Given the fact that the function <strong>returns</strong> if the conditions are met, is it redundand to add an <code>else</code>? I don't know why, but it felt <strong>safer</strong> to add it.</li> <li>As for the way that <strong>Characters</strong> are handled, would I be better off having the characters in a numbered <code>array</code> then having them being handled by their variable names? Especially considering that the <strong>Battle initialisation module</strong> is just an example and, ideally, will extract data from an XML or a JSON.</li> </ol> <p>"Extra" questions:</p> <ul> <li><strong>Documentation</strong>: I am always confused by best practices on how to document code, especially when it is Javascript (at least PHP as some more consolidated best practices).</li> <li><strong>Dev tools</strong>: both Chrome and Firefox behave differently in the way they handle the <em>debugging</em> statements. <ol> <li>For some reason, Chrome doesn't display an integer when it's 0, while Firefox does.</li> <li>On the other hand, Firefox doesn't correctly substitute the strings when encountering things such as <code>%2$s</code> and <code>%ss</code>. Am I using those incorrectly?</li> <li>In <a href="https://developers.google.com/chrome-developer-tools/docs/console#string_substitution_and_formatting" rel="nofollow">this article of the Chrome Dev Tools documentation</a>, they show that, when using string substitution, the variables get colored in blue, which aids readability quite a lot. My dev tools are not working as such, showing it all in black: am I missing something or this has been changed since the documentation has been written? I know that I can style the whole message with <code>%c</code>, but I don't think that's what happens in that article section.</li> </ol></li> </ul> <p><kbd><a href="http://jsbin.com/ikenaq/2/edit" rel="nofollow"><strong>Working code</strong></a></kbd></p> <p><strong>Global JS</strong></p> <pre><code>/* * Initialising the container global object */ var Battle = { itemDefinitions: [], characters: {} }; </code></pre> <p><strong>Item module</strong></p> <pre><code>(function(Battle){ /* * Item constructor * * Defines a new Item object. * * @param string name The name of the item; * @param string result The effect of the item; * @param string augmentedResult The effect of the item if the user's * support is 'experiment' */ function Item(name, result, augmentedResult){ this.name = name; this.result = result; this.augmentedResult = augmentedResult; } // Here come the items var potion = new Item('Potion', '+50 hp', '+100 hp'); var hiPotion = new Item('Hi Potion', '+125 hp', '+150hp'); // Put all the created items in an array for easier iteration var itemDefinitions = [potion, hiPotion]; // Populate the global object with item Definitions itemDefinitions.forEach(function(entry, idx){ Battle.itemDefinitions.push(entry); }); })(Battle); </code></pre> <p><strong>Character module</strong></p> <pre><code>(function(Battle){ /* * Character constructor * * Defines a new Character object. * * @param string name The name of the character; * @method mixed useItem Uses an item from the character's inventory; */ Battle.Character = function Character(name){ this.name = name; }; /* * Uses an item from the character's inventory. * * This method checks if the character has the item available in * his inventory. If he does, it uses the item to the best of the * character's ability. * * @param string item The name of the item to use; * @return mixed Returns false if the item could not be used * otherwise, returns the item's effect; */ Battle.Character.prototype.useItem = function(item) { var itemType, ownedItem, result; // Checks if the requested item has been defined in the // items dictionary itemType = Battle.itemDefinitions.filter(function(obj){ return obj.name === item; }); itemType = itemType.length === 0 ? null : itemType[0]; if( itemType === null ) { console.error('Invalid item type “%s”: item does not exist', item); return false; } // Checks if the user has enough of those items in his // inventory ownedItem = this.inventory.filter(function(obj){ return obj.name === item; }); ownedItem = ownedItem.length === 0 ? null : ownedItem[0]; if( ownedItem === null || ownedItem.quantity &lt;= 0 ) { console.error('Cannot complete action: not enough %ss', item); return false; } else { // Defines the item's effect according to the user's // actual ability if ( this.support === 'experiment' ) result = itemType.augmentedResult; else result = itemType.result; // Removes one of the said item from the user's inventory // and logs the result. ownedItem.quantity--; console.log('%s used %s: %s; \n%d %2$s remaining.', this.name, item, result, ownedItem.quantity); } }; })(Battle); </code></pre> <p><strong>Battle initialisation module</strong></p> <pre><code>/* * Battle initialisation * * This would ideally get data from an external source. */ (function(Battle){ var carl = new Battle.Character('Carl'); carl.inventory = [ { name: 'Potion', quantity: 2 }, { name: 'Eyedrop', quantity: 1 }]; carl.support = 'experiment'; var jerry = new Battle.Character('Jerry'); jerry.inventory = [ { name: 'Hi Potion', quantity: 1 } ]; Battle.characters.carl = carl; Battle.characters.jerry = jerry; })(Battle); </code></pre> <p><strong>Battle execution</strong></p> <pre><code>/* * Battle execution * * Just a quick example of what happens when * the defined functions are run. */ Battle.characters.carl.useItem('Potion'); Battle.characters.carl.useItem('Potion'); Battle.characters.carl.useItem('Potion'); Battle.characters.jerry.useItem('Hi Potion'); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T23:07:10.053", "Id": "45016", "Score": "2", "body": "I would structure `Battle` as more of a namespace, right now you have it as a catch-all. I don't have much time to go into more detail now, but I'll try to find some time in the near future." } ]
[ { "body": "<p>As Shmiddty said, you want your <code>Battle</code> object to be more of a namespace providing access to the modules:</p>\n\n<pre><code>var Battle = function () {}\n\nBattle.Character = (function (/* dependencies */) {\n\n // constructor\n var Character = function (name) {\n this.name = name;\n };\n\n // instance method\n Character.prototype.useItem = function () {\n [...]\n };\n\n // private method\n var soSomething = function () {\n [...]\n };\n\n return Character;\n\n}(/* dependencies */));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T23:16:44.160", "Id": "41016", "ParentId": "28666", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T22:46:42.253", "Id": "28666", "Score": "3", "Tags": [ "javascript", "modules", "closure" ], "Title": "Correctly dealing with closures and modularity in Javascript" }
28666
<p>I have inside a Backbone model <code>validate</code> function several <code>if</code> statements:</p> <pre><code>if(!attrs.firstAttr) errorMsg+="first attr mandatory"; if(!attrs.secondAttr) errorMsg+="second attr mandatory"; </code></pre> <p>as you can see there is a lot of repetition (I have actually 10 fields to check with this. </p> <p>I was thinking of introducing an <em>interface</em> <code>Validator</code> with a method <code>validate</code>. Then implement a <code>MandatoryFieldValidator</code> with:</p> <pre><code>validate: function(attr, errors) { if(!attr) errors.push(attr + " mandatory"); } </code></pre> <p>So the validate method would become like this:</p> <pre><code>mandatoryFieldValidator.validate(attr.firstAttr, errors); // errors now is an array mandatoryFieldValidator.validate(attr.secondAttr, errors); </code></pre> <p>Would you think is a good solution? I still don't like it because I need to rewrite it a lot of times. Next step would be to have some kind of <code>foreach</code> but I don't have a list of parameters. The attributes passed by the Backbone validate is an object with the properties of the model.</p> <p>Would it be ok to declare an array with every element I want to validate like <code>[attr.firstAttr, attr.secondAttr]</code>? </p> <p>If yes, how would it be possible to do it in Backbone? I'm referring to the fact that <a href="http://underscorejs.org/#each" rel="nofollow"><code>_.each</code></a> function from underscore.js just passes an array with a callback function and I still need to pass the <em>error</em> array and apply the <code>validate</code> method of my <code>Validator</code>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T14:33:33.997", "Id": "45061", "Score": "0", "body": "Have you tried to use Backbone.Validation plugin? It helps a lot! https://github.com/thedersen/backbone.validation" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T17:02:47.477", "Id": "45082", "Score": "0", "body": "@Juliano I know that plugin but my problem is that part of the validation needs to happen only when certain conditions are met. If I recall correctly, with Backbone.Validation you can't do that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-28T13:28:27.880", "Id": "84940", "Score": "0", "body": "I know this is an old post, but in general, providing us the real code with the 10 fields helps us finding a better answer ;)" } ]
[ { "body": "<p>I would approach that like this:</p>\n\n<p>Have an array with all the fields you</p>\n\n<pre><code>var mandatoryFields = ['firstAttr','secondAttr'];\n</code></pre>\n\n<p>Then have a validate function that takes <code>attrs</code>, <code>mandatoryFields</code> and <code>errors</code></p>\n\n<pre><code>function validate( o , mandatoryFields, errors )\n{\n for( var i = 0 , i &lt; mandatoryFields.length ; i++ )\n {\n var field = mandatoryFields[i];\n if(!o[field]) \n errors.push(field + \" mandatory\");\n }\n}\n</code></pre>\n\n<p>Note that I replaced <code>attrs</code> with <code>fields</code> but fare more readable, I also added a new-line after that <code>if</code> statement for readability.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-28T13:28:02.797", "Id": "48397", "ParentId": "28670", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T01:24:22.450", "Id": "28670", "Score": "2", "Tags": [ "javascript", "beginner", "validation", "backbone.js", "underscore.js" ], "Title": "Validator function in Backbone" }
28670
<p>I'd like to know how this program can be improved. Any comments or critiques are most welcome.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;time.h&gt; #include &lt;errno.h&gt; #define MAX 10000 #define FOUND 1 #define NOT_FOUND 0 #define DEAD 0 #define LINUX void starMaker(char string[] , char starContainer[]); /*creats a string of stars */ int wordCalculator();/*calculates how many words there is in the dictionary file*/ int queryFinder(char letter , char string[] , char starWord[]);/*checks if the character entered is in the mystery word*/ int starFinder(char starWord[]);/*checks if there is anymore stars in the star string if there isn't any it means the player has won*/ void nRemover(char string[]);/*removes the \n */ void score(char name[] , int score);/*organizes the scores and writes them into the score file*/ void showScores();/*shows the scores at the end of the game*/ main(void) { /*---------------------------------DECLARATION OF VARIABLES---------------------------------*/ FILE* wordDic = NULL; char entered_char; char starWord[MAX] = ""; char winPath[20] = ".\\wordDIC"; char mysteryWord[MAX] = ""; char ans = 0; char name[MAX] = ""; int i = 0; int ran = 0; /*ran holds a random number that represents the number of lines*/ int lifes = 10;/*initial number of lifes ... the numbers of shots to go*/ int check = 0; /*checks if there is any more stars*/ int Max = 0; /*max lines*/ long scor = 0; const int Min = 0; time_t secA = 0 , secB = 0; /*------------------------------------------------------------------------------------------*/ do { #ifdef LINUX /*linux version*/ wordDic = fopen("wordDIC" , "r"); if(wordDic == NULL) { perror("wordDIC"); return -1; } #endif #ifdef WINDOWS /*windows version*/ wordDic = fopen(winPath , "r"); if(wordDic == NULL) { perror("wordDIC"); return -1; } #endif /*----------INITIALIZING----------------------------------*/ scor = 0; lifes = 10; Max = wordCalculator(); srand(time(NULL)); ran = (rand() % (Max - Min + 1)) + Min; /*-------------------------------------------------------*/ for(i = 0 ; i &lt; ran ; i++) { fgets(mysteryWord , sizeof(mysteryWord) , wordDic); nRemover(mysteryWord); } /*now mystery word has the random word*/ starMaker(mysteryWord , starWord); printf("Enter your name : ");/*entering the pseodo*/ fgets(name , sizeof(name) , stdin); nRemover(name); time(&amp;secA);/*start counting seconds*/ while(lifes &gt; 0 &amp;&amp; (check = starFinder(starWord)) == FOUND) { printf("Word : %s\n" , starWord); printf("Enter a character (%d shots left) : \n" , lifes); entered_char = getchar(); getchar(); entered_char = toupper(entered_char); if(!queryFinder(entered_char , mysteryWord , starWord)) lifes--; system("clear"); } time(&amp;secB);/*stop counting*/ scor = secB - secA; /*calculating the score*/ if(lifes == DEAD) printf("YOU HAVE LOST \n"); else { printf("CONGRATS YOU HAVE WON , THE WORD IS INDEED %s , YOU FOUND THE WORD in %ld SECONDS\n" , mysteryWord , scor); score(name , scor); } printf("Would you like to play another game ? y/n : "); ans = getchar(); getchar(); fclose(wordDic); } while(ans == 'y' || ans == 'Y'); printf("would you like to see the scores ? y/n : "); ans = getchar(); getchar(); if(ans == 'y' || ans == 'Y') showScores(); } void starMaker(char string[] , char starContainer[]) { int i; int lenght = strlen(string); for(i = 0 ; i &lt; lenght ; i++) starContainer[i] = '*'; starContainer[i] = '\0'; } int wordCalculator() { FILE* wordDic = NULL; char buff[1000]; int i = 0; wordDic = fopen("wordDIC" , "r"); if(wordDic == NULL) { perror("wordDIC"); return -2; } while(fgets(buff , sizeof(buff) , wordDic) != NULL) i++; fclose(wordDic); return i; } int queryFinder(char letter , char string[] , char starWord[]) { int i; int lenght = strlen(string); if(!strchr(string , letter)) return NOT_FOUND; else for(i = 0 ; i &lt; lenght ; i++) { if(string[i] == letter) starWord[i] = toupper(letter); } } int starFinder(char starWord[]) { if(!strchr(starWord , '*')) return NOT_FOUND; else return FOUND; } void nRemover(char string[]) { int i = 0; int lenght = strlen(string); for(i = lenght ; i &gt; 0 ; i--) if(string[i] == '\n') string[i] = '\0'; } void score(char name [] , int score) { FILE* fscore = NULL; fscore = fopen("score" , "a+"); if(fscore == NULL) { perror("score"); exit(-10); } fprintf(fscore , "%25s **** %3d seconds\n" , name , score); fclose(fscore); } void showScores() { char scoreLine[MAX] = ""; FILE* scoreFile = NULL; scoreFile = fopen("score" , "r"); if(scoreFile == NULL) { perror("score"); exit(-4); } while(fgets(scoreLine , sizeof(scoreLine) , scoreFile) != NULL) { printf("%s" , scoreLine); } fclose(scoreFile); } </code></pre>
[]
[ { "body": "<p>Don't use macros to conditionally change code.<br>\nUse the macros to define appropriate macros that can be used in code:</p>\n\n<pre><code>#ifdef LINUX /*linux version*/\n wordDic = fopen(\"wordDIC\" , \"r\");\n if(wordDic == NULL)\n {\n perror(\"wordDIC\");\n return -1;\n }\n#endif\n#ifdef WINDOWS /*windows version*/\n wordDic = fopen(winPath , \"r\");\n if(wordDic == NULL)\n {\n perror(\"wordDIC\");\n return -1;\n }\n\n#endif\n</code></pre>\n\n<p>This should be re-written as:</p>\n\n<pre><code> wordDic = fopen(WORD_DICTIONARY , \"r\");\n if(wordDic == NULL)\n {\n perror(\"wordDIC\");\n return -1;\n }\n</code></pre>\n\n<p>Then in the header you can define:</p>\n\n<pre><code>#if defined(LINUX)\n#define WORD_DICTIONARY \"wordDIC\"\n#elif definded(WINDOWS)\n#define WORD_DICTIONARY \".\\\\wordDIC\"\n#else\n#error \"Unsupported platform\"\n#endif\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T03:55:35.823", "Id": "45019", "Score": "0", "body": "thank you for your quick and very helpful answer I'll make sure to apply that in my future projects" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T03:23:40.180", "Id": "28673", "ParentId": "28671", "Score": "5" } }, { "body": "<ul>\n<li><p>You could eliminate the function prototypes by defining <code>main()</code> lastly, cutting down on some code. In this way, <code>main()</code> will already be aware of the other functions in the same way with prototypes.</p></li>\n<li><p>Keeping a \"list of variables\" could make maintenance more difficult as it won't be easy to, for instance, tell if a variable is still in use. In order to avoid this, declare or initialize variables as close to their use as possible. This is especially problematic in <code>main()</code>.</p></li>\n<li><p>This function:</p>\n\n<pre><code>int starFinder(char starWord[])\n{\n if(!strchr(starWord , '*'))\n return NOT_FOUND;\n else\n return FOUND;\n}\n</code></pre>\n\n<p>can just have a one-line <a href=\"http://en.wikipedia.org/wiki/%3F%3a#C\" rel=\"nofollow\">ternary statement</a>:</p>\n\n<pre><code>int starFinder(char starWord[])\n{\n return (!strchr(starWord , '*')) ? NOT_FOUND : FOUND;\n}\n</code></pre>\n\n<p>In addition, consider swapping the conditionals, which may sound more logical as the function <em>is</em> first trying to find something. If you make this change, you may also have to adjust the calling code.</p>\n\n<pre><code>int starFinder(char starWord[])\n{\n return (strchr(starWord , '*')) ? FOUND : NOT_FOUND;\n}\n</code></pre></li>\n</ul>\n\n<p>Overall, this code isn't quite easy to follow. Some of the function names aren't too clear and it looks like more code can be still shortened or removed. Apart from the aforementioned advice, it could help to remove some unneeded comments, such as the \"initializing block\" in <code>main()</code>.</p>\n\n<p>Regarding the \"initialization block\" thing, there may be a code organization problem if you have to isolate a block of code with comments like that. If you're writing too much code in one function, then it <em>may</em> mean that it's doing too much or it's doing something that can be done in another function. In the case of <code>main()</code>, it should (ideally) do as little as possible, primarily calling other functions to do the real work.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T23:11:45.383", "Id": "47620", "ParentId": "28671", "Score": "5" } } ]
{ "AcceptedAnswerId": "28673", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T02:23:39.770", "Id": "28671", "Score": "6", "Tags": [ "beginner", "c", "game", "hangman" ], "Title": "Improving Hangman game" }
28671
<p>I am trying to build a simple C#/.Net console application that runs three iterations (see code below). The process runs as intended, but because of how many iterations there are, it can run upwards of 15 to 20 minutes. I intend to run through a list of nodes that would require individual simulations. Therefore requiring iterations for each node. Maybe 50 nodes.</p> <p>I am wondering if there is a better method to run these iterations. I have just started reviewing Parallel.For() functions, but have not tested. And I have not seen many examples of chained Parallel.For() functions. </p> <p>I am thinking the code below requires better iteration coding and a bit of multi-threading to really see an improvement in speed. Any suggestions? Is there anything glaring that looks wrong? </p> <p>Here is the code:</p> <pre><code>static void Sim() { OE oe = new OE(); // node-path functionality string ftC = "x"; // first call double fC = 4; // fourth call double tTime = 252; // days remaining double calendar = 365; // full calendar days double rate = .0065; /// interest rate double sC = 1; // secondary call double tC = 3.897; // third call string path = @"c:\temp\output.csv"; // export //tC settings double i; double nIncrement = .05; double nMin = 2; double nMax = 5; // sC settings double vi; double nvIncrement = .005; double nvMin = .10; double nvMax = .50; // time settings double ti; double ntIncrement = 5; double ntMin = 1; double ntMax = tTime + 4; //double ntMax = 30; // begin basic increments // where I think I can find improvement in code for (i = (tC - nMin); i &lt; nMax + (tC + nIncrement); i += nIncrement) // tC loop { double nP = Math.Round(i, 2); for (vi = (sC - nvMin); vi &lt; (sC + nvMax) + nvIncrement; vi += nvIncrement) // sCatility loop { double nV = Math.Round(vi, 4); for (ti = ntMin; ti &lt;= ntMax; ti += ntIncrement) // time loop { double nT = ti; double variableResult = Math.Round(oe.Solver(ftC, fC, nP, nV, nT, calendar, rate, 4), 5); // output code here } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T03:35:25.707", "Id": "45018", "Score": "1", "body": "So the first thing that comes to mind is that you could make a queue of numbers that you would plug into a oe.Solver. have a few threads (maybe about 4) work on them in parallel. When one solves the problem it fires an event that it is finished. That would put that thread back in line to get another set of numbers to calculate. Continue until you finish calculating." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T09:33:36.607", "Id": "45025", "Score": "0", "body": "@RobertSnyder Wouldn't it be simpler to just use `Parallel.For()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T09:34:10.547", "Id": "45026", "Score": "0", "body": "It looks like the slow part of your code is the call to `oe.Solver()`. Can't you optimize that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T11:04:25.697", "Id": "45033", "Score": "0", "body": "You should not need _chained_ `Parallel.For`. You can parallelize the outermost loop only, for instance. [See the example here](http://msdn.microsoft.com/en-us/library/dd460713.aspx)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T11:06:04.563", "Id": "45035", "Score": "0", "body": "@svick - It is a vendor developed dll. Im not sure how much it can be optimized from my side." } ]
[ { "body": "<p>If <code>oe.Solver()</code> is your slowdown, you're not going to be able to get a huge improvement, but you can get some by parallelizing all the calls to it. </p>\n\n<p>Replace your loops with this version:</p>\n\n<pre><code>List&lt;double[]&gt; data = new List&lt;double[]&gt;();\nfor (i = (tC - nMin); i &lt; nMax + (tC + nIncrement); i += nIncrement) // tC loop\n{\n double nP = Math.Round(i, 2); \n\n for (vi = (sC - nvMin); vi &lt; (sC + nvMax) + nvIncrement; vi += nvIncrement) // sCatility loop\n {\n double nV = Math.Round(vi, 4);\n\n for (ti = ntMin; ti &lt;= ntMax; ti += ntIncrement) // time loop\n {\n double nT = ti;\n\n //double variableResult = Math.Round(oe.Solver(ftC, fC, nP, nV, nT, calendar, rate, 4), 5);\n data.Add(new[] { fC, nP, nV, nT, calendar, rate});\n\n }\n }\n\n}\nParallel.ForEach(data, x =&gt; { \n var output = oe.Solver(fC, x[0], x[1], x[2], x[3], x[4], x[5], 4);\n // Round and display output\n});\n</code></pre>\n\n<p>This will kick off a new solver run each time the prior one displays, up to the limits of what your computer can handle.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T02:53:09.000", "Id": "45137", "Score": "1", "body": "Using `Parallel` for `OE`'s instance requires `OE`' thread-safe implementation, which is not guaranteed here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T13:46:22.233", "Id": "45322", "Score": "0", "body": "@tia - A valid point, but if it's not thread safe then the whole question is moot. Also, given the inputs and the fact it's called `Solver`, I'm making the (unsupported) assumption that it's stateless." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T20:02:30.793", "Id": "28732", "ParentId": "28672", "Score": "0" } }, { "body": "<p>Since this is code review, I would like to point out that your variable naming scheme makes your code hard to read. Why abbreviate anything? Why not call <code>fC</code> as just <code>fourthCall?</code> etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-25T06:07:52.887", "Id": "28958", "ParentId": "28672", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T02:40:27.400", "Id": "28672", "Score": "3", "Tags": [ "c#", "performance", ".net" ], "Title": "Faster Iteration Functions" }
28672
<p>Suppose I need to process a list of list of list of many objects, where the data usually comes from third party APIs.</p> <p>For the sake of an example, lets assume we have many users, and for each user we get many days of data, and for each day you get many events. We want to process all of these objects and store in our database</p> <p>I thought about some differents design patterns I could use, but I'm not sure what is considered to be the best approach, if any.</p> <p>These are my thoughts:</p> <p>1) Nested iterations and do the side-effect (save to database) at the lowest-level loop.</p> <pre><code>for user in users: for day in user.days: for event in day.event: processed_object = process_event(event) save_to_db(processed_object) </code></pre> <p>2) Similar to one, except that each nested iteration is 'hidden' in another method.</p> <pre><code>for user in users: process_user(user) def process_user(user): for day in user.days: process_day(day) def process_day(day): for event in day.events: process_event(event) def process_event(event): save_to_db(event) </code></pre> <p>3) Return everything from deep in the nest and then do the side-effects afterwards.</p> <pre><code>def process_users(users): processed = [] for user in users: processed.append(process_user(user)) return processed def process_user(user): processed = [] for day in user.days: processed.append(process_day(day)) return processed def process_day(day): processed = [] for event in day.events: processed.append(process_event) return processed processed_events = process_users(users) for event in processed_events: save_to_db(event) </code></pre> <p>Is there a general, agreed on approach for these type of programs, where side-effects are involved?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T15:54:07.330", "Id": "45166", "Score": "0", "body": "Your third example could be rewritten using generators, avoiding the creation of temporary lists. Also using `itertools.chain.from_iterable` could be useful to flatten the iterations." } ]
[ { "body": "<p>Your third approach is the most pythonic, in the sense that you create a function for each specific purpose, avoiding repetition and giving the user more options (process the users, only the days, etc...) and the option to save or not to save the processed data to the database.</p>\n\n<p><strong>It is also the fastest</strong>. If you benchmark it, that kind of approach (separating things into functions) will almost always be the faster one with Python.</p>\n\n<p>Using your first approach it took roughly 0.00027 seconds to process a list of 100 events for each day, having two days for each user and two users.</p>\n\n<p>Using the second approach it takes roughly 0.00018 seconds.</p>\n\n<p>Using the third approach it takes roughly 0.00012 seconds.</p>\n\n<p>Here are all the approaches and their output:\n<a href=\"http://pastebin.com/vU12HaQW\" rel=\"nofollow\">http://pastebin.com/vU12HaQW</a></p>\n\n<p>Notice your third approach yields a list of list of lists, whereas the first and the second return a list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T11:49:34.520", "Id": "45042", "Score": "0", "body": "How did you populate the events list?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T12:03:03.570", "Id": "45045", "Score": "0", "body": "@AseemBansal It's a list of random numbers: `for x in xrange(0,100): myList.append(random())`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T18:23:13.767", "Id": "45183", "Score": "0", "body": "Using `time` for doing benchmarking won't do any good. That module isn't meant for that. You need to use `timeit` module for benchmarking. See [this](http://stackoverflow.com/questions/17764098/limit-of-performance-benefit-gained-in-python-from-using-local-variables-instead) for how breaking functions indefinitely doesn't give performance upgrade." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T02:46:50.790", "Id": "45286", "Score": "0", "body": "@AseemBansal `timeit` [uses `time.time()` repeatedly](http://hg.python.org/cpython/file/2.7/Lib/timeit.py), which is basically what I did." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T03:59:10.443", "Id": "45288", "Score": "0", "body": "You called it once on each of the tasks. Having a nested `for` loop between two calls to measure the starting and ending doesn't make those repeated calls. I have used that method and it gives incorrect results compared to this approach." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T11:34:17.877", "Id": "28688", "ParentId": "28674", "Score": "1" } }, { "body": "<p>Not sure what is \"generally agreed upon\", if anything, but in my opinion the first variant is by far the easiest to read and understand, let alone most compact.</p>\n\n<p>As @Alex points out, the second and third variant give more flexibility, e.g., you can process the events of just a single user, or a single day, but judging from your question this seems not to be necessary.</p>\n\n<p>Another variant would be: First collect the events in a list, then process them in a separate loop, i.e., a mixture of variant 1 and 3:</p>\n\n<pre><code>all_events = []\nfor user in users:\n for day in user.days:\n all_events.extend(day.event)\n\nfor event in all_events:\n processed_object = process_event(event)\n save_to_db(processed_object)\n</code></pre>\n\n<p>You could also use a list comprehension for the first part...</p>\n\n<pre><code>all_events = [event for user in users for day in user.days for event in day.event]\n</code></pre>\n\n<p>...or even for the whole thing (although I don't think this is very readable).</p>\n\n<pre><code>[save_to_db(process_event(event)) for user in ... ]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T11:55:34.347", "Id": "28691", "ParentId": "28674", "Score": "1" } } ]
{ "AcceptedAnswerId": "28691", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T04:20:59.267", "Id": "28674", "Score": "1", "Tags": [ "python", "design-patterns" ], "Title": "Deep iterations with side effects" }
28674
<p>So, this is a thing. I've got a simple little 2D game where a character can run left and right and jump. My problem here is that I've got two velocities, xVel and yVel, that I need to increment as the character runs in a certain direction, and stop altogether as the player stops moving altogether. Right now, I'm only focusing on xVel. So we have the player class, which contains the movement methods. I've got two booleans to determine when to increment the velocities, goingRight and goingLeft. When going left, goingRight is false and goingLeft is true, and vice versa. The only problem is that when the player doesn't move, he shouldn't have any velocity. But there isn't a way to determine when the player isn't moving.</p> <p>Now, the above is my setup for velocities and such so that the player can run into a jump and move in the air. I'm getting confused just trying to think about it, and overall, it just feels disorganized. Am I doing this right, and if so, what can I do to improve it? If not, what would be the best approach for adjusting these velocities and making player movement more smooth. I'll post both classes for the game below so that you can analyze what I'm doing wrong. I don't necessarily need code corrected, but I would like a solid understanding and explanation of what I can do to improve the continuity of the game's movement.</p> <p>Main class: </p> <pre><code>import com.hasherr.platformer.entity.Player; import org.lwjgl.LWJGLException; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import static org.lwjgl.opengl.GL11.*; public class Main { private void display() { try { Display.setDisplayMode(new DisplayMode(1000, 550)); Display.setTitle("Unnamed Platformer Game"); Display.create(); } catch (LWJGLException e) { e.printStackTrace(); System.exit(0); } // OpenGL while (!Display.isCloseRequested()) { Display.update(); Display.sync(60); // sync to 60 fps initGL(); player.update(); handleKeyboardInput(); } Display.destroy(); } private void handleKeyboardInput() { if (!player.goingLeft &amp;&amp; !player.goingRight) { player.xVel = 0; } if (Keyboard.isKeyDown(Keyboard.KEY_D)) { player.moveRight(); } else if (Keyboard.isKeyDown(Keyboard.KEY_A)) { player.moveLeft(); } else if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) { player.jump(); } } private void initGL() { // initial OpenGL items for 2D rendering glClear(GL_COLOR_BUFFER_BIT); glEnable(GL_TEXTURE_2D); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glOrtho(0 , 1000, 0, 550, 1, -1); // start rendering player image player.grabTexture().bind(); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(player.xPos, player.yPos); glTexCoord2f(1, 0); glVertex2f(player.xPos + 150, player.yPos); glTexCoord2f(1, 1); glVertex2f(player.xPos + 150, player.yPos + 150); glTexCoord2f(0, 1); glVertex2f(player.xPos, player.yPos + 150); glEnd(); // stop rendering this image } Player player = new Player(); public static void main(String[] args) { Main main = new Main(); main.display(); } } </code></pre> <p>Player class: </p> <pre><code>import java.io.IOException; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.TextureLoader; import org.newdawn.slick.util.ResourceLoader; public class Player { public Texture playerTexture; // Positions &amp; speed public float xPos = 20.0f; // This is initial public float yPos = 0.0f; // Same as above. public float xVel, yVel; public static int gravityForce = 6; public static int jumpVelocity = 100; private static int moveSpeed = 15; public boolean isSupported = true; // Once again, initial value. public boolean goingRight, goingLeft; // movement methods public void update() { applyGravity(); checkForSupport(); } private void checkForSupport() { if (yPos == 0) { isSupported = true; } else if (yPos &gt; 0 /* and is not on a platform */) { isSupported = false; } } public Texture grabTexture() { try { playerTexture = TextureLoader.getTexture("PNG", ResourceLoader .getResourceAsStream("resources/test_char.png")); } catch (IOException e) { e.printStackTrace(); } return playerTexture; } private void applyGravity() { if (!isSupported) { yPos -= gravityForce; if (yPos &lt; 0) { yPos = 0; } } } private void printPos(String moveMethod) { System.out.println(moveMethod + " X: " + xPos + " Y: " + yPos + " Left: " + goingLeft + " Right: " + goingRight); } // movement methods public void moveRight() { xPos += moveSpeed; goingRight = true; goingLeft = false; printPos("Moving right!"); } public void moveLeft() { xPos -= moveSpeed; goingRight = false; goingLeft = true; printPos("Moving left!"); } public void jump() { if (isSupported) { yPos += jumpVelocity; } } public void shoot() { // do shooty stuff here } } </code></pre>
[]
[ { "body": "<p>The movement of your character is going to feel a bit unnatural in this setup. When you hit the left key, the character will immediately start moving left at full speed; as soon as you stop hitting the key, the character will stop dead. I suggest modeling the character's velocity as well as its position, so that e.g. while holding on the left key, the character's velocity decreases steadily until it reaches a minimum. Likewise, modeling gravity as a constant velocity instead of an acceleration will lead to unnatural looking jumps.</p>\n\n<p>As for the goingLeft and goingRight bools, they seem like an awkward way to manage state, and it will require great care as your control scheme becomes more complex to maintain a consistent state. If you need to maintain this information beyond (or instead of) the velocity I suggest, consider an enum with the values XMOTION_LEFT, XMOTION_STOPPED, XMOTION_RIGHT, or similarly descriptive names.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T11:00:57.367", "Id": "28686", "ParentId": "28675", "Score": "1" } } ]
{ "AcceptedAnswerId": "28686", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T04:27:36.897", "Id": "28675", "Score": "0", "Tags": [ "java", "opengl", "physics" ], "Title": "Issue regarding game velocity" }
28675
<p>This is a method which creates an array of all possible consecutive substrings from a string:</p> <pre><code>def get_seperated_tokens(query) result = [] length = query.split.count tokens = query.downcase.strip.split(' ') length.times do |i| length.times do |j| result &lt;&lt; tokens[i..j].join(' ') if j &gt;= i end end result end </code></pre> <p>To get a better idea I have added rspec for it:</p> <pre><code>describe "#get_seperated_tokens" do it "returns an array of seperated tokens" do query = 'ruby is awesome' result = ['ruby','is', 'awesome', 'ruby is', 'is awesome','ruby is awesome'] expect(get_seperated_tokens(query)).to include(*result) end it "returns an array of seperated tokens" do query = 'red blue iphones' result = ['red','blue', 'iphones', 'red blue', 'blue iphones','red blue iphones'] expect(get_seperated_tokens(query)).to include(*result) end end </code></pre> <p>How can this be made more idiomatic?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T11:08:32.793", "Id": "45037", "Score": "0", "body": "http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-combination" } ]
[ { "body": "<p>Are you familiar with <a href=\"https://en.wikipedia.org/wiki/Functional_programming\" rel=\"nofollow\">functional programming</a>? (my page on the subject: <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">FP with Ruby</a>). Your code feels clunky because, well, imperative programming is clunky (recommended reading: <a href=\"http://www.stanford.edu/class/cs242/readings/backus.pdf%E2%80%8E\" rel=\"nofollow\">Can Programming Be Liberated From The Von Neumann Style?</a>).</p>\n\n<p>You just need to re-write the code without <code>times</code> (as it's being used as an <code>each</code>), mutable variables (<code>result = []</code>), inplace operations (<code>&lt;&lt;</code>) and inline conditionals with side-effects (<code>do_something if j &gt;= i</code>). I'd write:</p>\n\n<pre><code>def get_separated_tokens(query)\n tokens = query.split\n (0...tokens.size).flat_map do |istart|\n (istart...tokens.size).map do |iend|\n tokens[istart..iend].join(\" \")\n end\n end\nend\n\np get_separated_tokens(\"ruby is awesome\")\n#[\"ruby\", \"ruby is\", \"ruby is awesome\", \"is\", \"is awesome\", \"awesome\"]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T10:51:12.030", "Id": "45309", "Score": "0", "body": "You can select Nakilon's answer, I calculated the combinations to build ranges, we have Array#combination." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T11:35:31.037", "Id": "28689", "ParentId": "28679", "Score": "1" } }, { "body": "<p>As @Michael Szyndel mentioned in a comment, <code>Array#combination</code> is the more appropriate method to use.</p>\n\n<pre><code>def get_separated_tokens query\n tokens = query.split\n (0..tokens.size).to_a.combination(2).map{ |i,j| tokens[i...j].join \" \" }\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T09:17:13.430", "Id": "45241", "Score": "0", "body": "In fact Michael wrote an answer with `combination` (now deleted), the problem is that OP needs *contiguous* combinations, so this won't do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T10:29:37.057", "Id": "45305", "Score": "0", "body": "@tokland, I don't get you. Did you run this code? It produces the same as OP's code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T10:34:42.143", "Id": "45306", "Score": "0", "body": "oh, you're right, you use combinations, but with a slice later, which is right. +1" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T20:19:14.330", "Id": "28757", "ParentId": "28679", "Score": "2" } } ]
{ "AcceptedAnswerId": "28757", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T08:21:22.423", "Id": "28679", "Score": "4", "Tags": [ "strings", "ruby" ], "Title": "Creating consecutive words from a string" }
28679
<p>Following on from a question about <a href="https://codereview.stackexchange.com/questions/582/handling-com-exceptions-busy-codes">handling-com-exceptions-busy-codes</a> I would like to know if the following model is the accepted best practice of handling Excel COM busy messages when accessing the Excel COM object model:</p> <pre><code>private void AskExcelToDoSomething() { bool retry = true; do { try { // Call Excel OM retry = false; } catch (COMException e) {} } while (retry); } </code></pre> <p>Assuming that IMessageFilter has been implemented and catches the errors for which it is intended and retries, is the above model the 'accepted' way of handling these busy exceptions? If so, is it not vulnerable to hanging if for some reason it keeps being rejected? Is there no better way of doing this that guarantees success?</p>
[]
[ { "body": "<p>You're missing the <code>Thread.Sleep(500);</code> call from the linked post's solution, which is much, much better than what you've posted here:</p>\n\n<pre><code>private void TryUntilSuccess(Action action)\n{\n bool success = false;\n while (!success)\n {\n try\n {\n action();\n success = true;\n }\n\n catch (System.Runtime.InteropServices.COMException e)\n {\n if ((e.ErrorCode &amp; 0xFFFF) == 0xC472)\n { // Excel is busy\n Thread.Sleep(500); // Wait, and...\n success = false; // ...try again\n }\n else\n { // Re-throw!\n throw e;\n }\n }\n }\n}\n</code></pre>\n\n<p><sub>(above code from sepp2k's answer <a href=\"https://codereview.stackexchange.com/a/583/23788\">here</a>)</sub></p>\n\n<blockquote>\n <p>is it not vulnerable to hanging if for some reason it keeps being rejected?</p>\n</blockquote>\n\n<p>Given that this code is meant to address a COM exception thrown when <em>Excel is busy</em>, it remaining in the loop would mean, well, that <em>Excel is still busy</em> - and possibly hung... in which case, the user will probably lose their patience and kill the application anyway.</p>\n\n<p>The difference between <a href=\"https://codereview.stackexchange.com/a/583/23788\">sepp2k's code</a> and the code you're having here, is that you're <strong>swallowing all COM exceptions</strong> - which is bad. I really don't see a reason not to use the code provided in the post you're following-up on, which filters the error code (<code>if ((e.ErrorCode &amp; 0xFFFF) == 0xC472)</code>) and re-throws all other exceptions, leaving you with a way to exit the loop if you get a COM exception that's saying anything other than <em>Excel is busy</em>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T02:57:47.870", "Id": "35469", "ParentId": "28680", "Score": "2" } } ]
{ "AcceptedAnswerId": "35469", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T08:49:19.300", "Id": "28680", "Score": "4", "Tags": [ "c#", "exception-handling", "excel", "com" ], "Title": "Is brute force the accepted best practice for handling Excel COM 'busy' exceptions?" }
28680
<p>I'm making my own <em>script editor</em> (in this case for <code>Arma: Cold War Assault</code>) because I want to learn and this is challenging enough. </p> <p>Let me just get this out of the way: <strong><em>please don't tell me that I should do easier things. I want to do this anyway</em></strong>.</p> <p>So, basically I have the simple GUI for now with a working new/open/save file menu. </p> <p>I've managed to highlight certain words with different colors (because I want to tackle the hardest part first) but it's <strong>not efficient</strong>. </p> <p>I've come up with several ideas for the algorithm (didn't implement them all), but I want to know what you'do, if there's a certain way and what I am doing wrong.</p> <p>This all happens inside a <code>JTextPane</code> class.</p> <hr> <p>The arrays containing the reserved words:</p> <pre><code>Collections.addAll(keywords, "private", "public", "if", "not", "then", "else", "else if"); Collections.addAll(operators, "+", "-", "=", "==", "?", "!","(", ")","{", "}", "_", "-", "^", "&lt;", "&gt;"); ArrayList&lt;String&gt; keywords = new ArrayList&lt;String&gt;(); ArrayList&lt;String&gt; operators = new ArrayList&lt;String&gt;(); </code></pre> <hr> <p>Everytime the user makes an update to the document, it get's updated:</p> <pre><code>@Override public void insertUpdate(DocumentEvent e) { update(); } @Override public void removeUpdate(DocumentEvent e) { update(); } </code></pre> <hr> <p>When the user stops typing, it waits 500 ms to update the screen: </p> <pre><code>Timer t; /** * Updates the text when user stops typing */ public void update(){ if (t != null) { if (t.isRunning()) t.stop(); } t = new Timer(250, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { long start = System.currentTimeMillis(); String text = getText(); SimpleAttributeSet attrs = new SimpleAttributeSet(); StyleConstants.setForeground(attrs, Color.BLACK); StyledDocument doc = getStyledDocument(); doc.setCharacterAttributes(0, text.length(), attrs, true); int index = 0, carriage = 0; while ((index &lt; text.length())) { if (text.codePointAt(index) == 10) { carriage += 1; } for (String s : Keywords.listKeywords()) { if (text.startsWith(s, index)){ changeColor(doc, reserved.get(s), index, carriage, s.length(), false); index += s.length(); break; } } for (String s : Keywords.listOperators()) { if (text.startsWith(s, index)){ changeColor(doc, reserved.get(s), index, carriage, s.length(), false); index += s.length(); break; } } index++; } wordCount.setText("word count: " + index); System.out.println("Iterations took: " + (System.currentTimeMillis() - start) + " ms"); t.stop(); } }); t.start(); } private void changeColor(StyledDocument doc, Color color, int index, int carriage, int length, boolean replace) { SimpleAttributeSet attrs = new SimpleAttributeSet(); StyleConstants.setForeground(attrs, color); doc.setCharacterAttributes(index - carriage, length, attrs, replace); } </code></pre> <p>How would I go about doing this more efficiently?</p> <p>As of right now, with almost 145.000 words i have a delay of about 400 ms with 12 keywords and other words.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-26T05:55:33.047", "Id": "45715", "Score": "0", "body": "scanner.match().start() returns 0 whenever it starts a new line, so it doesn't know it is in a new line..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-26T06:42:04.927", "Id": "45720", "Score": "0", "body": "The code in revision 4 does not work so I've rollbacked it since it's off-topic here. I think it should be on Stack Overflow instead." } ]
[ { "body": "<p>Currently the it's <code>O(n)</code> where <code>n</code> is the length of the text inside the <code>JTextPane</code>.\nYou could reduce it if you process only the modified regions of the document in the event listener.\nI think <a href=\"http://docs.oracle.com/javase/7/docs/api/javax/swing/event/DocumentEvent.html\" rel=\"nofollow noreferrer\"><code>DocumentEvent</code></a>'s <code>getLength()</code> and <code>getOffset()</code> method could help here.</p>\n\n<p>Another notes:</p>\n\n<ol>\n<li>\n\n<pre><code>int index = 0, carriage = 0;\n</code></pre>\n\n<p>I'd put the variable declarations to separate lines. From Code Complete, 2nd Edition, p759:</p>\n\n<blockquote>\n <p>With statements on their own lines, the code reads from top to bottom, instead\n of top to bottom and left to right. When you’re looking for a specific line of code,\n your eye should be able to follow the left margin of the code. It shouldn’t have to\n dip into each and every line just because a single line might contain two statements.</p>\n</blockquote></li>\n<li><p>Be aware of static helper classes, like <code>Keywords</code>. You might find <a href=\"https://codereview.stackexchange.com/a/14361/7076\">my former answer about it</a> useful.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-25T05:02:20.313", "Id": "45592", "Score": "1", "body": "Thanks! Didn't search through all the DocumentEvent's methods. getOffset() is perfect." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T17:03:57.810", "Id": "28785", "ParentId": "28681", "Score": "0" } }, { "body": "<p>As a general direction for improvement, your technique for finding those keywords uses <code>startsWith</code>, which will effectively compare any given character once per potential keyword or operator. If you switch to <em>regular expressions</em>, by compiling a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html\" rel=\"nofollow\"><code>Pattern</code></a> that matches <em>any keyword</em> or <em>any operator</em>, you build (what amounts to) a lookup table that typically allows one comparison per character, reducing the total number of comparisons significantly.</p>\n\n<p>You can even use <code>Pattern.quote</code> to make building the String easier.</p>\n\n<pre><code>public Pattern fromList(List&lt;String&gt; strings) {\n StringBuilder builder = new StringBuilder();\n boolean isFirst = true;\n for (String string : strings) {\n if (!isFirst) {\n builder.append('|');\n }\n builder.append(Pattern.quote(string));\n isFirst = false;\n }\n return Pattern.compile(builder.toString());\n}\n</code></pre>\n\n<p>After that, search for every occurrence of the String using either <code>Pattern.matcher()</code> (or <code>Scanner.next()</code>), which will save you those repeated comparisons. At that point you can use the <code>start</code> and <code>end</code> methods on <code>Matcher</code> (or the same on <code>Scanner.match()</code>).</p>\n\n<p>I do notice that your algorithm will tend to highlight the first half of terms like <code>publicValue</code> even if the compiler does not detect it as a keyword. For this, you may want to customize the patterns you generate to match <a href=\"http://www.regular-expressions.info/wordboundaries.html\" rel=\"nofollow\">word boundaries</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-25T04:48:37.783", "Id": "45589", "Score": "0", "body": "Thanks. Patterns are complicated for first use! I understand how it works, but: how would I make a pattern to match a set of fixed words, like \"public, private, int, boolean\". I managed to understand how to use to search for a pattern, but not for individual words." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-25T05:00:58.293", "Id": "45591", "Score": "0", "body": "Im using right now: Matcher m = Pattern.compile(\"\\\\b(public+?)\\\\b\").matcher(this.getText()); but surelly there are better ways i imagine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-25T06:20:10.090", "Id": "45594", "Score": "0", "body": "The pipe symbol (`|`) means \"or\". Try \"\\\\b(public|private|function)\\\\b\" and so forth. Because you're in parens, the word would technically be \"group 1\" for the methods on Matcher, but since word boundaries are zero-length it'd work the same. Don't be afraid to generate the regex from your existing List. ;)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T01:25:47.973", "Id": "28796", "ParentId": "28681", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T09:26:27.580", "Id": "28681", "Score": "1", "Tags": [ "java", "algorithm", "performance", "strings" ], "Title": "Custom Script Editor" }
28681
<p>Given a production module like this:</p> <pre><code>function ($) { var showForm = function () { $.get(url, function (html) { $('body').append(html); }); }; return { showForm: showForm }; }); </code></pre> <p>I have written the following unit test:</p> <pre><code>it("calling showForm appends html to existing page", function () { var testPage = $('&lt;div&gt;&lt;body&gt;&lt;span&gt;&lt;/span&gt;&lt;/body&gt;&lt;/div&gt;'); var expectedPage = $('&lt;div&gt;&lt;body&gt;&lt;span&gt;&lt;/span&gt;&lt;label&gt;&lt;/label&gt;&lt;/body&gt;&lt;/div&gt;'); var htmlToAppend = $('&lt;label&gt;&lt;/label&gt;'); var callback = function () { return testPage.append(htmlToAppend); } sinon.stub(presenter, "showForm").yields(testPage); presenter.showForm(callback); expect(testPage.html()).to.equal(expectedPage.html()); }); </code></pre> <p>I am trying to test that when <code>presenter.showForm</code> is called, the returned html is appended successfully appended. Problem is, I'm not usre if it's a valid test as pretty much everything is fake.</p> <p>I'm toying with the idea of abstracting out the call to <code>$('body').append(html);</code> to another public function of the module or perhaps even to another module so that the call <code>presenter.showForm(callback);</code> can use the real function but I'm not sure?</p> <p>I hope that all makes sense.</p> <p>Can someone review and advise please?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T11:22:48.053", "Id": "45041", "Score": "1", "body": "First write a failing test. Then make it pass by writing non-test code only. Then you should be sure you haven't faked _everything_." } ]
[ { "body": "<p>I'm not quite sure what you mean by \"abstracting out the call...\", but given that the \"production module\" actually looks like that, then I'd say that you have a perfectly valid little test there.</p>\n\n<p>It is good to hear that you really are interested in making sure that your test cases are testing the right things. Unit tests are too often something that programmers write simply because they are forced to do it, and they are therefore happy enough when the tests don't fail - not pausing to consider that it might have passed because the test was incorrect, tested the wrong criteria, or did not in fact test anything at all.</p>\n\n<p>Using fake data is what you normally do at this level of functionality, so you are good there. You might generally want to consider using more than one set of test data, but in this case I would say that it is not necessary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T23:49:36.173", "Id": "45118", "Score": "0", "body": "Oh, and by the way: Good advice from @abuzittin in the comment to your post. Do make sure that your tests actually fails when the result is not the expected. For example by adding some character to htmlToAppend without making the corresponding change to expectedPage." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T08:48:30.643", "Id": "45378", "Score": "0", "body": "This did answer my question, so is the accepted one. However, I decided to go down a slightly different route, which I've posted in case it's helpful to others." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T23:44:00.197", "Id": "28738", "ParentId": "28684", "Score": "1" } }, { "body": "<p>I decided to add a callback to <code>showForm</code> so that I could get the returned html from the inner ajax request like so:</p>\n\n<pre><code> var showForm = function (url, callback) { \n $.get(url, function (html) {\n $('body').append(html);\n\n if (callback != undefined)\n callback(html);\n }); \n };\n</code></pre>\n\n<p>The test now looks like this:</p>\n\n<pre><code> it(\"showForm calls jQuery.append\", function (done) {\n\n // 1\n $.mockjax({ \n url: '/fake',\n dataType: 'html',\n responseText: '&lt;label&gt;&lt;/label&gt;'\n }); \n\n // 2\n var spy = sinon.spy($.fn, \"append\"); \n\n // 3\n presenter.showForm('/fake', function (html) {\n done();\n expect(spy.withArgs('&lt;label&gt;&lt;/label&gt;').calledOnce).to.be.equal(true); \n });\n });\n</code></pre>\n\n<ol>\n<li><p>I used the <a href=\"https://github.com/appendto/jquery-mockjax\" rel=\"nofollow\">jQuery.mockjax.js</a> library to setup a fake call and return fake html<br>\nfrom the ajax request. </p></li>\n<li><p>I then setup a spy on jQuery's append function.</p></li>\n<li><p>I can then check the spy was called with the html that would be returned from the ajax \nrequest. (my thinking is that I don't need to test that jQuery actually append the<br>\ndata, just that the call was made).</p></li>\n</ol>\n\n<p>This technique gives me more comfort that I am appending the html returned from my ajax request to the form. I would be even more happy if I could test that the <code>body</code> is being used as the selector but that's another story...</p>\n\n<p>Hope this is helpful.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T09:05:35.627", "Id": "28867", "ParentId": "28684", "Score": "0" } } ]
{ "AcceptedAnswerId": "28738", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T10:27:05.563", "Id": "28684", "Score": "0", "Tags": [ "javascript", "unit-testing" ], "Title": "Is my JavaScript test actually testing anything worthwhile here" }
28684
<h1>What?</h1> <p>I have a reference counted dynamic byte array written in C. I'm currently using this implementation in a FIFO fashion. Particularly reading data from files into the arrays, then parsing the data in the array byte by byte. </p> <p>I'm looking for feedback on anything! Even the decision to use a dynamic byte array versus using a linked list or any other data structure. </p> <p>Edit: I'm trying to follow the <a href="https://www.kernel.org/doc/Documentation/CodingStyle" rel="nofollow">Linux Kernel coding style</a>, so I'm looking for feedback on how well I follow that convention. </p> <h1>Files</h1> <h2>Header</h2> <pre><code>#ifndef DATA_BYTE_ARRAY #define DATA_BYTE_ARRAY #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;stdint.h&gt; #include &lt;assert.h&gt; #include &lt;string.h&gt; #include "../memory.h" /** * Dynamic array that grows when it's full (given that * the util functions in this module are used). * * For each grow it uses the current length doubled. See * byte_array_push for more info. */ struct byte_array { uint8_t refs; uint32_t length; uint32_t capability; uint8_t *bytes; }; /** * Creates a byte array with the given length. * * Values of the returned struct: * - 1 reference * - All bytes will be set to 0 * - Current position will be set to 0 * - Capability will reflect how many bytes are allocated. Which is * the same as given capability. */ struct byte_array *byte_array_create(uint32_t capability); /** * Adds the given input at the current position of the array. * * Note that if the pointer to the byte array is NULL an assertion will crash * the program. * * If the byte array is full more memory will be allocated. The amount * of new memory that will be allocated is the current amount doubled. */ void byte_array_push(struct byte_array *a, uint8_t input); void byte_array_incref(struct byte_array *a); void byte_array_decref(struct byte_array *a); #endif </code></pre> <h2>Source</h2> <pre><code>#include "byte_array.h" #define NEW_CAPABILITY a-&gt;capability * 2 static void zero_init_bytes(struct byte_array *a, uint32_t offset, uint32_t nmemb) { uint8_t *bytes = a-&gt;bytes; bytes += offset; memset(bytes, 0, nmemb); } struct byte_array *byte_array_create(uint32_t capability) { struct byte_array *result = assert_malloc(sizeof(*result)); result-&gt;refs = 1; result-&gt;length = 0; result-&gt;capability = capability; result-&gt;bytes = assert_calloc(capability, sizeof(uint8_t)); return result; } void byte_array_push(struct byte_array *a, uint8_t input) { assert(a != NULL); if (a-&gt;length == a-&gt;capability) { void *tmp = assert_realloc(a-&gt;bytes, NEW_CAPABILITY); a-&gt;bytes = tmp; zero_init_bytes( a, a-&gt;capability, NEW_CAPABILITY - a-&gt;capability ); a-&gt;capability = NEW_CAPABILITY; } a-&gt;bytes[a-&gt;length++] = input; } void byte_array_incref(struct byte_array *a) { assert(a != NULL); a-&gt;refs++; } void byte_array_decref(struct byte_array *a) { assert(a != NULL); if (--a-&gt;refs != 0) return; free(a-&gt;bytes); free(a); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T12:01:29.607", "Id": "45044", "Score": "0", "body": "A quick note. \"memory.h\" contains the functions `assert_malloc` and `assert_calloc`, they are wrapper functions that raises an assertion if `malloc` or `calloc` fails." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T12:47:58.690", "Id": "59706", "Score": "0", "body": "What if assert_realloc will fail (return NULL) ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T12:50:55.860", "Id": "59707", "Score": "0", "body": "Then an assertion will be raised and the program will terminate. But as @Lstor mentioned \"Note that the assert() macro is only evaluated if your library is compiled without NDEBUG\"\n\nSo I have to make a manual check instead of using the `assert` macro." } ]
[ { "body": "<p>This looks mostly good to me. Your code looks like fairly clean C. I have some comments:</p>\n\n<ul>\n<li><p>I think <code>capacity</code> is a better name than <code>capability</code>.</p></li>\n<li><p>I would avoid calling your header <code>memory.h</code>, since <code>memory</code> is a header in C++. Maybe <code>checked_alloc.h</code> instead? Also, include it as <code>\"memory.h\"</code> and let your build system figure out its path.</p></li>\n<li><p>How is your error handling in the <code>assert_...alloc</code> functions? Do they just terminate the program?</p></li>\n<li><p>Two of your public interface functions are without documentation. Are they not supposed to be part of the public interface? If not, put them in the implementation file (only) and make them <code>static</code>. If they are, document them as well.</p></li>\n<li><p>Note that the <code>assert()</code> macro is only evaluated if your library is compiled without <code>NDEBUG</code>. This means that the code using it will be unchecked for production builds. It might be fine, but maybe you want checking in production as well; I'm just pointing it out.</p></li>\n<li><p>As far as I can see, you adhere to the Linux coding style.</p></li>\n<li><p>Consider <code>typedef uint8_t byte</code> or something like that to emphasize what the role of the <code>uint8_t</code>s are. Remember that you have no guarantee that <code>CHAR_BIT</code> is 8. (Maybe you want to use <code>char</code> instead, which is guaranteed to always be one byte.)</p></li>\n<li><p>I would change <code>if (a-&gt;length == a-&gt;capability)</code> to <code>if (a-&gt;length &gt;= a-&gt;capability)</code>. The latter is a bit clearer, and if you at one point allow adding larger objects the code will still work.</p></li>\n<li><p>Your macro looks nasty.</p>\n\n<p>I'd do:</p>\n\n<pre><code>#define CAPACITY_GROWTH_FACTOR 2\n\n/* ... */\n\na-&gt;capability *= CAPACITY_GROWTH_FACTOR;\n</code></pre>\n\n<p>Or even better, change the <code>#define</code> into a <code>const size_t</code>.</p></li>\n<li><p>The <code>nmemb</code> variable isn't very readable. Change it to <code>num_members</code> or something like that.</p></li>\n<li><p>Consider sorting your <code>#include</code>s alphabetically.</p></li>\n<li><p>While I don't <em>see</em> anything wrong with your reference counting, you should thoroughly test it to verify that it works.</p></li>\n<li><p>Regarding reference counting and your interface, ask yourself these questions:</p>\n\n<ul>\n<li>What happens when you copy your array? What do you want to happen? How should a copy be made?</li>\n<li>How should copies behave when you modify an array that has multiple references to it?</li>\n<li>Will this be used in a multi-threaded environment?</li>\n</ul>\n\n<p>The answers affect how the interface should be designed. Personally, it seems to me that the reference counting is on a very low level (the caller has to take care of it himself), meaning it would be easy to make mistakes. Make your interface easy to use correctly, and hard to use incorrectly. Reference counting <em>might</em> not even be necessary here, depending on what the array is meant to be used for.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T12:42:51.040", "Id": "45047", "Score": "0", "body": "Thank you very much! Awesome list of comments, you have given me a lot to think about. \n\n- All `assert_*alloc` functions uses `assert` to check that the return was not `NULL` from the `*alloc` call. I didn't even realize what happens with NDEBUG until you mentioned it now. \n\n- The undocumented functions are supposed to be public, I just didn't think it was worth commenting them since they were so simple." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T12:32:25.653", "Id": "28697", "ParentId": "28690", "Score": "3" } }, { "body": "<p>On the header, you are exporting extra headers that have no part of the\ninterface. Anything you include in the public header is part of the interface\nof your module. That means anything that #includes your header becomes\ndependent upon those headers, which is undesirable.</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdint.h&gt;\n#include &lt;assert.h&gt;\n#include &lt;string.h&gt;\n\n#include \"../memory.h\"\n</code></pre>\n\n<p>All you need to include in the header is <code>stdint.h</code> to resolve the <code>uint8_t</code>\netc. As dependencies are generally best avoided, you might consider whether\nyou really need to use stdint types at all. What are you gaining over <code>char</code> and\n<code>int</code>?</p>\n\n<p>In the <code>struct byte_array</code> the <code>capability</code> field is misnamed. <code>capacity</code>\nseems to be what you mean.</p>\n\n<hr>\n\n<p>In the C file, you should delete the <code>NEW_CAPABILITY</code> macro. Macros are\ngenerally unsafe and should be avoided unless there is a good justification for\nthem (which there isn't here - you are just hiding some details). Here is how I would do it</p>\n\n<pre><code> if (a-&gt;length == a-&gt;capacity) {\n size_t new_size = a-&gt;capacity * 2;\n a-&gt;bytes = realloc(a-&gt;bytes, new_size);\n memset(a + capacity, 0, new_size - a-&gt;capacity);\n a-&gt;capacity = new_size;\n }\n</code></pre>\n\n<p>Your <code>zero_init_bytes</code> function is just a wrapper for <code>memset</code> and is\nredundant (ie. it adds nothing).</p>\n\n<hr>\n\n<p>On style, it looks nice. I am unfamiliar with Linux rules, so cannot comment\nthere. There is some excess whitespace, for example <code>byte_array_push</code> has\nfour unnecessary blank lines (an a redundant variable <code>tmp</code>).</p>\n\n<p>Note that <code>sizeof(uint8_t)</code> is 1, so just use 1</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T12:47:05.757", "Id": "28698", "ParentId": "28690", "Score": "2" } } ]
{ "AcceptedAnswerId": "28697", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T11:50:42.697", "Id": "28690", "Score": "2", "Tags": [ "c", "array", "linux" ], "Title": "Reference counted dynamic byte array" }
28690
<h1>What?</h1> <p>I have an algorithm that parses comma separated lists of unsigned 32-bit ints from strings. Here is an example of what a list could look like: </p> <pre><code>1302,51,2312,2,52 </code></pre> <p>The algorithm uses a custom data structure called <code>parse_input</code> which is a data structure that is a FIFO of numbers. This structure is passed to another unrelated function that parses some data with the help of this list of numbers. <code>parse_input_push</code> is used to add a number to the queue. </p> <p>The <code>byte_array</code> structure used in the tests has <a href="https://codereview.stackexchange.com/questions/28690/reference-counted-dynamic-byte-array-in-c">a separate code review</a>. </p> <p>I would like feedback on everything. Even the tests!</p> <h1>Files</h1> <h2>Source</h2> <pre><code>#define MAX_NUM_GLYPHS 11 static bool number_len_ok(const char *literal_num, size_t curr_num_len) { if (curr_num_len != MAX_NUM_GLYPHS - 1) return true; size_t i = 0; char *max_literal_num = "4294967296"; for (; i &lt; curr_num_len; i++) { if (literal_num[i] &gt; max_literal_num[i]) return false; } return true; } int parse_num_list(struct parse_input *lookup, char *num_list) { size_t i = 0; size_t curr_num_len = 0; size_t list_len = strlen(num_list); char literals[MAX_NUM_GLYPHS] = {0}; char curr_glyph; bool prev_was_comma = false; for (; i &lt; list_len; i++) { if (curr_num_len &gt;= MAX_NUM_GLYPHS) return -1; curr_glyph = num_list[i]; if (curr_glyph == ',') { if (prev_was_comma) return -2; if (!number_len_ok(literals, curr_num_len)) return -1; parse_input_push(lookup, atoi(literals)); memset(literals, '\0', 10); curr_num_len = 0; prev_was_comma = true; continue; } if (curr_glyph &lt; '0' || curr_glyph &gt; '9') return -2; prev_was_comma = false; literals[curr_num_len++] = curr_glyph; } if (!number_len_ok(literals, curr_num_len)) return -1; parse_input_push(lookup, atoi(literals)); return 0; } </code></pre> <h2>Tests</h2> <pre><code>void test_ok_parse_num_list() { char num_list[] = "124,1231231,2,20202,4294967296,1"; struct byte_array *lookup_name = byte_array_from_cstring("chr1"); struct parse_input *lookup = parse_input_create(lookup_name); int ret = parse_num_list(lookup, num_list); byte_array_decref(lookup_name); parse_input_decref(lookup); assert(ret == 0); printf("[ OK ] Parse num list\n"); } void test_too_big_parse_num_list() { char num_list[] = "124,1231231,2,20202,42949672952,1"; char num_list2[] = "124,1231231,2,20202,9999999999,666"; char num_list3[] = "124,1231231,2,20202,4294967297,1"; struct byte_array *lookup_name = byte_array_from_cstring("chr1"); struct parse_input *lookup = parse_input_create(lookup_name); int ret = parse_num_list(lookup, num_list); assert(ret == -1); ret = parse_num_list(lookup, num_list2); assert(ret == -1); ret = parse_num_list(lookup, num_list3); assert(ret == -1); byte_array_decref(lookup_name); parse_input_decref(lookup); printf("[ OK ] Parse too big num list\n"); } void test_invalid_parse_num_list() { char num_list[] = "124,1231231.,2,20202,429496,1"; char num_list2[] = "124,1231231,2,20202,99999999ö,666"; char num_list3[] = "124,1231231,2,20202,4294967,1,,,,"; struct byte_array *lookup_name = byte_array_from_cstring("chr1"); struct parse_input *lookup = parse_input_create(lookup_name); int ret = parse_num_list(lookup, num_list); assert(ret == -2); ret = parse_num_list(lookup, num_list2); assert(ret == -2); ret = parse_num_list(lookup, num_list3); assert(ret == -2); byte_array_decref(lookup_name); parse_input_decref(lookup); printf("[ OK ] Parse invalid num list\n"); } </code></pre>
[]
[ { "body": "<ul>\n<li><p>Having tests is good. I recommend using a test framework, for example <a href=\"https://code.google.com/p/googletest/\">googletest</a>.</p></li>\n<li><p>You are obviously using C99 (otherwise parts of your code wouldn't compile). C99 does not require variable instantiation at the beginning of a scope. You should generally create your variables as late as possible, to limit their scope. This includes moving your <code>for</code> loop counters into the loop.</p></li>\n</ul>\n\n<p>Like this:</p>\n\n<pre><code>for (size_t i = 0; i &lt; curr_num_len; i++) {\n if (literal_num[i] &gt; max_literal_num[i]) return false;\n}\n</code></pre>\n\n<ul>\n<li><p>Use a <code>const</code> instead of <code>#define</code>. That way you get normal scope rules, easier debugging, more readable compilation errors and so on.</p></li>\n<li><p>Don't use literal constants (\"magic numbers\"). Why does your function return <code>-2</code> and <code>-1</code>? Give them names instead: <code>return PARSE_ERROR;</code>. Why do you <code>memset</code> 10 bytes of <code>literals</code>, when its size is <code>MAX_NUM_GLYPHS</code>?</p></li>\n<li><p>I'd probably rename <code>number_len_ok()</code> to something along <code>is_number_too_large()</code> (and inverted the return values).</p></li>\n<li><p>You are assuming that numbers are located together and in order in the character set. It doesn't <em>necessarily</em> have to be that way (although it almost always is).</p></li>\n<li><p>Are the input strings allowed to have spaces? You don't have any tests for that.</p></li>\n<li><p>Your parsing function could probably be written in a bit cleaner and/or more readable way. This is left as an exercise to the reader :-)</p></li>\n<li><p>You're missing <code>#include</code>s for <code>memset</code>, <code>atoi</code> etc.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T13:11:03.230", "Id": "45050", "Score": "0", "body": "Again, thank you very much! Will look into googletest, didn't even know it existed before!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T13:06:42.590", "Id": "28705", "ParentId": "28694", "Score": "6" } }, { "body": "<p>What is <code>number_len_ok</code> supposed to do? <code>max_literal_num</code> is set to\n\"4294967296\" which is the string rep of 2^32. Is this supposed to be the\nmaximum <strong>length</strong> number you can parse - ten characters in other words? Why\nwould you compare the individual characters of the number you are parsing to\nthe individual chars of this string? If you pass the string \"9\", length 1 the\nfunction will return <code>false</code>. This makes no sense to me.</p>\n\n<p>I don't really follow why you are using such a complicated parsing function\neither, so maybe I am missing the point of this code altogether...</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>It is now clear to me that you really are just trying to parse out the numbers from a string (I was a bit obtuse before :-). My comment above was wrong in that \"9\" would not fail due to the initial conditional, but many (most?) 10-character strings starting from \"1000000007\" would fail. </p>\n\n<p>As I said, the code is very complicated for what it does. You should investigate what the standard library can offer for this sort of parsing. The <code>strtol</code> function is like <code>atoi</code> but sets <code>errno</code> if it finds that the number cannot be parsed (eg the number is too long or not valid). <code>strtol</code> returns a signed long (there is also a <code>strtoul</code> for unsigned long), which can be greater than 32 bits so if you really must restrict input to 32-bit integers you will need to test its return value.</p>\n\n<p>Something like the following would seem to do what you need without all of the copying characters and other tests etc.</p>\n\n<pre><code>static int parse(...lookup, const char *s)\n{\n char *end;\n errno = 0;\n while (*s != '\\0') {\n long n = strtol(s, &amp;end, 0);\n if (errno != 0) {\n // handle EINVAL, ERANGE (see man strtol)\n } else if (end == s) {\n // handle case where no number was found\n } else if (*end != ',') {\n // handle delimiter other than comma\n } else {\n parse_input_push(lookup, n);\n }\n s = end + 1;\n }\n return ...\n}\n</code></pre>\n\n<p>Note that testing is good. For something like this it is quite possible to test all good inputs for a single-number string:</p>\n\n<pre><code>for (int i=0; i&lt;LONG_MAX; ++i) {\n char buf[100];\n snprintf(buf, sizeof buf, \"%ld\", i);\n if (parse(lookup, i) != 0) {\n // Failed !!!\n }\n else if (i != /* get number from 'lookup' */) {\n // Failed !!!\n }\n}\n</code></pre>\n\n<p>Hope this is more useful than my initial comment :-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T14:46:54.940", "Id": "45259", "Score": "0", "body": "Thank you for pointing this out. It's not readable, very messy AND I haven't even written a comment. Basically the goal is to check that when the number string has the maximum amount of characters allowed the actual numeric value is not larger than `4294967296`. For example the number string `9999999999` has the same amount of *characters* as `4294967296`, but the actual numeric value is higher." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T23:50:59.237", "Id": "45284", "Score": "0", "body": "Unreadability, messiness and a lack of comments are secondary problems compared to the function not doing what you think it does :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T10:49:52.940", "Id": "45308", "Score": "0", "body": "That's why I wrote tests to make sure the function behaves as expected. And all tests succeeds. Maybe I missed what use case you say doesn't work?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T12:48:58.920", "Id": "45313", "Score": "0", "body": "I see now that your initial condition rules out most of the failing numbers (such as '9' suggested in my answer). But there are still many that fail. Start at 1000000007 and keep counting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T12:58:23.243", "Id": "45315", "Score": "0", "body": "Actually `1000000007` is a valid number and will not fail. I added it to my tests just to be sure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T13:11:13.333", "Id": "45316", "Score": "0", "body": "Don't know how that can be true. Try `const char * s = \"1000000007\"; printf(\"%s\\n\", number_len_ok(s, strlen(s)) ? \"true\":\"false\");`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T13:30:27.277", "Id": "45318", "Score": "0", "body": "You are totally right, sorry. I was looking at a later commit of that function where I changed the if-clause to only continue checking if the current number is the same and return false if the number is larger and true if the number is smaller." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T23:33:47.853", "Id": "28737", "ParentId": "28694", "Score": "2" } } ]
{ "AcceptedAnswerId": "28705", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T12:19:17.967", "Id": "28694", "Score": "4", "Tags": [ "c", "algorithm", "parsing", "lookup", "c99" ], "Title": "Algorithm (and tests) to parse lists of unsigned 32-bit ints from strings in C" }
28694
<p>I am learning about heaps, and I have found two ways of building them from a given array: I am trying to build up a MAX Heap.</p> <h3>1. Top-down approach</h3> <p>Here I check for every element to see if it is at the correct position or not. By using a function called <code>restoreUp</code>, in which every key is compared to its parent key, and if the parent key is smaller than the parent key is moved down. This procedure continues until the parent key is greater. I check it for every key starting at index position 2.</p> <p>My code is:</p> <pre><code>void restoreUp(int arr[],int i) { int k=arr[i]; int par=i/2; while(arr[par]&lt;k) { arr[i]=arr[par]; i=par; par=i/2; } arr[i]=k; } void buildheap1(int arr[],int size) { int i; for(i=2;i&lt;=size;i++) restoreUp(arr,i); } </code></pre> <h3>2. Bottom-up approach</h3> <p>Here I start from the first non-leaf node present at index <code>floor(size/2)</code>, and call a function <code>restoreDown</code> until node number 1. I compare a key with both its left and right child and then the greater child is moved up. If both children are greater than the key, then I move the larger of the two children up. This procedure stops when both children are smaller than the key.</p> <p>My code is:</p> <pre><code>void restoreDown(int arr[],int i,int size) { int left=2*i; int right=2*i+1; int num=arr[i]; while(right&lt;=size) { if(num&gt;arr[left] &amp;&amp; num&gt;arr[right]) { arr[i]=num; return; } else if(arr[left]&gt;arr[right]) { arr[i]=arr[left]; i=left; } else { arr[i]=arr[right]; i=right; } left=2*i; right=2*i+1; } if(left==size &amp;&amp; arr[left]&gt;num) { arr[i]=arr[left]; i=left; } arr[i]=num; } void buildheap2(int arr[],int size) { int i; for(i=size/2;i&gt;=1;i--) restoreDown(arr,i,size); } </code></pre> <p>Both the methods are working for me. Which method is more efficient and why?</p>
[]
[ { "body": "<p>Someone with more expertise on algorithms may provide a more concrete answer to your specific algorithms. However, I would like to point out two things on a general note:</p>\n\n<h3>1. Do the math.</h3>\n\n<p>Mathematically determining the complexity of an algorithm usually isn't <em>that</em> hard. Calculate big-O, check number of operations for given inputs and so on. While the answer may not be extremely precise, it's a nice exercise and can be very helpful.</p>\n\n<h3>2. Measure twice; cut once.</h3>\n\n<p>The best way to figure out the speed of an algorithm is to run it. Calculating the theoretical complexity is useful, but doesn't account for cache misses, branch prediction and the plethora of other things that can affect the execution speed. Run your algorithm on a large number of inputs and test cases to get statistically significant results. Run with and without a profiler to measure what exactly takes time. Sometimes you will find that altering the input, for example by sorting it or changing its layout to reduce cache misses, is more effective than altering the algorithm.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-12T09:57:28.367", "Id": "378207", "Score": "0", "body": "Sorting the input array in descending order does the job, as each node of the heap is earlier in the array that both its children. However, a heap needs a partial order only, so imposing a linear order with sorting the array may turn out both overkill and waste of time, as sorting may take O(n log n) time, while bottom-up heapifying takes O(n) only (Wikipedia: [Binary heap § Building a heap](https://en.wikipedia.org/wiki/Binary_heap#Building_a_heap))." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T13:52:34.633", "Id": "28710", "ParentId": "28695", "Score": "5" } } ]
{ "AcceptedAnswerId": "28710", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T12:23:54.877", "Id": "28695", "Score": "3", "Tags": [ "optimization", "c", "algorithm" ], "Title": "Build a binary-heap from an array, which method is more efficient and why" }
28695
<p>I was doing timing with variations of function <code>largest_prime_factor</code>. I was able to write a better one <code>largest_prime_factor2</code>. There were some repetitions in the new function so I wrote another function <code>largest_prime_factor3</code>. </p> <p>I thought the 3rd one has to be faster than the 2nd because I broke it up into more functions but it wasn't faster but slower. </p> <ul> <li>I wanted to know whether my method of code reuse is good or not? </li> <li>Is there a better way of reusing code in Python? </li> <li>Did I miss something due to which the new function became slower?</li> </ul> <p>My functions alongwith the <code>testing()</code> function used to test all three.</p> <pre><code>def largest_prime_factor(num): '''returns the largest prime factor of a number''' ans = 0 if num % 2 == 0: ans = 2 num /= 2 while num % 2 == 0: num /= 2 i = 3 while i &lt;= num: if num % i == 0: ans = i num /= i while num % i == 0: num /= i i += 2 return ans def largest_prime_factor2(num): '''returns the largest prime factor of a number''' ans = 0 if num % 2: pass else: ans = 2 while True: num //= 2 if num % 2: break i = 3 while i &lt;= num: if num % i: pass else: ans = i while True: num //= i if num % i: break i += 2 return ans def largest_prime_factor3(num): '''returns the largest prime factor of a number''' def check(j): nonlocal ans nonlocal num if num % j: return ans = j while True: num //= j if num % j: return ans = 0 check(2) i = 3 while i &lt;= num: check(i) i += 2 return ans def testing(): from timeit import Timer import random def tests(f, times): def test1(f): f(random.randint(1, 1000)) def test2(f): f(random.randint(100000, 1000000)) print(f.__name__) print(Timer(lambda: test1(f)).timeit(number = times)) print(Timer(lambda: test2(f)).timeit(number = times//10)) print() tests(largest_prime_factor, 10000) tests(largest_prime_factor2, 10000) tests(largest_prime_factor3, 10000) if __name__ == "__main__": testing() </code></pre> <p>The timing results that I found:</p> <blockquote> <pre><code>largest_prime_factor 0.338549207387318 16.599112750324068 largest_prime_factor2 0.21575289594063918 12.086949738861868 largest_prime_factor3 0.36032199674939847 18.893444539398857 </code></pre> </blockquote> <p>This format of results is produced by the <code>testing</code> function. See that for details.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T13:45:33.890", "Id": "45056", "Score": "0", "body": "As this question is about time efficiency any discussions for this can take place in [this chat room](http://chat.stackexchange.com/rooms/9695/discussion-about-timing-in-python). Please use this to avoid extended discussions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T15:28:28.607", "Id": "45162", "Score": "0", "body": "\"I thought the 3rd one has to be faster than the 2nd because I broke it up into more functions but it wasn't faster but slower. \" Why would you think that? Using function call instead of \"inlining the code\" can *only* produce a slowdown. Depending on the interpreter/compiler the code might be optimized to obtain the same efficiency as the inlined version, otherwise you end up with function-call overhead which means *slower* code. This is especially true in python where the interpreter doesn't do this kind of optimization and function calls are relatively expensive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T15:37:01.097", "Id": "45163", "Score": "0", "body": "I know that making function calls costs performance in C but I came upon that [code runs faster in functions in case of Python](http://stackoverflow.com/questions/11241523/why-does-python-code-run-faster-in-a-function). That led me to think that. Or is it incorrect? I am a newbie so I don't know how to use that for analyzing my code so I asked here what did I miss that led to performance lag. Anyways, is there a better way to inline the code in the case of 3rd function? That would improve readability and should also improve performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T15:46:47.970", "Id": "45164", "Score": "0", "body": "The code *doesn't* run faster in functions. The problem is that accessing *global* variables is slower than accessing local ones. This implies that a loop **at the top level** will be slow, because all variables all global and require the slow access. In your case the code that you put inside the `check` function was already inside a function, hence it was already using the fast local lookup." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T15:54:03.247", "Id": "45165", "Score": "0", "body": "I think I understand that now. Is there any alternative way to inline the code without losing performance?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T15:58:20.630", "Id": "45167", "Score": "1", "body": "In general no. In your example you had to copy the loop to special case `2`. But you can create an iterable that first yields 2 and then only the odd numbers. For example using `itertools.chain`: `for i in it.chain([2], range(3, num, 2)): ...` would do what you want. (Last remark: instead of `while True` you could use `while n % i == 0` and remove the `break`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T16:00:48.430", "Id": "45168", "Score": "0", "body": "I'll try using `itertools` as you have suggested. About the second suggestion about using the condition in the `while` loop I have timed that. It is slower." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T16:03:08.840", "Id": "45169", "Score": "1", "body": "Did you remove the `if` when timing that? `for i in range(3, num, 2): while n %i == 0: ... n //= i`. Also, do not obsess to much about timing. Readable code is *much better* than a code that take 0.1 msec less. Having `while True`s around doesn't make code readable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T16:09:57.450", "Id": "45170", "Score": "1", "body": "By the way: you are considering only micro-optimizations when you could optimize the number of iterations in a much more significant way. You don't have to check numbers over `sqrt(n)` since they cannot be factors of `n`. the only case is when `n` is prime)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T18:16:34.223", "Id": "45181", "Score": "0", "body": "To everyone. Let us continue this discussion in this [chat room for discussion about timing in Python](http://chat.stackexchange.com/rooms/9695/discussion-about-timing-in-python) as it going too long. Please post further comments there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T06:24:48.737", "Id": "45235", "Score": "0", "body": "@Bakuriu Make your comments a proper answer. That really helped me. The timing had huge improvements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T08:19:43.183", "Id": "45376", "Score": "0", "body": "@Bakuriu Can you make that an answer? I have been waiting to accept your answer. Or should I write it myself?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T08:46:24.120", "Id": "45377", "Score": "0", "body": "I wrote my answer. Note that my previous comment wasn't entirely true. A number *can* have a factor bigger than the square root, but it can have only once such factor. See my answer for the final correct version." } ]
[ { "body": "<p>Usually, splitting your code into different smaller functions is a good idea as it makes things easier to read, to reuse and to test.</p>\n\n<p>However, this comes at a (cheap) price as far as performances are concerned because functions calls are not for free (nor are function definitions). </p>\n\n<p>Now, for additional advices, whenever you want to compare performances of functions, it might also be a good idea to return what they compare. It's not good having a fast function if it doesn't return the right thing. By using <code>assert</code>, you could ensure you get notified quickly whenever something goes wrong.</p>\n\n<p>This being said, I'd like to run and comment your code but I don't have a python3 handy and it seems that it is the version you are using so I'll try to do this later :-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T13:35:04.873", "Id": "45051", "Score": "0", "body": "I am not using many features of Python3. You just need to change the `print` in the `testing` function. Maybe the nested function in that also. Everything else is same. Otherwise you can use http://ideone.com/ if you want." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T13:35:29.203", "Id": "45052", "Score": "0", "body": "[ideone.com](http://ideone.com) is your friend :-) The code: http://ideone.com/565hyx (Note that I divided the number of tests by 100.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T13:37:49.683", "Id": "45053", "Score": "0", "body": "@Lstor Making the numbers too small would give wrong results. the large numbers were the reason it is giving reproducible results. Instead just changing the `testing` function should suffice. Not much Python3 in this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T13:39:07.020", "Id": "45054", "Score": "0", "body": "@AseemBansal I fully agree, and larger numbers are definitely better. But ideone.com has a time limitation, and the purpose of running the code there is *running* it, not *timing* it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T13:40:36.827", "Id": "45055", "Score": "0", "body": "Thanks guys, `nonlocal` was actually the place making my python2.x interpreter sad ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T14:01:25.930", "Id": "45058", "Score": "1", "body": "Thanks for the advice about `assert`. About function calls costing performance then what about [this](http://stackoverflow.com/questions/11241523/why-does-python-code-run-faster-in-a-function)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T14:09:14.293", "Id": "45060", "Score": "0", "body": "Interesting link!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T05:49:53.573", "Id": "45140", "Score": "0", "body": "@Josay I'll be waiting to hear back from you." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T13:31:38.693", "Id": "28709", "ParentId": "28700", "Score": "1" } }, { "body": "<p>In order to avoid code duplication and the performance regression that you get when putting that code into a function you can use <a href=\"http://docs.python.org/3.3/library/itertools.html#itertools.chain\" rel=\"nofollow\"><code>itertools.chain</code></a>:</p>\n\n<pre><code>import itertools as it\n\ndef largest_prime_factor(num):\n '''returns the largest prime factor of a number'''\n ans = num\n for div in it.chain([2], range(3, num, 2)):\n while not num % div:\n num //= div\n ans = div\n return ans\n</code></pre>\n\n<p>To improve performances in a significant way you can reduce the number of iterations noting that you don't have to check factors bigger than <code>sqrt(num)</code>, since if <code>num</code> isn't a prime, then it can have at most one prime factor bigger than its square root(otherwise, if <code>p</code> and <code>q</code> where prime factors bigger than <code>sqrt(n)</code> you'd get that <code>n = A * p *q &gt; A * sqrt(n) * sqrt(n) = A * n &gt; n</code> which cannot be true when <code>A != 1</code>).</p>\n\n<p>This leads to:</p>\n\n<pre><code>def largest_prime_factor(num):\n '''returns the largest prime factor of a number'''\n ans = num\n sqrt_num = int(num**.5)\n for div in it.chain([2], range(3, sqrt_num + 1, 2)):\n while not num % div:\n num //= div\n ans = div\n return ans if num == 1 else num\n</code></pre>\n\n<p>Note that, at the end of the <code>for</code> loop, the value of <code>num</code> is 1 if all its prime factors were smaller than the square root, otherwise it is equal to the only prime factor bigger than the square root.</p>\n\n<p>Sample run:</p>\n\n<pre><code>In [34]: list(map(largest_prime_factor, range(2, 25)))\nOut[34]: [2, 3, 2, 5, 3, 7, 2, 3, 5, 11, 3, 13, 7, 5, 2, 17, 3, 19, 5, 7, 11, 23, 3]\n</code></pre>\n\n<hr>\n\n<p>In fact we can further optimize the code noting that, whenever <code>num</code> becomes <code>1</code> inside the <code>for</code> loop we can safely <code>break</code> out of it(while the current code tries all the other factors up to <code>sqrt(n)</code> anyway).</p>\n\n<pre><code>def largest_prime_factor(num):\n '''returns the largest prime factor of a number'''\n ans = num\n sqrt_num = int(num**.5)\n for div in it.chain([2], range(3, sqrt_num + 1, 2)):\n while not num % div:\n num //= div\n ans = div\n if div &gt; num // div:\n return ans\n return num\n</code></pre>\n\n<p>We could also do something like:</p>\n\n<pre><code>def largest_prime_factor(num):\n '''returns the largest prime factor of a number'''\n ans = num\n sqrt_num = int(num**.5)\n candidates = it.chain([2], range(3, sqrt_num + 1, 2))\n for div in it.takewhile(lambda div: div &lt;= num // div, candidates):\n while not num % div:\n num //= div\n ans = div\n return max(ans, num)\n</code></pre>\n\n<p>However this last version does a function call for each iteration and it will be <em>slightly</em> slower.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T08:49:45.533", "Id": "45379", "Score": "0", "body": "I figured that there is a bigger number. There is slight formatting problem in the beginning of the question when importing `itertools`. Also when `sqrt_num = int(num**.5) + 1` then you don't need the `+ 1` in the range. Redundant. Please fix that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T09:26:53.447", "Id": "45380", "Score": "0", "body": "@AseemBansal Fixed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T15:02:15.137", "Id": "45398", "Score": "2", "body": "largest prime factor of (2^200 * 9) is 3. To find this, the maximal divisor to try by is 3, not (3 * 2^100). :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T18:28:30.280", "Id": "45415", "Score": "0", "body": "welcome; your code isn't right still though. What about (2^100 * 10000000019)? What is the biggest divisor to consider?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T18:29:19.483", "Id": "45417", "Score": "0", "body": "Actually your new solution can be improved. That is a function so if num is 1 you don't need to break. You can just return. Then you can take out the condition from the return statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T18:31:58.997", "Id": "45419", "Score": "0", "body": "This solution can be good for really big numbers but wouldn't it be bad for small numbers? Perhaps check the range of the number and call different helper functions. Also placing any arithmetic in `range` slows it down slightly. The `+1` should be placed when `sqrt_num` is calculated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T18:42:33.627", "Id": "45422", "Score": "0", "body": "@AseemBansal It doesn't make any difference where you put the `+1`. `range` is a function like any other, which means all its arguments are evaluated *once* when the function is called. @WillNess In that case I don't see how the code could see where to stop. It wouldn't be too hard to implement Miller-Rabin and do a fast check for primality at every iteration and stop whenever it fails, but it seems an overkill to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T18:46:29.667", "Id": "45423", "Score": "0", "body": "@WillNess Just out of curiosity, why aren't you posting an answer?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T18:48:13.027", "Id": "45424", "Score": "0", "body": "@AseemBansal if this is almost right, easier to correct it here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T18:48:41.197", "Id": "45425", "Score": "0", "body": "@AseemBansal You should read also about [`Fermat's factorization method`](http://en.wikipedia.org/wiki/Fermat%27s_factorization_method) which, with a bit more work, achieves better performance for numbers with big prime factors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T18:50:45.150", "Id": "45426", "Score": "0", "body": "@Bakuriu just use a `while` loop, nothing fancy, with stop condition `divisor <= number / divisor`. Increment divisor by 2, starting from 3. Test divisor=2 separately. Inside the loop have `number /= divisor` like you have now. -- (BTW, `while not num % div:` is *very* counter-intuitive, to me. :) I'd write `while num % div == 0:`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T19:18:05.903", "Id": "45429", "Score": "1", "body": "@WillNess I see, changed; now it should be as fast as possible for a simple implementation. Regardin the rest I don't see why should I use a `while` loop where a `for` will do(note that in python using a `while` *will* decrease performances, even though in this case, hopefully, the operations inside the loop should take most of the time). Also the OP specifically asked how to do this *without* testing `2` separately. Regarding the `not`: it's common practice in python to use `not` or simply `if expression` to check for truth values(e.g. `if some_sequence:` means `some_sequence` isn't empty." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-12T20:11:37.023", "Id": "176742", "Score": "0", "body": "@Bakuriu you were totally right about the `while` vs `for`! now I know, for sure. :)" } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T08:44:36.037", "Id": "28865", "ParentId": "28700", "Score": "1" } } ]
{ "AcceptedAnswerId": "28865", "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T12:53:28.120", "Id": "28700", "Score": "1", "Tags": [ "python", "optimization", "primes", "python-3.x" ], "Title": "Efficient way of code reuse for finding the largest prime factor" }
28700
It is the practice of reusing existing code to avoid redundancy in code.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T12:59:58.727", "Id": "28702", "Score": "0", "Tags": null, "Title": null }
28702
<p>Python 3 is the latest version of the Python programming language, released on December 3rd, 2008. It features simplifications and improvements to the syntax of the language. Some of these changes are backwards incompatible, and therefore Python 3 has its own tag.</p> <p>Although Python 3 itself is ready for primetime and stable use, many of the popular external libraries have not yet been ported.</p> <p>You should see the article <a href="https://wiki.python.org/moin/Python2orPython3" rel="nofollow noreferrer">Python 2 or Python 3</a> on the Python website before choosing which version to use.</p> <p>For information on the differences see <a href="https://docs.python.org/3.6/howto/pyporting.html" rel="nofollow noreferrer">Porting Python 2 Code to Python 3.</a></p> <p>For information on Python in general, visit the <a href="https://codereview.stackexchange.com/tags/python/info">main Python tag wiki</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T13:05:06.000", "Id": "28703", "Score": "0", "Tags": null, "Title": null }
28703
Python 3 is the latest version of the Python programming language and was formally released on December 3rd, 2008. Use this tag along with the main python tag to denote programs that are meant to be run on a Python 3 interpreter only. Do not mix this tag with the python-2.x tag.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-07-19T13:05:06.000", "Id": "28704", "Score": "0", "Tags": null, "Title": null }
28704
<p>I created this quite important piece of code, but I am not pretty sure is it good enough. </p> <p><strong>Goal:</strong></p> <p>I have a big task for a database and have decided to use Django-Celery. I want to go through all objects of a particular model and create monthly statistics for each of them based on other foreign objects of it. The task will be run on the 1st day of every month.</p> <p>The application will be rather dedicated for particular social group. No, I will not have millions of users. </p> <p>My main worries are:</p> <ol> <li><p>Date and time and time zone calculations.</p></li> <li><p>Is it good Idea to do it with Celery? Maybe do it on the statistics view every time somebody wants to see his stats but it may take too many queries?</p></li> </ol> <hr> <pre><code># -*- coding: utf-8 -*- from __future__ import unicode_literals import calendar from datetime import datetime, time from djcelery import celery import pytz from models import MonthlyStatistics, Scope, Entry, Action, Support @celery.task def calculate_monthly_statistics(): """\ Create Monthly Statistic objects for all Scope models. In statistics there are numbers of created Actions, Entries and Supports in last month period. """ for scope in Scope.all(): # Create datetime range for querying now = datetime.utcnow().replace(tzinfo=pytz.utc) last_month = {} last_month['year'] = now.year if now.month &gt; 1 else now.year - 1 last_month['month'] = now.month - 1 if now.month &gt; 1 else 12 last_month['first_day'] = 1 last_month['last_day'] = \ calendar.monthrange(last_month['year'], last_month['month'])[1] last_month_range = \ (datetime.combine(datetime(last_month['year'], last_month['month'], last_month['first_day']), time.min).replace(tzinfo=pytz.utc), datetime.combine(datetime(last_month['year'], last_month['month'], last_month['last_day']), time.max).replace(tzinfo=pytz.utc)) # Get Entries for current month entries = Entry.filter(created__range=last_month_range, diary__scope=scope) # Get Actions for current month actions = Action.filter(created__range=last_month_range, scope=scope) # Get Supports for current month supports = Support.filter(created__range=last_month_range, scope=scope) # Create Stats monthly_statistics = MonthlyStatistics.create(scope=scope, year=now.year, month=now.month, support_number=len(supports), entries=len(entries), actions=len(actions)) monthly_statistics.save() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T13:08:07.110", "Id": "28706", "Score": "2", "Tags": [ "python", "django" ], "Title": "Task for all objects in model with datetime operations" }
28706
C99 is a standard for the C programming language. It replaces the previous C89 standard, and is succeeded by the C11 standard. C99 added inline functions, C++-style comments, allows intermingled declarations and code, as well as multiple other language and library fixes and additions.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T13:25:16.247", "Id": "28708", "Score": "0", "Tags": null, "Title": null }
28708
<p>Questions regarding code organization can deal with the topic on various levels:</p> <ul> <li><p>how to split parts of a larger project into subprojects (e.g. in Maven modules)</p></li> <li><p>how to distribute classes in packages</p></li> <li><p>where to put tests relative to the code that gets tested</p></li> <li><p>where to put methods or fields inside of classes or other code units</p></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T14:22:34.383", "Id": "28713", "Score": "0", "Tags": null, "Title": null }
28713
Questions that deal with the organization and structure of the code should be given this tag.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T14:22:34.383", "Id": "28714", "Score": "0", "Tags": null, "Title": null }
28714
<p>This script creates a hierarchy of directories. Is this a good approach or can it be made better? I am mainly concerned with maintainability here, not efficiency. Suppose I wanted to add more directories to this hierarchy. Would this structure of the script make it easier to do?</p> <p><strong>Hierarchy</strong></p> <pre><code>./project_euler ./001_050 ./051_100 ... ./401_450 ./codechef ./easy ./medium ./hard ./spoj ./functions ./utilities </code></pre> <p><strong>The script</strong></p> <pre><code>import os TOP = ['project_euler', 'codechef', 'spoj', 'functions', 'utilities'] CODECHEF = ['easy', 'medium', 'hard'] def safe_make_folder(i): '''Makes a folder if not present''' try: os.mkdir(i) except: pass def make_top_level(top): for i in top: safe_make_folder(i) def make_euler_folders(highest): def folder_names(): '''Generates strings of the format 001_050 with the 2nd number given by the function argument''' for i in range(1,highest, 50): yield ( 'project_euler' + os.sep + str(i).zfill(3) + '_' + str(i + 49).zfill(3) ) for i in folder_names(): safe_make_folder(i) def make_codechef_folders(codechef): for i in codechef: safe_make_folder('codechef' + os.sep + i) def main(): make_top_level(TOP) make_euler_folders(450) make_codechef_folders(CODECHEF) if __name__ == "__main__": main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T19:58:10.533", "Id": "45093", "Score": "1", "body": "PEP 8 advices lower case for local variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T16:37:10.633", "Id": "45172", "Score": "1", "body": "@Josay HIGHEST is constant, but not defined at the module level. PEP8: `Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T16:59:02.973", "Id": "45174", "Score": "0", "body": "@Lstor said that global variables are code-smell so I thought to make them local variables(which are constants so I used capital letters). What would be the correct design decision here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T16:59:34.587", "Id": "45175", "Score": "0", "body": "@Josay Please see the above" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T17:08:55.517", "Id": "45176", "Score": "0", "body": "@Anthon Please see the above comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T19:08:32.653", "Id": "45188", "Score": "0", "body": "Since Python doesn't have real constants, the convention is to use all uppercase (+underscore) for the variable name, make it global and treat it as read-only. It would be inappropriate to assign a value to the global 'constant' somewhere else. Look e.g. at the os.py module that comes with Python. It has `SEEK_SET = 0` at the module level and no smell is involved because it is used as a constant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T19:17:21.573", "Id": "45189", "Score": "0", "body": "@Anthon Updated the code. How about now? Is this what you were talking about?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T19:27:28.443", "Id": "45192", "Score": "0", "body": "@AseemBansal Looks good to me, I would leave it like that." } ]
[ { "body": "<p>I'm not quite convinced that a python script is required here as a shell one-liner would probably do the trick (<code>mkdir -p codechef/{easy,medium,hard} spoj utilities</code> would be a good starting point).</p>\n\n<p>Your python code could be improved by using <a href=\"http://www.python.org/dev/peps/pep-0289/\" rel=\"nofollow\">Generator Expressions</a> :</p>\n\n<pre><code>def make_euler_folders(highest):\n def folder_names():\n '''Generates strings of the format 001_050 with\n the 2nd number given by the function argument'''\n for i in range(1,highest, 50):\n yield (\n 'project_euler' + os.sep +\n str(i).zfill(3) + '_' + str(i + 49).zfill(3)\n )\n\n for i in folder_names():\n safe_make_folder(i)\n</code></pre>\n\n<p>would become</p>\n\n<pre><code>def make_euler_folders(highest):\n def folder_names():\n '''Generates strings of the format 001_050 with\n the 2nd number given by the function argument'''\n return ('project_euler' + os.sep + str(i).zfill(3) + '_' + str(i + 49).zfill(3) for i in range(1,highest, 50))\n\n for i in folder_names():\n safe_make_folder(i)\n</code></pre>\n\n<p>which is then nothing but :</p>\n\n<pre><code>def make_euler_folders(highest):\n for i in ('project_euler' + os.sep + str(i).zfill(3) + '_' + str(i + 49).zfill(3) for i in range(1,highest, 50)):\n safe_make_folder(i)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T14:57:03.443", "Id": "45065", "Score": "0", "body": "I used Python because I am on Windows." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T15:02:36.047", "Id": "45066", "Score": "0", "body": "Anything about use of global variables? Should I pass them or not? Best practice about that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T15:25:07.960", "Id": "45068", "Score": "1", "body": "You should pass them. Global variables is a code smell, and leads to tighter coupling (which is bad)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T15:50:17.833", "Id": "45070", "Score": "1", "body": "Also, you should probably check your usage of literal strings as some of them are defined twice ('project_euler', 'codechef')." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T05:46:00.400", "Id": "45139", "Score": "0", "body": "@Josay Is it better now?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T14:45:14.807", "Id": "28716", "ParentId": "28715", "Score": "2" } }, { "body": "<p>One of the things I would do is remove the double occurrence of the strings <code>'project_euler'</code> and <code>'codechef'</code>. If you ever have to change one of these in <code>TOP</code>, you are bound to miss the repetition in the functions. </p>\n\n<p>You should at least use <code>TOP[0]</code> in <code>make_euler_folders()</code> and <code>TOP[1]</code> in <code>make_codechef_folders</code>. A better approach however would be to take both definitions out of <code>TOP</code> and change <code>def safe_make_folder()</code>:</p>\n\n<pre><code>TOP = ['spoj', 'functions', 'utilities']\n\ndef safe_make_folder(i):\n '''Makes a folder (and its parents) if not present'''\n try: \n os.makedirs(i)\n except:\n pass\n</code></pre>\n\n<p>The standard function <a href=\"http://docs.python.org/2/library/os.html#os.makedirs\" rel=\"nofollow\"><code>os.makedirs()</code></a> creates the <code>'project_euler'</code> resp. \n'codechef', as the first subdirectory of each is created.</p>\n\n<hr>\n\n<p>The other is that I would create the directory names using <a href=\"http://docs.python.org/2/library/os.path.html#os.path.join\" rel=\"nofollow\"><code>os.path.join()</code></a> (as it prevents e.g. the mistake of providing double path separators), in combination with <a href=\"http://docs.python.org/3/library/string.html#format-specification-mini-language\" rel=\"nofollow\">standard string formatting</a> to get the leading zeros on the subfolder names:</p>\n\n<pre><code>os.path.join('project_euler', '{:03}_{:03}'.format(i, i+49))\n</code></pre>\n\n<p>the <code>{:03}</code> gives a 3 character wide field with leading zeros. @Josay improvemed function would then become:</p>\n\n<pre><code>def make_euler_folders(highest):\n for i in (os.path.join('project_euler', '{:03}_{:03}'.format(i, i+49)) \\\n for i in range(1,highest, 50)):\n safe_make_folder(i)\n</code></pre>\n\n<p>And the other function would become:</p>\n\n<pre><code>def make_codechef_folders(codechef):\n for i in codechef:\n safe_make_folder(os.path.join('codechef', i))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T16:40:38.997", "Id": "45077", "Score": "0", "body": "Updated the code. Any other suggestions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T16:38:27.263", "Id": "45173", "Score": "0", "body": "move the constant `HIGHEST` to the module level and make it a somewhat more descriptive name (HIGHEST_EXERSIZE_NUMBER ?)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T16:04:01.203", "Id": "28719", "ParentId": "28715", "Score": "4" } } ]
{ "AcceptedAnswerId": "28719", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T14:30:32.763", "Id": "28715", "Score": "5", "Tags": [ "python", "directory" ], "Title": "Script for creating a hierarchy of directories" }
28715
<p>Ok, I have written the following but I am sure it can be done better, my two main worries here are the awful use of the if else statements in the check variables and the usage of setinterval to set the i variable. my problem with the i variable is that the check's run after the i has been set forcing the i to always have a value of 0 due to the css being set as display none. Hope someone can advise: </p> <pre><code> (function ($) { // variables setInterval(function() { // Do something every 5 seconds i = jQuery('#widgets-right').find('.addinput &gt; div:visible').length + 2; }, 1500); //check if box has value allready and show if it has var check1 = function () { var empty1 = $("#widgets-right .div_2 p .title2:input").filter(function () { return this.value === ""; }); if (empty1.length) { $('.div_2').hide(); } else { $('.div_2').show(); } }, check2 = function () { var empty2 = $("#widgets-right .div_3 p .title3:input").filter(function () { return this.value === ""; }); if (empty2.length) { $('.div_3').hide(); } else { $('.div_3').show(); } }, check3 = function () { var empty3 = $("#widgets-right .div_4 p .title4:input").filter(function () { return this.value === ""; }); if (empty3.length) { $('.div_4').hide(); } else { $('.div_4').show(); } }, check4 = function () { var empty4 = $("#widgets-right .div_5 p .title5:input").filter(function () { return this.value === ""; }); if (empty4.length) { $('.div_5').hide(); } else { $('.div_5').show(); } }, check5 = function () { var empty5 = $("#widgets-right .div_6 p .title6:input").filter(function () { return this.value === ""; }); if (empty5.length) { $('.div_6').hide(); } else { $('.div_6').show(); } }, check6 = function () { var empty6 = $("#widgets-right .div_7 p .title7:input").filter(function () { return this.value === ""; }); if (empty6.length) { $('.div_7').hide(); } else { $('.div_7').show(); } }, check7 = function () { var empty7 = $("#widgets-right .div_8 p .title8:input").filter(function () { return this.value === ""; }); if (empty7.length) { $('.div_8').hide(); } else { $('.div_8').show(); } }, check8 = function () { var empty8 = $("#widgets-right .div_9 p .title9:input").filter(function () { return this.value === ""; }); if (empty8.length) { $('.div_9').hide(); } else { $('.div_9').show(); } }, check9 = function () { var empty9 = $("#widgets-right .div_10 p .title10:input").filter(function () { return this.value === ""; }); if (empty9.length) { $('.div_10').hide(); } else { $('.div_10').show(); } }; check1(); check2(); check3(); check4(); check5(); check6(); check7(); check8(); check9(); $('body').ajaxSuccess(function () { check1(); check2(); check3(); check4(); check5(); check6(); check7(); check8(); check9(); }); //load on widget title click $(document).on("click", '#widgets-right .widget-top', function () { $(".area").load("/galleries/ #projects &gt; li a"); check1(); check2(); check3(); check4(); check5(); check6(); check7(); check8(); check9(); }); //stop default href from working $(document).unbind().on("click", '.area a', function () { event.preventDefault(); return; }); //show new forms $(document).on('click', '#widgets-right .addNew', function () { if (i === 10) { alert('thats the max!'); } else if (i === 9) { alert('one more to go be careful now your gonna break me, Now pick one more image!'); $(".div_" + i).show('slow'); i = i + 1; } else { alert(i); $(".div_" + i).show('slow'); i = i + 1; alert('Now pick another image'); return false; } }); //remove old forms $(document).on('click', '#widgets-right .remNew', function () { if (i &gt; 1 &amp;&amp; jQuery(this).parent('div').next().is(':visible')) { alert('remove me in order please.'); } else { i = i - 1; $('.title' + i).val(""); $('.link' + i).val(""); $('.img' + i).val(""); $('.gallery_one' + i).attr("src", ''); $(this).parent('div').hide('slow'); } return false; }); //load into input boxes $(document).on("click", "#widgets-right .area a", function () { $(this).toggleClass('selected'); var title = $(this).attr('title'), link = $(this).attr('href'), img = $("img", this).attr('src'), imgexample = $("img", this).attr('src'); if (i &lt;= 2) { alert('added to project 1. If you want to add more projects just click button labeled "add new project"!'); $(".title").val(title); $(".link").val(link); $(".img").val(img); $(".gallery_one").attr("src", imgexample); } else { i = i - 1; alert('added to project ' + i); $('.title' + i).val(title); $('.link' + i).val(link); $('.img' + i).val(img); $('.gallery_one' + i).attr("src", imgexample); i = i + 1; } }); }(jQuery)); </code></pre> <p>here's html structure: </p> <pre><code>&lt;div class="addnew"&gt; &lt;input type="text"&gt; &lt;input type="text"&gt; &lt;div class="addinput"&gt; &lt;a href="#" class="addnew"&gt;ADD NEW&lt;/a&gt; &lt;div class="div_2"&gt; &lt;h4&gt;lorem ipsum&lt;/h4&gt; &lt;div class="div"&gt;&lt;img src="" alt=""&gt;&lt;/div&gt; &lt;p&gt;&lt;label for=""&gt;&lt;/label&gt;&lt;input type="text" /&gt;&lt;/p&gt; &lt;a class="remNew" href=""&gt;REMOVE&lt;/a&gt; &lt;/div&gt; &lt;div class="div_3"&gt; &lt;h4&gt;lorem ipsum&lt;/h4&gt; &lt;div class="div"&gt;&lt;img src="" alt=""&gt;&lt;/div&gt; &lt;p&gt;&lt;label for=""&gt;&lt;/label&gt;&lt;input type="text" /&gt;&lt;/p&gt; &lt;a class="remNew" href=""&gt;REMOVE&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T16:48:04.847", "Id": "45081", "Score": "0", "body": "Some HTML would help for context." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T17:22:04.330", "Id": "45083", "Score": "0", "body": "@JonnySooter hello again :D \nUpdated with html !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T17:49:23.260", "Id": "45085", "Score": "0", "body": "I forgot to ask before but a fiddle would be nice :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T18:29:06.363", "Id": "45088", "Score": "0", "body": "@JonnySooter there is a fiddle more or less http://jsfiddle.net/JrHhJ/5/" } ]
[ { "body": "<p>The <code>check</code> stuff is very redundant and should be handled by doing something like this:</p>\n\n<pre><code>var check = [];\nfor(var i = 1; i &lt; 10; i++) {\n check[i] = (function(i) {\n return function() {\n console.log(i);\n var empty = $(\"#widgets-right .div_\" + i + \" p .title\" + i + \":input\").filter(\n function() {\n return this.value === \"\";\n }\n );\n if (empty.length) {\n $('.div_' + i).hide();\n } else {\n $('.div_' + i).show();\n }\n };\n }(i));\n}\n</code></pre>\n\n<p>And then replace all the check calls with this:</p>\n\n<pre><code>function checkAll() {\n $.each(check, function(i) { check[i]() });\n}\n</code></pre>\n\n<p>Later on, you're doing this:</p>\n\n<pre><code> [...snip...]\n $('.title' + i).val(\"\");\n $('.link' + i).val(\"\");\n $('.img' + i).val(\"\");\n $('.gallery_one' + i).attr(\"src\", '');\n [...snip...]\n</code></pre>\n\n<p>And then later again, this:</p>\n\n<pre><code> [...snip...]\n $(\".title\").val(title);\n $(\".link\").val(link);\n $(\".img\").val(img);\n $(\".gallery_one\").attr(\"src\", imgexample);\n [...snip...]\n</code></pre>\n\n<p>...and then...</p>\n\n<pre><code> [...snip...]\n $('.title' + i).val(title);\n $('.link' + i).val(link);\n $('.img' + i).val(img);\n $('.gallery_one' + i).attr(\"src\", imgexample);\n</code></pre>\n\n<p>I guess you can see where I am going. I won't rewrite this for you, but a hint is that all you need is to write a function with this signature:</p>\n\n<pre><code>function setStuff(i, title, link, img, imgexample) {\n [fill in the blanks here]\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T07:48:15.707", "Id": "45141", "Score": "0", "body": "One note: if you never need to check the different elements separately, then the above solution can be simplified further." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T18:42:14.043", "Id": "28725", "ParentId": "28718", "Score": "2" } } ]
{ "AcceptedAnswerId": "28725", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T15:55:43.207", "Id": "28718", "Score": "-1", "Tags": [ "javascript", "jquery" ], "Title": "Jquery ajax loader and messy if else statements?" }
28718
<p>I'm just getting started on GUI programming using swing in Java, and I would love some critiques on my code. I understand there is a danger in using global variables. If someone can hint me on how to get rid of my globals (which will be later registered for event handling), I'd really appreciate it.</p> <pre><code>import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; public final class Calculator extends JFrame { //initialise various variables for use within the program //BUTTONS private final JButton additionButton = new JButton("+"); private final JButton subtractionButton = new JButton("-"); private final JButton divisionButton = new JButton("/"); private final JButton multiplicationButton = new JButton("*"); //PANELS private JPanel operatorPanel; private JPanel operandPanel; //LABELS private JLabel operationLabel; //constructor to initialise the frame and add components into it public Calculator() { super("Clancy's Calculator"); setLayout(new BorderLayout(5, 10)); setResizable(false); setSize(370, 200); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); //create a message label to display the operation that has just taken place operationLabel = new JLabel("YOU HAVE PERFORMED SOME OPERATION", SwingConstants.CENTER); add(getOperatorPanel(), BorderLayout.NORTH); add(getOperandPanel(), BorderLayout.CENTER); add(operationLabel, BorderLayout.SOUTH); pack(); } //setter method for the operator panel public void setOperatorPanel() { operatorPanel = new JPanel(); operatorPanel.setLayout(new FlowLayout()); operatorPanel.add(additionButton); operatorPanel.add(subtractionButton); operatorPanel.add(multiplicationButton); operatorPanel.add(divisionButton); } //getter method for the operator panel public JPanel getOperatorPanel() { setOperatorPanel(); return operatorPanel; } //setter method for operands panel public void setOperandPanel() { operandPanel = new JPanel(); operandPanel.setLayout(new GridLayout(3, 2, 5, 5)); //LABELS JLabel operandOneLabel = new JLabel("Enter the first Operand: "); JLabel operandTwoLabel = new JLabel("Enter the second Operand: "); JLabel answerLabel = new JLabel("ANSWER: "); //TEXT FIELDS JTextField operandOneText = new JTextField(); //retrieves one operand JTextField operandTwoText = new JTextField(); //retrieves another operand JTextField answerText = new JTextField(); //displays answer answerText.setEditable(false); //ensure the answer field is not editable operandPanel.add(operandOneLabel); operandPanel.add(operandOneText); operandPanel.add(operandTwoLabel); operandPanel.add(operandTwoText); operandPanel.add(answerLabel); operandPanel.add(answerText); } //getter method for operand panel public JPanel getOperandPanel() { setOperandPanel(); return operandPanel; } /** main method */ public static void main(String[] args) { new Calculator(); } } </code></pre>
[]
[ { "body": "<p>A thing I like to do is instead of using four different JButtons is use an array of four JButtons that is initialized in the same method that you build the JPanel this would remove the need to have them as global variables. Also instead of using two different methods to create your JPanels just use one that returns a JPanel as you can see you can remove the JButtons and the two JPanels this way:</p>\n\n<pre><code>public JPanel buildOperatorPanel()\n{\n JPanel operatorPanel = new JPanel();\n operatorPanel.setLayout(new FlowLayout());\n\n JButton[] buttons = new JButton[4];//the array of JButtons\n String[] buttonNames = {\"+\", \"-\", \"/\", \"*\"};//the names to be displayed on the JButtons\n for(int i = 0; i &lt; buttons.length; i++)\n {\n buttons[i] = new JButton(buttonNames[i]);\n //buttons[i].addActionListener(yourActionListener)//for whenever you add event handling\n operatorPanel.add(buttons[i]);\n }\n return operatorPanel;\n}\n</code></pre>\n\n<p>Another thing I could suggest is instead of named reference variables for your JLabels use anonymous objects so for operationLabel (this is only assuming your not going to use the JLabels later):</p>\n\n<pre><code>add(new JLabel(\"YOU HAVE PERFORMED SOME OPERATION\", SwingConstants.CENTER), BorderLayout.SOUTH);\n</code></pre>\n\n<p>However I am going to suggest that you move the JTextFields to global variables. Based on what I'm assuming you have to do with this calculator you are going to want the JTextFields to be accessible to everything.\nHere is my revision of your code:</p>\n\n<pre><code>import java.awt.BorderLayout;\nimport java.awt.FlowLayout;\nimport java.awt.GridLayout;\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\nimport javax.swing.SwingConstants;\n\npublic final class Calculator extends JFrame\n{\n private JTextField operandOneText;//these get initialized in buildOperandPanel() method which is called in the constructor\n private JTextField operandTwoText;\n private JTextField answerText;\n\n //constructor to initialise the frame and add components into it\n public Calculator()\n {\n super(\"Clancy's Calculator\");\n setLayout(new BorderLayout(5, 10));\n setResizable(false);\n setSize(370, 200);\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n\n add(buildOperatorPanel(), BorderLayout.NORTH);\n add(buildOperandPanel(), BorderLayout.CENTER);\n add(new JLabel(\"YOU HAVE PERFORMED SOME OPERATION\", SwingConstants.CENTER), BorderLayout.SOUTH);\n\n pack();\n }\n\n //method builds and returns operatorPanel\n public JPanel buildOperatorPanel()\n {\n JPanel operatorPanel = new JPanel();//JPanels are FlowLayout by default\n\n JButton[] buttons = new JButton[4];\n String[] buttonNames = {\"+\", \"-\", \"/\", \"*\"};\n for(int i = 0; i &lt; buttons.length; i++)\n {\n buttons[i] = new JButton(buttonNames[i]);//the array of JButtons\n //buttons[i].addActionListener(yourActionListener)//for whenever you add event handling\n operatorPanel.add(buttons[i]);\n }\n return operatorPanel;\n }\n\n //method builds and returns operandPanel\n public JPanel buildOperandPanel()\n {\n JPanel operandPanel = new JPanel();\n operandPanel.setLayout(new GridLayout(3, 2, 5, 5));\n\n //Initialize TEXT FIELDS\n operandOneText = new JTextField(); //retrieves one operand\n operandTwoText = new JTextField(); //retrieves another operand\n answerText = new JTextField(); //displays answer\n\n answerText.setEditable(false); //ensure the answer field is not editable\n\n operandPanel.add(new JLabel(\"Enter the first Operand: \"));\n operandPanel.add(operandOneText);\n operandPanel.add(new JLabel(\"Enter the second Operand: \"));\n operandPanel.add(operandTwoText);\n operandPanel.add(new JLabel(\"ANSWER: \"));\n operandPanel.add(answerText);\n\n return operandPanel;\n }\n\n /** main method */\n public static void main(String[] args)\n {\n new Calculator();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T03:58:38.000", "Id": "28767", "ParentId": "28721", "Score": "1" } }, { "body": "<p>Good feedback by user27517. I want to add one thing, which is to use <a href=\"http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingUtilities.html#invokeLater%28java.lang.Runnable%29\" rel=\"nofollow noreferrer\"><code>SwingUtilities.invokeLater()</code></a> in the main method:</p>\n\n<pre><code>public static void main(String[] args) \n{\n SwingUtilities.invokeLater(new Runnable() \n {\n public void run() \n {\n new Calculator();\n }\n });\n}\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/3551542/swingutilities-invokelater-why-is-it-neded\">Why it's needed</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-20T05:04:05.897", "Id": "29976", "ParentId": "28721", "Score": "0" } }, { "body": "<p>One of the reasons for removing global variables is to limit the tight coupling between pieces of an application. For example, if you reduce the coupling between the computation of the Calculations and the input and display of the operands and results, it would be easier to adapt your code for calculations to Web based application without rewriting and introducing new bugs in the calculations code.</p>\n\n<p>In your case I would like to see a clearly defined 'interface', based only upon very primitive objects like strings or integers, between the Users inputs and the Calculation engine code.</p>\n\n<p>So instead of referring to a global <code>JTextField.Text</code> to get an operand, the Calculations engine has a function that accepts a <code>String</code> and only a <code>String</code>. Then you have a small piece that says <code>CalculatePlus(oJTextFieldOperandOne.Text)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-20T05:57:54.737", "Id": "29978", "ParentId": "28721", "Score": "1" } }, { "body": "<p>First a bit of terminology. According to the <a href=\"https://en.wikipedia.org/wiki/Global_variable\" rel=\"nofollow\">Wikipedia definition</a>, your program does not contain any global variables. The <code>JButton</code>s and <code>JPanel</code>s that I think you are asking about are <em>member variables</em> of the <code>Calculator</code> class. That said, it is reasonable to ask if you can get rid of those variables. There is a rule of thumb that variables should be scoped as narrowly as possible, and this is one way of applying that.</p>\n\n<p>Member variables are part of an object's state, and are accessible from any (non-static) member function. If that is not a requirement for a variable, then it doesn't have to be (and probably shouldn't be) a member variable. Currently, your program just builds the UI, so the existing functionality doesn't require that any of your buttons, panels, etc be accessible from outside the function that creates them and adds them to the GUI. Even when you hook up event handlers for the buttons, that can happen at the same time that they are created and so they don't need to be members.</p>\n\n<p>As you add functionality, you'll find that you need to access certain widgets and it would be convenient to have them as a member. For instance, having the <code>answerText</code> text field available as a member would make it easy to write answers to the screen. And in applications like this there are generally conditions under which some buttons should become disabled; this too is much easier if those buttons are stored as member variables.</p>\n\n<p>In general, the panels and other more structural UI elements (as opposed to functional ones like buttons and text boxes) rarely have reason to be stored as members. But every rule has exceptions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-04T05:32:07.930", "Id": "109733", "ParentId": "28721", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T16:55:03.983", "Id": "28721", "Score": "1", "Tags": [ "java", "swing", "gui" ], "Title": "Eliminating global variables in GUI program" }
28721
<p>I wrote this code to read text of a file and use it to initialize objects and place them in a multi-tree data structure. The multi-tree has the base node as an object called <code>theTree</code>, which has an <code>ArrayList</code> that contains a bunch of objects called <code>Party</code>. Each <code>Party</code> has an <code>ArrayList</code> that contains a <code>Creature</code>. Each creature has 3 <code>ArrayList</code>s: <code>artifacts</code>, <code>treasures</code>, and <code>jobs</code>, which contain items of those types.</p> <p><a href="https://i.stack.imgur.com/EdRcp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EdRcp.png" alt="enter image description here"></a></p> <p>This is a sample of the .txt I'm scanning:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>// Parties format: // p:&lt;index&gt;:&lt;name&gt; p : 10000 : Crowd p : 10001 : Band ... // Creatures format: // c:&lt;index&gt;:&lt;type&gt;:&lt;name&gt;:&lt;party&gt;:&lt;empathy&gt;:&lt;fear&gt;:&lt;carrying capacity&gt;[:&lt;age&gt;:&lt;height&gt;:&lt;weight&gt;] c : 20000 : Gnome : Rupert : 10000 : 91 : 30 : 149 : 176.73 : 206.23 : 31.15 c : 20001 : Magician : Delmar : 10000 : 49 : 31 : 223 : 226.37 : 181.93 : 438.56 ... // Treasures format: // t:&lt;index&gt;:&lt;type&gt;:&lt;creature&gt;:&lt;weight&gt;:&lt;value&gt; // creature = 0 means noone is carrying that treasure at the moment t : 30000 : Marks : 20000 : 291.8 : 82 t : 30001 : Chest : 20001 : 82.8 : 66 ... // Artifacts format: // a:&lt;index&gt;:&lt;type&gt;:&lt;creature&gt;[:&lt;name&gt;] a : 40000 : Stone : 20000 : Chrysoprase a : 40001 : Stone : 20000 : Onyx ... // Jobs for creatures // measure time in seconds // j:&lt;index&gt;:&lt;name&gt;:&lt;creature index&gt;:&lt;time&gt;[:&lt;required artifact:type&gt;:&lt;number&gt;]* j : 50000 : Get Help : 20000 : 2.00 : Stone : 0 : Potions : 2 : Wands : 1 : Weapons : 1 j : 50001 : Swing : 20000 : 8.00 : Stone : 0 : Potions : 2 : Wands : 1 : Weapons : 2 </code></pre> </blockquote> <p>Here is what I wrote to scan the .txt and send the gathered information to the proper constructors. As you can see I utilize a <code>HashMap</code> to store each object in a spot associated with its index. Each object that belongs to it has a value that matches that index. <code>Creatures</code> have an attribute called <code>party</code>. Its party is equal to the index of what party it belongs to. <code>Treasures</code>, <code>Artifacts</code>, and <code>Jobs</code> have a similar field called <code>creature</code>.</p> <pre class="lang-none prettyprint-override"><code>public static void readFile(){ String [] param; param = new String [30]; int findParty; int findCreature; char x; int u;//used to determine what constructor to call in case some data is missing //HashMap used for an easy way to reference objects during instantiation HashMap&lt; Integer, Assets &gt; gameAssets = new HashMap&lt; Integer, Assets &gt;(); while ( input.hasNextLine () ) { String line = input.nextLine().trim(); Scanner getStat = new Scanner(line).useDelimiter("\\s*:\\s*"); if ( line.length()== 0 || line.charAt(0) == '/' ) continue; while ( getStat.hasNext() ) { u = 0; x = getStat.next().charAt(0); switch ( x ) { case 'p' : for ( int i = 0; i&lt;2; i++){ if (getStat.hasNext() ){ param [i] = getStat.next(); } } Party newParty = new Party( param ); SorcerersCave.theCave.addParty( newParty ); gameAssets.put( newParty.getIndex(), newParty ); continue; case 'c' : Creature newCreature; while ( getStat.hasNext() ){ param [u] = getStat.next(); u++; } if (u == 7){ newCreature = new Creature ( param [0], param [1], param[2], param [3], param[4], param [5], param [6]); }else { newCreature = new Creature ( param ); } findParty = ( newCreature.getParty() );// == index of parent Node in HashMap if (findParty == 0 ) { SorcerersCave.theCave.addCreature( newCreature ); }else { ((Party)gameAssets.get( findParty )).addMember( newCreature ); gameAssets.put( newCreature .getIndex(), newCreature ); } continue; case 't' : for ( int i = 0; i&lt;5; i++){ param [i] = getStat.next(); } Treasure newTreasure = new Treasure ( param ); findCreature = newTreasure.getCreature(); if ( findCreature == 0 ) { SorcerersCave.theCave.addTreasure( newTreasure ); } else { ((Creature)gameAssets.get( findCreature )).addItem( newTreasure ); gameAssets.put( newTreasure.getIndex(), newTreasure ); } continue; case 'a' : while ( getStat.hasNext() ){ param [u] = getStat.next(); u++; } if ( u == 4 ) { Artifact newArtifact = new Artifact( param ); findCreature = newArtifact.getCreature(); ((Creature)gameAssets.get( findCreature )).addArtifact( newArtifact ); gameAssets.put( newArtifact.getIndex(), newArtifact ); } else { Artifact newArtifact = new Artifact ( param [0], param [ 1 ], param[ 2 ]); findCreature = newArtifact.getCreature(); ((Creature)gameAssets.get( findCreature )).addArtifact( newArtifact ); gameAssets.put( newArtifact.getIndex(), newArtifact ); } continue; case 'j' : while ( getStat.hasNext() ) { param[u] = getStat.next(); u++; } Job newJob = new Job ( param,( Creature )(gameAssets.get( Integer.parseInt( param [2] )))); SorcerersCave.theCave.addJob( newJob ); findCreature = newJob.getCreature(); ((Creature)gameAssets.get( findCreature )).addJob( newJob ); newJob.target = ( Creature )(gameAssets.get( findCreature ) ); GameInterface.jobHeight = GameInterface.jobHeight + 1; } } } input.close(); } </code></pre> <p>I turned this in last weekend, got a good grade, but looking back on this method I'm not very proud of it. It's ugly, complicated, and the least readable method I have ever written. For my first time performing a task like this it works, but I would never show this off.</p>
[]
[ { "body": "<p>First off, you should use a more sane indentation style. The line where <code>u</code> is set to <code>0</code> is just crazy :-). I prefer <a href=\"http://en.wikipedia.org/wiki/Indent_style#Variant%3a_1TBS\" rel=\"nofollow\">The One True Brace Style</a>.</p>\n\n<p>Beyond that, the code could benefit from breaking the things that takes place in the switch clause up using method calls:</p>\n\n<pre><code>switch(x) {\n case 'p':\n doSomething();\n continue;\n case 'c':\n doSomethingElse();\n continue;\n[...]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T18:53:53.767", "Id": "28726", "ParentId": "28722", "Score": "1" } }, { "body": "<p>This could benefit from breaking the code down into a number of separate methods to improve readability, however the issue that you will find with code like this is that you end up with lots of parameters on each method to pass the data around.</p>\n\n<p>One effective way to deal with this is through a combination of the <a href=\"http://sourcemaking.com/refactoring/extract-class\" rel=\"nofollow\">Extract Class</a> and <a href=\"http://sourcemaking.com/refactoring/extract-method\" rel=\"nofollow\">Extract Method</a> refactorings as follows:</p>\n\n<ul>\n<li>Extract the <code>readFile</code> function into a separate class, making it a public method on the new class, and having existing call <code>readFile</code> on the new class. </li>\n<li>Start using Extract Method to break down this large method into smaller methods (by introducing private methods in the new class). When extracting the methods, instead of passing variables into the method as a parameter, move the variable to the class level so that it can be shared amongst methods without using parameters.</li>\n</ul>\n\n<p>By doing this, it will become very simple to aggressively apply Extract Method to break the code down into smaller pieces and make it more readable. Furthermore, by encapsulating the code for reading a file into a separate class, it will clean up the code that calls this function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T10:40:06.773", "Id": "28740", "ParentId": "28722", "Score": "1" } } ]
{ "AcceptedAnswerId": "28740", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T17:16:32.473", "Id": "28722", "Score": "2", "Tags": [ "java", "tree" ], "Title": "Initializing a multi-tree data structure" }
28722
<p>I have been watching <a href="http://www.youtube.com/watch?v=aIHAEYyoTUc" rel="nofollow">Alexander Stepanov</a> programming C++ with components and he, as usual, has some strong opinions. I did like one of his assertions that we use regular, semi-regular and fully ordered types. So I decided to pull together a skeleton class (pair in this case) and wonder if there are any valid reasons for using this skeleton or something different. I realise there is no silver bullet and am not looking for one, but I am interested in the basics being programmatically consistent and correct. Alex seemed to loosely suggest that such a start position would be valid.</p> <p>I hope this is a valid question, I think some of the areas of concern are:</p> <ul> <li>Is it valid to refer to class as regular/semiregular/fullyordered? (It's hard to find examples.) </li> <li>Are there strong reasons for non-member <code>friend</code>/non-<code>friend</code> member functions? (I'm thinking here of the <a href="http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197" rel="nofollow">Dr. Dobbs article</a> showing non-member (non-<code>friend</code>) functions improving encapsulation.)</li> <li>Should <code>friend</code> requirements define member/non member functions?</li> <li>Is it a good rule that each of these groups are implemented fully if at least one member of that group is? I.e. <code>==</code> must also be implemented with <code>!=</code> etc. Sort of as an extension to the big 4 or 5 or 6 construction or regular methods :-) </li> </ul> <p><strong>This is C++11 that MSVC 2012 can handle. Clang, gcc etc. can improve this loads, but for now I am using MSVC 2012 as the baseline. <code>friend</code> is not required in these functions. I have included it to try and cover a normal "template" (if I create a template/snippet) for use where there are private data members. My intent is <em>not</em> to use this as a snippet, though.</strong></p> <pre><code>#ifndef MY_CLASS_H #define MY_CLASS_H #include &lt;tuple&gt; #include &lt;utility&gt; template &lt;typename T, typename U&gt; struct MyClass { T first; U second; // semiregular MyClass(const MyClass&amp; other) : first(other.first), second(other.second) {} MyClass(MyClass&amp;&amp; other) : first(std::move(other.first)), second(std::move(other.second)) {} MyClass() : first(), second() {} ~MyClass() {} MyClass&amp; operator=(MyClass other) { swap(*this, other); return *this; } // regular friend bool operator==(const MyClass&amp; lhs, const MyClass&amp; rhs) { return std::tie(lhs.first, lhs.second) == std::tie(rhs.first, rhs.second); } friend bool operator!=(const MyClass&amp; lhs, const MyClass&amp; rhs) { return !operator==(lhs, rhs); } // fully ordered friend bool operator&lt;(const MyClass&amp; lhs, const MyClass&amp; rhs) { return std::tie(lhs.first, lhs.second) &lt; std::tie(rhs.first, rhs.second); } friend bool operator&gt;(const MyClass&amp; lhs, const MyClass&amp; rhs) { return operator&lt;(rhs, lhs); } friend bool operator&lt;=(const MyClass&amp; lhs, const MyClass&amp; rhs) { return !operator&gt;(lhs, rhs); } friend bool operator&gt;=(const MyClass&amp; lhs, const MyClass&amp; rhs) { return !operator&lt;(lhs, rhs); } }; // swap void swap(MyClass&amp; lhs, MyClass&amp; rhs) /* noexcept */ { using std::swap; swap(lhs.first, rhs.first); swap(lhs.second, rhs.second); } #endif // MY_CLASS_H </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T22:17:05.963", "Id": "45113", "Score": "1", "body": "Can you provide a definition of *regular*, *semi-regular* and *fully ordered* types? As it stands now, it's a bit hard to understand your question fully without watching the hour long video." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T23:11:20.403", "Id": "45117", "Score": "0", "body": "@Lstor yes as far as I can tell from Alex. it is semi-regular is construction move and assignment (I added move), regular is equality comparable and fully ordered is < and all associated members to allow stable sort." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T00:32:43.600", "Id": "45127", "Score": "0", "body": "I'm not sure of `std::swap(a, a)` is guaranteed to be safe or not. If not, you should check for self-assignment in `op=()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T00:40:47.397", "Id": "45129", "Score": "0", "body": "@Lstor: Although I've never seen `std::swap()` used in `operator=` before, it got me thinking about private data members. When you modify their declarations, don't you also update `operator=` accordingly? That seems to reduce maintainability, at least the way I'm thinking about it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T01:22:26.880", "Id": "45131", "Score": "0", "body": "His `op=()` takes `rhs` by value. It's normal to take it by `const&`. I'm not even completely sure taking by value is valid, but I presume it is. When taking by value, the swapped object is just a temporary, so destructively changing the values is not harmful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T01:33:52.437", "Id": "45134", "Score": "0", "body": "@Jamal See [this chat room](http://chat.stackexchange.com/rooms/9728/c-code-reviews) regarding maintainability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T09:40:03.210", "Id": "45147", "Score": "0", "body": "@Lstor That's where a move aware swap works well, it can make use of rvalue's saving an extra temporary and if defined correctly should be `noexcept` (again msvc 2012 stops us using this important feature)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T13:48:13.163", "Id": "45159", "Score": "0", "body": "@Lstor It’s valid and recommended. OP’s implementation is idiomatic for `operator=` nowadays." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T14:54:04.760", "Id": "45161", "Score": "0", "body": "@KonradRudolph Thanks for the insight. I guess I should revisit the basics to see what's changed and what I need to unlearn." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T10:43:09.150", "Id": "45307", "Score": "0", "body": "@Lstor, the operator= by-value implementation is called the [\"copy&swap idiom\"](http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom)" } ]
[ { "body": "<p>It is kind of hard to tell what you're really asking. Without knowing what you're asking, it's hard to provide a helpful and meaningful answer. I will try regardless. Feel free to point me in the right direction if I'm missing the point.</p>\n\n<hr>\n\n<blockquote>\n <p><em>Is it valid to refer to class as regular/semiregular/fully ordered?</em></p>\n</blockquote>\n\n<p>While I'm not familiar with the terminology, the distinctions are useful. These classifications let you reason about a class. For example, <code>std::list&lt;T&gt;::sort()</code> requires that <code>operator&lt;</code> is defined for <code>T</code>. This is part of what Java and C# interfaces and the suggested C++ <em>concepts</em> feature is about. Note that they aren't necessarily accumulative: A type can be \"fully ordered\" without being \"semi-regular\".</p>\n\n<p>However, I can't see a good reason for sorting types into <em>only</em> these categories. Stepanov may have some deeper insight here.</p>\n\n<hr>\n\n<blockquote>\n <p><em>Are there strong reasons for non-member</em> <code>friend</code><em>/non-</em><code>friend</code> <em>member functions?</em></p>\n</blockquote>\n\n<p>Like Scott Meyers points out in the article you link to, non-member non-<code>friend</code>functions improve encapsulation, which leads to looser coupling. (Looser coupling in turn leads to better complexity handling, replaceable components, more testable interfaces and so on. These are <em>good things</em>.)</p>\n\n<p>Regarding non-member <code>friend</code> functions, I personally consider them a code smell. It doesn't <em>necessarily</em> mean that the code is dirty, but in most cases you don't want <code>friend</code>s. (<em>Even without</em> <code>friend</code><em>s, you can still</em> <code>throw party;</code><em>!</em>) Declaring a <code>friend</code> breaks encapsulation and leads to tighter coupling, which is the opposite of what we want.</p>\n\n<p>(If you do have <code>friend</code>s, make sure they interact with an interface (i.e. member function) and not directly with private variables/implementation details.)</p>\n\n<hr>\n\n<blockquote>\n <p><em>Should</em> <code>friend</code> <em>requirements define member/non-member functions?</em></p>\n</blockquote>\n\n<p>I am reading the question as: <em>\"Should functions that need to be declared <code>friend</code> be member functions instead?\"</em></p>\n\n<p>For functions that are <em>not</em> part of the class' public interface, the answer is <strong>yes, definitely</strong>. They should be <code>private</code> member functions.</p>\n\n<p>For functions that <em>are</em> part of the public interface: Unless you have a specific reason to make that function non-member, <strong>it should be a member function</strong>. The point Scott Meyers is making, however, is this: If the function can use the class' public interface instead of being non-member <code>friend</code> or a member function, it should do so: It should be a non-member, non-<code>friend</code> function that interacts with the type through the type's public interface.</p>\n\n<p>My basic guideline is this: <strong>Can the function make use of only the public interface? Then make it non-member, non-<code>friend</code>. If not, make it a member function.</strong> However, <strong>don't</strong> extend the public interface <em>more than otherwise necessary</em> just to allow a function to be non-member, non-<code>friend</code>. If you have to extend the public interface for just a single function, then that function should probably be a member function instead.</p>\n\n<hr>\n\n<blockquote>\n <p>Is it a good rule that each of these groups are implemented fully if at least one member of that group is?</p>\n</blockquote>\n\n<p>When defining one of assignment operator, destructor or copy constructor, <a href=\"http://en.wikipedia.org/wiki/Rule_of_three_%28C++_programming%29\" rel=\"nofollow\">the Rule of Three</a> comes into play and you should probably define the others.</p>\n\n<p>For the categories Stepanov talks about: <strong>Yes, if you implement one part of the groups of operators, you should probably implement the others.</strong> This is because you should follow <a href=\"https://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"nofollow\">the Principle of Least Astonishment</a>. Users of a type expect that if you can say <code>a == b</code>, then you should be able to say <code>a != b</code> as well.</p>\n\n<p>The exception is what he refers to as <em>regular</em>: A type that is constructable may not need to be copyable or movable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T09:23:22.333", "Id": "45143", "Score": "0", "body": "Thanks for that, a great response to a wide question really. I have a couple of suggestions. I don't think Stepanov suggests only these types but for generic programming like he does it he makes great use of associativity and commutativity and these groups perhaps make sense there. I agree with the friend issues with one query, if a function can only be useful for a public interface then why not include it in the object (if it can never be useful outside it for other objects). I know Stepanov has many issues with some of Scott Meyers views, not sure about this one. cont." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T09:31:46.333", "Id": "45145", "Score": "0", "body": "I am also not sure these groups are not accumulative or the regular types are different (group of three/4/5 etc.) it seems to me these should all be declared, even if declared private (or better =delete or default or defined later hand crafted). I think this also satisfies the rule of no astonishment (an object assigned that was never meant to etc.). It also makes programer intent clear and not rely on what a compiler default creates or not (msvc has some weird broken rules here with move for instance)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T10:24:44.017", "Id": "45148", "Score": "0", "body": "If I understand you correctly: If a function can only ever be useful for the class itself, it should probably not even be part of the class' public interface. And, like you say, if a type is not meant to be assignable, then you would have to hide (or `= delete`) its assignment operator and so on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T11:58:12.330", "Id": "45149", "Score": "0", "body": "Yes, kinda :-) I mean if a method is public, but only applicable to the object itself i.e. if we had a prime object that is only prime numbers (so ++p would go to next prime etc.) and we had a member PrimePosition() that returned the position of the current prime or perhaps just to make it more clear a method PrimePosition(Prime p); that returned the position of the prime, then even as a non member non friend this would be floating around the code somewhere outside the object and of no use to any other object. In this case is there a good reason not to have it as a member ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T12:00:12.843", "Id": "45150", "Score": "0", "body": "I think in that case it should be a `private` member function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T12:00:52.763", "Id": "45151", "Score": "0", "body": "Even though it would be useful for clients to call it ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T12:03:59.643", "Id": "45152", "Score": "0", "body": "If it's useful for clients to call it, then it should be part of the public interface, which means that it should be a non-member, non-`friend` unless it needs special access. It wouldn't be \"floating around\" -- normally it would be kept in the same namespace and translation unit as the class it belongs to." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T12:05:17.780", "Id": "45153", "Score": "0", "body": "I am assuming in this case this Prime method could iterate through primes it calculates internally, so not possible, it's only an example. Somebody may say I want to know which position 17 is in the list of primes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T12:06:30.157", "Id": "45154", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9733/discussion-between-lstor-and-dirvine)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T12:08:07.243", "Id": "45155", "Score": "0", "body": "this is exactly the point, I cannot see how having it external to the class would buy anything as it should be part of the object and logically would be in both cases, but external seems dijointed. I am pretty sure I can put this down to a style preference perhaps, so I won't pursue it :-) Your opinion seems to be held by the majority and more likely valid." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T00:07:03.860", "Id": "28739", "ParentId": "28723", "Score": "2" } } ]
{ "AcceptedAnswerId": "28739", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T18:07:40.800", "Id": "28723", "Score": "5", "Tags": [ "c++", "c++11" ], "Title": "Is this a valid and correct skeleton class/struct" }
28723
<p>My biggest problem is attempting to remove a client when the "disconnect" button is hit. It doesn't work properly, and I'm not sure if my approach is best: sending out a list of all the current users to the clients.</p> <p>Any major logic/coding flaws and any suggestions for improvement would also be welcome.</p> <p><strong>Server class:</strong> </p> <pre><code>import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.util.ArrayList; import java.util.Collections; public class Server { static ArrayList&lt;String&gt; users = new ArrayList&lt;String&gt;(); static ArrayList&lt;PrintWriter&gt; outG = new ArrayList&lt;PrintWriter&gt;(); static int port=4444; // ip address: 192.168.0.104 public static void main(String[] args) throws IOException { Collections.synchronizedList(users); ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(port); System.out.print("success"); } catch (IOException e) { System.err.println("Could not listen on port: "+port); System.exit(1); } try { while(true){ Thread thread = new Thread(new UserThread(serverSocket.accept())); thread.start(); } } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } serverSocket.close(); } } </code></pre> <p><strong>User Thread (when a client tries to connect):</strong></p> <pre><code> import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; public class UserThread extends Server implements Runnable{ private Socket socket = null; String message=""; String name=""; String id=""; public UserThread(Socket sock){ this.socket=sock; } @Override public void run() { try { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); addWriter(outG,out); boolean temp2=true; while(temp2){ boolean temp3=true; String name = readIn(in,true); for(int i=0;i&lt;getArraySize(users);i++){//trying to make sure that one client doesnt if(getArray(users,i).equals(name)){//enter a name that another already typed in sendOut(out,"no",true,false,false); temp3=false; i=getArraySize(users); } } if(temp3){ sendOut(out,"yes",true,false,false); addArray(users,name); temp2=false; } } for(int i=0;i&lt;getWriterSize(outG);i++){//sending to all clients a list of all the clients sendOut(outG.get(i),"",false,true,false); } while (true) { readIn(in,false); if(name.equals("bye")){ for(int i=0;i&lt;getWriterSize(outG);i++){ sendOut(outG.get(i),"",false,true,false); } removeArray(users,id); removeoutG(outG,id); break; } int index=search(id); sendOut(outG.get(index),"",false,false,true); message=null; name=null; id=null; } out.close(); in.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } public int search(String name){ for(int i=0;i&lt;getArraySize(users);i++){ if(getArray(users,i).equals(name)){ return i; } } return -1; } public /*synchronized*/ void sendOut(PrintWriter out,String item,boolean init,boolean sendingNames,boolean sendingMessage){ if(init){//not sure if i should syncronize?? out.println(item); out.flush(); } else if(sendingNames){ out.println("~StOp"); out.flush(); out.println(users); out.flush(); } else if(sendingMessage){ out.println(message); out.flush(); out.println(name); out.flush(); out.flush(); } } public /*synchronized*/ String readIn(BufferedReader in, boolean one){ if(one){ try { return in.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else{ try { message= in.readLine(); name= in.readLine(); id= in.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } public /*synchronized*/ String getArray(ArrayList&lt;String&gt;users,int i){ return users.get(i); } public /*synchronized*/ void removeArray(ArrayList&lt;String&gt;users,String name){ users.remove(name); } public /*synchronized*/ void removeoutG(ArrayList&lt;PrintWriter&gt;users,String name){ int index=search(name); outG.remove(index); } public /*synchronized*/ int getArraySize(ArrayList&lt;String&gt;users){ return users.size(); } public /*synchronized*/ int getWriterSize(ArrayList&lt;PrintWriter&gt;out){ return out.size(); } public /*synchronized*/ void addArray(ArrayList&lt;String&gt;users,String name){ users.add(name); } public /*synchronized*/ void addReader(ArrayList&lt;BufferedReader&gt;inG,BufferedReader r){ inG.add(r); } public /*synchronized*/ void addWriter(ArrayList&lt;PrintWriter&gt;outG,PrintWriter p){ outG.add(p); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T11:00:48.753", "Id": "45243", "Score": "1", "body": "This code could use much more advice; but you should implement all of @palacsint's suggestions first, to make other problems _operable_." } ]
[ { "body": "<p>(It's not a complete review, just a few random notes.)</p>\n\n<ol>\n<li><p><code>ArrayList&lt;...&gt;</code> reference types should be simply <code>List&lt;...&gt;</code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p>\n\n<pre><code>private static List&lt;String&gt; users = new ArrayList&lt;String&gt;();\n</code></pre></li>\n<li><p><code>Collections.synchronizedList()</code> does not modify the parameter. It returns a new lists which is synchronized, you should use its return value.</p></li>\n<li><p>Instead of the <code>boolean</code> flag of the <code>readIn</code> method (which is hard to read, readers have to check the implementation to know what <code>true</code> and <code>false</code> means) I'd create two methods: a <code>readName</code> and (probably) a <code>readMessage</code>. Then it would be obvious what the called method does. See: Clean Code by Robert C. Martin, Flag Arguments, p41</p></li>\n<li><p>Instead of modifying <code>i</code> (<code>i = getArraySize(users)</code>) to finish the loop you could break it:</p>\n\n<pre><code>for (int i = 0; i &lt; getArraySize(users); i++) {\n if (getArray(users, i).equals(name)) {\n sendOut(out, \"no\", true, false, false);\n temp3 = false;\n break;\n }\n}\n</code></pre></li>\n<li><p>Furthermore, you could replace the whole loop with the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains%28java.lang.Object%29\"><code>List.contains</code></a> method. The Java ecosystem is really big - if you find that you're writing something that could be useful for someone else too (like getting the index of an element from a list) it certainly has been written. Search for a few minutes. If JDK does not have a method for that Google Guava or Apache Commons probably has.</p></li>\n<li><p>Comments like these are hard to modify:</p>\n\n<pre><code>for(int i=0;i&lt;getArraySize(users);i++){//trying to make sure that one client doesnt \n if(getArray(users,i).equals(name)){//enter a name that another already typed in\n</code></pre>\n\n<p>Placing them before the line are easier to maintain: </p>\n\n<pre><code>//trying to make sure that one client doesnt enter a name that another already typed in\nfor(int i=0;i&lt;getArraySize(users);i++){\n if(getArray(users,i).equals(name)){\n</code></pre>\n\n<p>Anyway, comments often could be function names and the commented code could be extracted out to these functions. References: </p>\n\n<ul>\n<li><em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Bad Comments, p67</em>: <em>Don’t Use a Comment When You Can Use a Function or a Variable</em>.</li>\n<li><em>Refactoring</em> by <em>Martin Fowler</em>, <em>Chapter 3. Bad Smells in Code</em>, <em>Long Method</em></li>\n</ul></li>\n<li><p>Variable name like <code>temp2</code>, <code>temp3</code> are hard to understand. For example,<code>temp3</code> could be renamed to <code>userExists</code>, if I'm right. It explains the purpose and helps readers a lot.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T20:16:22.100", "Id": "28755", "ParentId": "28724", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T18:19:57.187", "Id": "28724", "Score": "2", "Tags": [ "java", "server", "client" ], "Title": "Implementing a Java server" }
28724
<p>I need to read <em>n</em> <code>char</code>s from a binary file into a <code>string</code>. Currently, what I do is:</p> <pre><code>static string Read(istream &amp;stream, uint32_t count) { auto bytes = unique_ptr&lt;char[]&gt;(new char[count]); stream.read(bytes.get(), count); return string(bytes.get(), count); } </code></pre> <p>I found the way I deal with the array of <code>char</code>s quite messy. If I used <code>new</code> and <code>delete[]</code> directly, it would make the code messy in another way (I would need to add a local variable for the result). And I'm trying to avoid <code>delete</code> as a general rule.</p> <p>Is there a clear way to write this code? The fact that it uses twice as much memory as it needs is probably not a big deal, but fixing that would be nice too.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T13:51:19.147", "Id": "45160", "Score": "0", "body": "I think this is actually quite clean – albeit low-level – code. Nothing really wrong with it, and it’s probably more efficient than ruds’ implementation, although that’s arguably even cleaner." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T21:48:13.210", "Id": "45205", "Score": "0", "body": "@KonradRudolph: There is no need to be calling new here. Especially since the string object will deal with all that for you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T22:03:40.417", "Id": "45207", "Score": "0", "body": "@Loki Ah true, I’d completely forgotten about C++11’s contiguity requirement." } ]
[ { "body": "<p>First of all, it seems that you've got a <code>using namespace std;</code> somewhere in your code. <a href=\"https://stackoverflow.com/questions/1265039/using-std-namespace\">Don't do that</a>. (<a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">No, really</a>).</p>\n\n<p>Here's a function that should meet your needs.</p>\n\n<pre><code>static std::string Read(std::istream &amp;stream, std::string::size_type count)\n{\n std::string out;\n out.reserve(count);\n std::copy_n(std::istreambuf_iterator(stream), count, std::back_inserter(out));\n return out;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T20:07:19.173", "Id": "45094", "Score": "1", "body": "`uint32_t` should have an `std::` as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T20:12:02.823", "Id": "45095", "Score": "0", "body": "I don't have `using namespace std;` there. Instead, I have `using std::uint32_t;\nusing std::unique_ptr;\nusing std::string;\nusing std::istream;` there. It's kind of annoying, but I thought it would be better than writing `std::` everywhere." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T20:13:32.570", "Id": "45096", "Score": "3", "body": "@Jamal You're right. Actually, I've changed it to std::string::size_type, as that's the size class we're interested in." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T20:14:13.293", "Id": "45097", "Score": "0", "body": "@svick I think it's odd to read code with names from `std` but with no `std::` in front. Personal tastes vary, of course." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T20:18:55.903", "Id": "45098", "Score": "0", "body": "Is this going to insert the characters one by one? I worry that doing that would be too slow (the result might be one megabyte or so). (Of course, the proper way to find that out would be to measure it.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T20:21:57.747", "Id": "45099", "Score": "0", "body": "@ruds: Ah, never heard of that (and seems better here, too). Noted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T20:24:04.207", "Id": "45100", "Score": "0", "body": "@svick: Do not quote me on this, but there _may_ be a `std::stringstream` alternative. I don't know how (and if) it would work and whether or not it'll improve optimization." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T20:26:58.600", "Id": "45101", "Score": "0", "body": "@svick As you say, measurement is the key here. The istreambuf_iterator reads from the buffer underlying the istream, so I suspect this will be fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T22:39:23.887", "Id": "45115", "Score": "0", "body": "@Lstor: This is why I love C++11. I just wish I could use more of it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-09T21:31:47.567", "Id": "222401", "Score": "0", "body": "IMPORTANT. This example may not work properly for count = 0. The standard says an istreambuf_iterator may read the first character during construction. At least I observed such behavior with g++-4.8. To fix the code above, just skip copying if count == 0." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T19:58:54.133", "Id": "28731", "ParentId": "28727", "Score": "8" } }, { "body": "<p>Why not:</p>\n\n<pre><code>static string Read(istream &amp;stream, uint32_t count)\n{\n std::string result(count, ' ');\n stream.read(&amp;result[0], count);\n\n return result;\n}\n</code></pre>\n\n<p>Though not strictly C++03 compatible that is easily validated. One of the reasons the committee found it easy to add the new constraint in C++11 was that no implementation did not use contiguous memory (Random Access Iterators are a hint).</p>\n\n<p>But a C++03 strict implementation would be:</p>\n\n<pre><code>static string Read(istream &amp;stream, uint32_t count)\n{\n std::vector&lt;char&gt; result(count); // Because vector is guranteed to be contiguous in C++03\n stream.read(&amp;result[0], count);\n\n return std::string(&amp;result[0], &amp;result[count]);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T21:57:19.863", "Id": "45206", "Score": "0", "body": "Yeah, that's certainly better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T22:12:38.803", "Id": "45209", "Score": "3", "body": "Note that this requires C++11 in a non-obvious way (C++03 didn't require that &result[0] worked this way). Otherwise, LGTM." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-21T18:40:42.407", "Id": "158333", "Score": "0", "body": "Depending on your use case, you may want to do `result.resize(stream.gcount());`, in case not all of `count` bytes could be read." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T21:43:21.410", "Id": "28759", "ParentId": "28727", "Score": "21" } } ]
{ "AcceptedAnswerId": "28759", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T18:59:45.980", "Id": "28727", "Score": "14", "Tags": [ "c++", "c++11", "memory-management", "stream" ], "Title": "Reading n chars from stream to string" }
28727
<p>I started learning C# a few months ago (so keep in mind that this is all fairly new to me) and I am working on my first real project (WPF / MVVM). I've received conflicting advice on how to handle my backing data. Currently I have everything held in a singleton class (DataManager); some say that's okay, but others say I should use a different design. So I've come here looking for suggestions on how to do this in an efficient way that will serve me well as the project progresses. </p> <p>For the sake of getting the best possible answer, I'm going to post a good bit of my code. Everything is very basic at the moment; I just want to get a good foundation before I go too much further. Once that happens I'll make this more elaborate. I don't think it's relevant, so I've decided not to post the ViewModel code. If you would like to see it, let me know. So...</p> <p>My DataManager class, where master lists of all major types are contained (my ViewModel's properties reference the data contained in this class):</p> <pre><code>class DataManager { private static DataManager _data; private ObservableCollection&lt;Adventurer&gt; _adventurers = new ObservableCollection&lt;Adventurer&gt;(); private ObservableCollection&lt;Expedition&gt; _expeditions = new ObservableCollection&lt;Expedition&gt;(); private ObservableCollection&lt;Guild&gt; _guilds = new ObservableCollection&lt;Guild&gt;(); private ObservableCollection&lt;Worker&gt; _workers = new ObservableCollection&lt;Worker&gt;(); public static DataManager Data { get { if (_data == null) { _data = new DataManager(); } return _data; } } public Date GameDate { get; set; } public ObservableCollection&lt;Adventurer&gt; Adventurers { get { return _adventurers; } } public ObservableCollection&lt;Expedition&gt; Expeditions { get { return _expeditions; } } public ObservableCollection&lt;Guild&gt; Guilds { get { return _guilds; } } public ObservableCollection&lt;Worker&gt; Workers { get { return _workers; } } } </code></pre> <p>My models for Workers and Adventuers:</p> <pre><code>interface IPerson { Gender Gender { get; set; } string FirstName { get; set; } string LastName { get; set; } } class Adventurer : IPerson { public Adventurer() { CreateAdventurer(); } public Gender Gender { get; set; } public Guild Employer { get; set; } public int Defense { get; set; } public int ID { get; set; } public int Salary { get; set; } public int Strength { get; set; } public string FirstName { get; set; } public string LastName { get; set; } private void CreateAdventurer() { this.Gender = ModelUtilities.RandomGender(); Employer = null; Defense = ModelUtilities._rand.Next(21); ID = DataManager.Data.Adventurers.Count; Salary = ModelUtilities._rand.Next(21); Strength = ModelUtilities._rand.Next(21); ModelUtilities.RandomName(this); } } class Worker : ObservableObject, IPerson { public Worker() { CreateWorker(); } public Gender Gender { get; set; } public Guild Employer { get; set; } public int ID { get; set; } public int Salary { get; set; } public int Skill { get; set; } public string FirstName { get; set; } public string LastName { get; set; } private void CreateWorker() { this.Gender = ModelUtilities.RandomGender(); Employer = null; ID = DataManager.Data.Workers.Count; Salary = ModelUtilities._rand.Next(21); Skill = ModelUtilities._rand.Next(21); ModelUtilities.RandomName(this); }  } </code></pre> <p>My Guild model:</p> <pre><code>class Guild { public Guild() { CreateGuild(); FilterAdventurers(); FilterWorkers(); } public ICollectionView Adventurers { get; set; } public ICollectionView Workers { get; set; } public int Gold { get; set; } public int ID { get; set; } public string Name { get; set; } private void CreateGuild() { Gold = 5000; ID = DataManager.Data.Guilds.Count; Name = "Guild1"; Adventurers = new CollectionViewSource { Source = DataManager.Data.Adventurers }.View; Workers = new CollectionViewSource { Source = DataManager.Data.Workers }.View; } private void FilterAdventurers() { Adventurers.Filter = a =&gt; { Adventurer adventurer = a as Adventurer; if (a == null) return false; return adventurer.Employer == this; }; } private void FilterWorkers() { Workers.Filter = w =&gt; { Worker worker = w as Worker; if (w == null) return false; return worker.Employer == this; }; } } </code></pre> <p>My Expedition model:</p> <pre><code>class Expedition { public Expedition() { CreateExpedition(); } public bool Available { get; set; } public Guild Owner { get; set; } public int Difficulty { get; set; } public int ID { get; set; } public int Reward { get; set; } public string Name { get; set; } private void CreateExpedition() { Available = true; Owner = null; Difficulty = ModelUtilities._rand.Next(21); ID = DataManager.Data.Expeditions.Count; Reward = ModelUtilities._rand.Next(21); Name = string.Format("Expedition {0}", ID); } } </code></pre> <p>And last, the class that initializes all of the data:</p> <pre><code>static class Initialize { public static void NewGame() { DataManager.Data.GameDate = new Date(1, 0); DataManager.Data.Guilds.Add(new Guild()); for (int i = 0; i &lt; 10; i++) { DataManager.Data.Adventurers.Add(new Adventurer()); } for (int i = 0; i &lt; 10; i++) { DataManager.Data.Workers.Add(new Worker()); } for (int i = 0; i &lt; 10; i++) { DataManager.Data.Expeditions.Add(new Expedition()); } } } </code></pre> <p>So this is how the data is currently being handled. As I said, I've had some people say that what I'm doing is okay and I've had others tell me to overhaul it. Right now it works, but I'm very interested in knowing what an experienced programmer would suggest I do to handle my backing data to make it more efficient/practical in the long term.</p> <p>As a novice programmer, I know that I have a lot to learn, and I want to learn everything that I can. That said, any advice you could give me would be greatly appreciated. Thanks.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T22:23:15.200", "Id": "45114", "Score": "0", "body": "The DataManager class actually looks more like a 'Game Container' than my notion of 'DataManager'. Also, the various 'CreateXXX' methods which are marked private would be more amenable to an abstract factory pattern that took advantage of generics" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T22:57:56.483", "Id": "45116", "Score": "0", "body": "DataManager is just the first name that I thought of. Regardless of the name, does the structure as a whole look okay? Are there any major modifications that I could to to make it more practical?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T23:54:15.313", "Id": "45119", "Score": "0", "body": "You're exposing the collections for add/remove modifications by external classes. Is that your intent?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T23:55:54.287", "Id": "45120", "Score": "0", "body": "My intent is to have them be globally accessible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T00:00:15.840", "Id": "45121", "Score": "0", "body": "Globally accessible versus globally modifiable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T00:07:19.717", "Id": "45122", "Score": "0", "body": "I would like to be able to access the data from anywhere, but I suppose I could localize modification to a single class that adds or removes items from the collections." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T00:13:09.033", "Id": "45123", "Score": "0", "body": "You can simply make them visible to external classes as read only collections, no?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T00:18:44.893", "Id": "45124", "Score": "0", "body": "When I make the collections readonly, I get errors saying \"The modifier 'readonly' is not valid for this item\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T00:20:42.673", "Id": "45125", "Score": "0", "body": "No, setting the access modifier to read only on an Observable Collection does not prevent external classes from making modifications to it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T00:26:14.737", "Id": "45126", "Score": "0", "body": "I apologize for not understanding your suggestions; I am still learning. Can you elaborate on your suggestion?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T00:38:51.720", "Id": "45128", "Score": "0", "body": "best practices when exposing a collection... http://geekswithblogs.net/Patware/archive/2013/05/19/152957.aspx There's a more worrying potential bug in your code's decision to let composition win out over inheritance. I'll look at that one also." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T01:27:32.917", "Id": "45132", "Score": "0", "body": "+1 for a great question and enjoyed looking over your stuff too" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T01:33:52.457", "Id": "45133", "Score": "0", "body": "With a `ReadOnlyObservableCollection`, can items be added to the collection elsewhere in my code? I would prefer to maintain that functionality." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T01:52:16.783", "Id": "45135", "Score": "0", "body": "you add/delete to the private backing field which is of type ObservableCollection. And that's best sited in your model. Consumers cannot add/delete so design integrity goes up, which means code quality goes up :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T01:53:55.730", "Id": "45136", "Score": "0", "body": "Thanks. I have to run for now but I'll look into this when I can. I appreciate your help!" } ]
[ { "body": "<p>Following the lengthy commentary on the question, there's one additional point that qualifies as an actual 'answer'. Your classes are built up using the composition model which is fine. But since an Adventurer contains an instance of Guild, what happens to the Guild instance if the Adventurer is destroyed? So you'll need to test for (or be aware of) unintended side-effects that may cause an unpredictable state.</p>\n\n<p>Along another line, consider this scaled-down implementation of Guild...</p>\n\n<pre><code>public class Guild\n{\n public string Name { get; set; }\n}\n</code></pre>\n\n<p>And here's a method to run using it...</p>\n\n<pre><code> public void Scenario1()\n {\n ObservableCollection&lt;Guild&gt; guilds = new ObservableCollection&lt;Guild&gt; ();\n for (int i = 0; i &lt; 20; i++)\n {\n Guild g1 = new Guild { Name = \"Meistersingers\" }; \n if (!guilds.Contains(g1))\n {\n guilds.Add(g1);\n }\n }\n int uniqueGuilds = guilds.ToList().Distinct().Count();\n Console.WriteLine(@\"Unique guilds: \" + uniqueGuilds);\n }\n</code></pre>\n\n<p>And the output is...</p>\n\n<pre><code>Unique guilds: 20\n</code></pre>\n\n<p>...because the 'Contains' method for collections uses the 'Equals' method on object. And object.Equals simply checks memory addresses. Lots of developers who are starting out expect 'Contains' to use value semantics, and thus start thinking that 'Contains' is buggy when their classes start to grow and use complex relationships.</p>\n\n<p>Now for an alternative, look at this scaled-down version of the Guild class...</p>\n\n<pre><code>public class Guild2 : IEquatable&lt;Guild2&gt;, IComparable&lt;Guild2&gt;\n{\n public string Name { get; set; }\n public bool Equals(Guild2 other)\n {\n return Name == other.Name;\n }\n public int CompareTo(Guild2 other)\n {\n return String.Compare(Name, other.Name, System.StringComparison.Ordinal);\n }\n}\n</code></pre>\n\n<p>And against the same function as before...</p>\n\n<pre><code>public void Scenario2()\n{\n ObservableCollection&lt;Guild2&gt; guilds = new ObservableCollection&lt;Guild2&gt;();\n for (int i = 0; i &lt; 20; i++)\n {\n Guild2 g1 = new Guild2 { Name = \"Meistersingers\" };\n if (!guilds.Contains(g1))\n {\n guilds.Add(g1);\n }\n }\n int uniqueGuilds = guilds.ToList().Distinct().Count();\n Console.WriteLine(@\"Unique guilds: \" + uniqueGuilds);\n}\n</code></pre>\n\n<p>And the output is...</p>\n\n<pre><code>Unique guilds: 1\n</code></pre>\n\n<p>...this is more in line with expectations. So consider inheriting from IEquatable and IComparable so as to avoid bugs when your library gets large and complex. Why? Because the collections 'Contains' method will look to see if you have implemented IEquatable and use it instead of the same method on 'object'. Polymorphism is your friend.</p>\n\n<p>Lastly, the three or four 'CreateXXX' methods are better situated in an abstract factory pattern.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T15:14:05.517", "Id": "28744", "ParentId": "28728", "Score": "1" } } ]
{ "AcceptedAnswerId": "28744", "CommentCount": "15", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T19:07:43.937", "Id": "28728", "Score": "1", "Tags": [ "c#", "mvvm" ], "Title": "Efficient strucure for backing data in MVVM" }
28728
<p>What are your guys thoughts on the following jQuery plugin?</p> <pre><code>$.fn.with = function( fn ) { // Verify function if( jQuery.isFunction( fn ) ) { var temp = fn.call(this); // Check fn for valid response if( temp instanceof jQuery ) { return temp; } } return this; }; </code></pre> <p>I believe this method to very useful as it allows for better chaining, thus increasing flow. Before developing this method, I found myself creating a lot of temporary variables just to preform a conditional test.</p> <p>Examples would be in cases where <code>.hasClass</code> and <code>.is()</code> are used:</p> <pre><code>// Example From: http://api.jquery.com/is/ $("ul").click( function( event ) { var $target = $(event.target); if ( $target.is("li") ) { $target.css("background-color", "red"); } }); </code></pre> <p>However, using the proposed <code>.with()</code> method, the code can become cleaner:</p> <pre><code>$("ul").click( function( event ) { $(event.target).with(function() { if( this.is("li") ) { this.css("background-color", "red"); } }) }); </code></pre> <p>Note: If the function processed by <code>.with()</code> returns an instance of jQuery it, instead of the calling instance, will be returned into the chain.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T16:19:08.380", "Id": "45171", "Score": "2", "body": "The resulting code is an order of magnitude uglier, even taking an extra indentation level." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-30T22:20:23.913", "Id": "46087", "Score": "0", "body": "I would suggest you submit that to jQuery. It seems like a viable method and might be added to the core." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-16T15:43:12.007", "Id": "47292", "Score": "0", "body": "Do you know what the process is for that or a site for reference? I've not found anything at www.jquery.com." } ]
[ { "body": "<h1>The code</h1>\n\n<p>I'm not quite sure of the purpose of this part:</p>\n\n<pre><code>if( temp instanceof jQuery ) {\n return temp;\n}\n</code></pre>\n\n<p>This seems to be related to the idea of chaining methods, but it prevents me from doing something like this:</p>\n\n<pre><code>var width = $('ul').show().with(function() {\n return this.width();\n}\n</code></pre>\n\n<p>Also, when chaining, there is no benefit of only returning the result if it is an instance of jQuery, because if you try to chain methods and you return nothing from with <code>with()</code>, it'll result in \"undefined is not a function\".</p>\n\n<p>You also check if the <code>fn</code> passed to <code>with()</code> actually is a function. I wouldn't do that, since this will silently ignore a wrong parameter to <code>with()</code>, which is <em>very</em> hard to debug. Instead you can just disable the check, or even better do something like this:</p>\n\n<pre><code>if(jQuery.isFunction(fn)) {\n [...]\n} else {\n throw \"Parameter passed to `with()` was not a function: \" + fn;\n}\n</code></pre>\n\n<h1>The idea in general</h1>\n\n<p>I have to side with @Esailija here. While there won't be a noticeable performance difference in any modern browser (if you omit the <code>instanceof</code> check), I can't see the benefit of replacing a local variable with an extra level of unnecessary indentation. But that is obviously a purely personal opinion.</p>\n\n<p>Aside from the extra level of indentation, I find the code using <code>with()</code> harder to read, since it removes context from the individual lines. I would prefer something like</p>\n\n<pre><code>$targetEl.css(\"background-color\", \"red\");\n</code></pre>\n\n<p>to </p>\n\n<pre><code>this.css(\"background-color\", \"red\");\n</code></pre>\n\n<p>any day, because in the former I don't have to scan the surrounding code to see what \"this\" currently means (which can be hard in JavaScript). Of course this is no concern in a snippet as short as your examples.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T22:49:19.857", "Id": "31023", "ParentId": "28729", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T16:09:02.743", "Id": "28729", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "jQuery .with() to allow better chaining and flow" }
28729
<p>Retrieving an instance of (Default) <code>SharedPreferences</code> and then calling the six methods that may be called to put/get a value gets pretty old pretty quickly, so I wrote this:</p> <pre><code>import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Build; import android.preference.PreferenceManager; import java.util.ArrayList; import java.util.List; import java.util.Set; public final class AccessPreferences { private static final List&lt;Class&lt;?&gt;&gt; CLASSES = new ArrayList&lt;Class&lt;?&gt;&gt;(); static { CLASSES.add(String.class); CLASSES.add(Boolean.class); CLASSES.add(Integer.class); CLASSES.add(Long.class); CLASSES.add(Float.class); CLASSES.add(Set.class); } private AccessPreferences() {} private static SharedPreferences prefs; // TODO: do I need synchronized ? (1) private static synchronized SharedPreferences getPrefs(Context ctx) { if (prefs == null) { prefs = PreferenceManager.getDefaultSharedPreferences(ctx); } return prefs; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) // (5) public static &lt;T&gt; void persist(Context ctx, String key, T value) { @SuppressLint("CommitPrefEdits") final Editor ed = getPrefs(ctx).edit(); if (value == null) { // commit it as that is exactly what the API does - can be retrieved // as anything but if you give get() a default non null value it // will give this default value back ed.putString(key, null); } else if (value instanceof String) ed.putString(key, (String) value); else if (value instanceof Boolean) ed.putBoolean(key, (Boolean) value); // TODO : IS THE ORDER OF FLOAT, INTEGER AND LONG CORRECT ? // (4) else if (value instanceof Integer) ed.putInt(key, (Integer) value); else if (value instanceof Long) ed.putLong(key, (Long) value); else if (value instanceof Float) ed.putFloat(key, (Float) value); else if (value instanceof Set) { if (android.os.Build.VERSION.SDK_INT &lt; Build.VERSION_CODES.HONEYCOMB) { throw new IllegalStateException( "You can add sets in the preferences only after API " + Build.VERSION_CODES.HONEYCOMB); } // (5) // The given set does not contain strings only --&gt; TODO : not my // problem ? probably cause the one who filled it made the mistake (3) // Set&lt;?&gt; set = (Set&lt;?&gt;) value; // if (!set.isEmpty()) { // for (Object object : set) { // if (!(object instanceof String)) // throw new IllegalArgumentException( // "The given set does not contain strings only"); // } // } @SuppressWarnings({ "unchecked", "unused" }) Editor soIcanAddSuppress = ed .putStringSet(key, (Set&lt;String&gt;) value); } else throw new IllegalArgumentException("The given value : " + value + " cannot be persisted"); ed.commit(); } @SuppressWarnings("unchecked") @TargetApi(Build.VERSION_CODES.HONEYCOMB) // (5) public static &lt;T&gt; T retrieve(Context ctx, String key, T defaultValue) { // if the value provided as defaultValue is null I can't get its class if (defaultValue == null) { // if the key (which can very well be null btw) !exist I return null // which is both the default value provided and what Android would // do (as in return the default value) (TODO: test) if (!getPrefs(ctx).contains(key)) return null; // if the key does exist I get the value and.. final Object value = getPrefs(ctx).getAll().get(key); // ..if null I return null if (value == null) return null; // ..if not null I get the class of the non null value. Problem is // that as far as the type system is concerned T is of the type the // variable that is to receive the default value is. So : // String s = AccessPreferences.retrieve(this, "key", null); // if the value stored in "key" is not a String (for instance // `"key" --&gt; true` or `"key" --&gt; 1.2`) a ClassCastException will // occur _in the assignment_ after retrieve returns // TODO : is it my problem ? This : // (2) // SharedPreferences p = // PreferenceManager.getDefaultSharedPreferences(ctx); // int i = p.getInt(KEY_FOR_STRING, 7); // results in a class cast exception as well ! final Class&lt;?&gt; clazz = value.getClass(); // TODO : IS THE ORDER OF FLOAT, INTEGER AND LONG CORRECT ? for (Class&lt;?&gt; cls : CLASSES) { if (clazz.isAssignableFrom(cls)) { try { // I can't directly cast to T as value may be boolean // for instance return (T) clazz.cast(value); } catch (ClassCastException e) { // won't work see : // https://stackoverflow.com/questions // /186917/how-do-i-catch-classcastexception // basically the (T) clazz.cast(value); line is // translated to (Object) clazz.cast(value); which won't // fail ever - the CCE is thrown in the assignment (T t // =) String s = AccessPreferences.retrieve(this, "key", // null); which is compiled as // (String)AccessPreferences.retrieve(this, "key", // null); and retrieve returns an Integer for instance String msg = "Value : " + value + " stored for key : " + key + " is not assignable to variable of given type."; throw new IllegalStateException(msg, e); } } } // that's really Illegal State I guess throw new IllegalStateException("Unknown class for value :\n\t" + value + "\nstored in preferences"); } else if (defaultValue instanceof String) return (T) getPrefs(ctx) .getString(key, (String) defaultValue); else if (defaultValue instanceof Boolean) return (T) (Boolean) getPrefs( ctx).getBoolean(key, (Boolean) defaultValue); // TODO : IS THE ORDER OF FLOAT, INTEGER AND LONG CORRECT ? else if (defaultValue instanceof Integer) return (T) (Integer) getPrefs( ctx).getInt(key, (Integer) defaultValue); else if (defaultValue instanceof Long) return (T) (Long) getPrefs(ctx) .getLong(key, (Long) defaultValue); else if (defaultValue instanceof Float) return (T) (Float) getPrefs(ctx) .getFloat(key, (Float) defaultValue); else if (defaultValue instanceof Set) { if (android.os.Build.VERSION.SDK_INT &lt; Build.VERSION_CODES.HONEYCOMB) { throw new IllegalStateException( "You can add sets in the preferences only after API " + Build.VERSION_CODES.HONEYCOMB); } // (5) // The given set does not contain strings only --&gt; TODO : not my // problem ? probably cause the one who filled it made the mistake // Set&lt;?&gt; set = (Set&lt;?&gt;) defaultValue; // if (!set.isEmpty()) { // for (Object object : set) { // if (!(object instanceof String)) // throw new IllegalArgumentException( // "The given set does not contain strings only"); // } // } return (T) getPrefs(ctx).getStringSet(key, (Set&lt;String&gt;) defaultValue); } else throw new IllegalArgumentException(defaultValue + " cannot be persisted in SharedPreferences"); } } </code></pre> <p>My questions are:</p> <ol> <li>Do I need to retrieve the preferences in a <code>synchronized</code> block (I understand that put/get operations are already synchronized)?</li> <li>When I get a <code>null</code> as a default in the retrieve method, I am not sure I adhere to the generics' contract - there is the possibility of a <code>ClassCastException</code> - but so is there in the original framework. Could I get completely rid of the <code>CLASSES</code> casts and still be as typesafe as Android? See my comments in code.</li> <li>generics' contract part II - if I get a <code>Set</code> as a parameter I believe <em>I do not have to check if it is indeed a <code>Set&lt;String&gt;</code></em> - am I right?</li> <li>The order I check (via <code>instanceof</code> and <code>isAssignableFrom</code>) what kind of number I got is : Integer, Long, Float. Is my order correct? - think of a call like <code>persist(ctx, key, 349857094387593475)</code>. Would completely dropping <code>Integer</code> checks do the trick (and be acceptable)?</li> <li>Do I handle the HONEYCOMB addition of <code>Set&lt;String&gt;</code> right (by throwing an exception if one calls my methods in pre HONEYCOMB build passing a <code>Set</code> in)?</li> </ol> <p>Follow my TODOs in the code for the particular points I make.</p> <p><a href="https://github.com/Utumno/AndroidHelpers/blob/master/src/gr/uoa/di/android/helpers/AccessPreferences.java" rel="nofollow noreferrer">Here</a> is my current solution for anyone interested.</p> <p>Part of this question is answered <a href="https://stackoverflow.com/questions/19610569/android-sharedpreferences-null-keys-values-and-sets-corner-cases">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-01T18:15:06.887", "Id": "143531", "Score": "0", "body": "Your self-answers were deleted because they contained code dumps, not actual reviews. This may be tolerated on SO, but it's not considered an acceptable answer on CR." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-01T23:51:49.587", "Id": "143592", "Score": "0", "body": "@Jamal: Alright - at least though I did reedit the question to clarify the code is my solution as well as to re add the SO link - this SO link is to a question my actual questions here are answered - this was the \"review\" part of my answer (for whoever would actually click it ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-01T23:57:03.407", "Id": "143593", "Score": "0", "body": "Fair enough. I've re-made them as hyperlinks instead of full URLs." } ]
[ { "body": "<p>I'm not too familiar with Android but I've found an issue with the code: both <code>persist</code> and <code>retrieve</code> methods contains the similar if-else chain. You should replace them with polymorphism:</p>\n\n<ul>\n<li><em>Refactoring: Improving the Design of Existing Code</em> by <em>Martin Fowler</em>: <em>Replacing the Conditional Logic on Price Code with Polymorphism</em></li>\n<li><a href=\"http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism\" rel=\"nofollow\">Replace Conditional with Polymorphism</a></li>\n</ul>\n\n<p>To answer some of your questions:</p>\n\n<ul>\n<li><p>(4) The order is not important since there isn't any class (in Java, at least) which <code>instanceof</code> more than one of <code>Long</code>, <code>Integer</code> and <code>Float</code>.</p></li>\n<li><p>(5) If it's invalid input data, I'd throw an exception with a detailed error message to the caller.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T18:00:56.447", "Id": "45178", "Score": "0", "body": "Thanks ! This is not the final - I just left the copy paste for easy ref (they are not exactly same either) - (5) is an android thing - as for 4 if I get `retrieve(ctx, key, 349857094387593475)` will `(value instanceof Integer) == true` ? - that king of thing" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T17:50:22.840", "Id": "28749", "ParentId": "28730", "Score": "4" } }, { "body": "<p>This code is will only work properly if you always use that same <code>Context</code>. <code>getPrefs()</code> caches the <code>SharedPreferences</code> instance for <code>ContextA</code>. But if it is called again with <code>ContextB</code> the value returned was the value retrieved when <code>ContextA</code> was used.</p>\n\n<hr>\n\n<p>Using the <code>synchronized</code> modifier on a method synchronizes the method on the class instance (or the class object for static methods). Any code can also synchronize on these instances, potentially causing deadlocks in code you don't control. You should always synchronize on a private instance that only you control.</p>\n\n<hr>\n\n<p>The huge blocks of comments tightly packed in with the code makes everything hard to read. If you are trying to ask for questions about the code, do not put that inside the code. The code you post should be how it would be in the code base.</p>\n\n<hr>\n\n<p>Don't put all of you if blocks on one line. It makes it harder to read and can cause problems when you need to add in a second line.</p>\n\n<pre><code>else if (defaultValue instanceof Float) return (T) (Float) getPrefs(ctx)\n .getFloat(key, (Float) defaultValue);\n</code></pre>\n\n<p>Here the code is trying to be put on one line, but has to be wrapped. The defeats the whole purpose of trying to one-line the code in the first place. It is best to always put the block on the next line and to always include the curly brackets.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-01T23:44:05.767", "Id": "143591", "Score": "0", "body": "Yes thanks - half agree half disagree - point 1 though is important and IIRC it isn't so - the `PreferenceManager.getDefaultSharedPreferences(ctx);` should return an Application wide singleton. Please verify this - or I will do when I get round to it - do not have android setup anymore - but nice (re: code style including comments etc I have my reasons) - point 2 I was aware (and it is a internal class under my control) but yes - this is a +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-02T04:49:05.583", "Id": "143613", "Score": "0", "body": "While a `Activity` should always have the same `Context`, there is nothing in this code to indicate to someone using it, that it should not be used with multiple `Context`s. I don't know enough about Android to say how you might get a different context withing the same application. But the issue would not be a problem at all if you made the class non-static and passed a Context in as an argument to the constructor. The `SharedPreferences` instance would still be cached and it would be impossible to use the code incorrectly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-01T18:35:59.643", "Id": "79266", "ParentId": "28730", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T19:58:22.893", "Id": "28730", "Score": "5", "Tags": [ "java", "android", "wrapper" ], "Title": "Wrapper around default shared preferences in Android" }
28730
<p>This is a class I wrote for parallelising certain parts of my main codebase. How could this code be improved in terms of making it shorter, more secure, and more efficient?</p> <pre><code>using System; using System.Collections.Generic; using System.Threading; using System.ComponentModel; namespace System.SMP { public static class Parallel { #region Context Structs /// &lt;summary&gt; /// /// &lt;/summary&gt; private struct WhileContext { public Func&lt;Object&gt; ConditionDelegate; public Action WorkerDelegate; public Action WorkerCompleteDelegate; public Int32 WorkerID; public Boolean WorkerThreadSafeExec; public Boolean CompleteThreadSafeExec; } /// &lt;summary&gt; /// /// &lt;/summary&gt; private struct ForContext { public Int32 LoopFrom; public Int32 LoopTo; public Action&lt;Object&gt; WorkerDelegate; public Action WorkerCompleteDelegate; public Int32 WorkerID; public Boolean WorkerThreadSafeExec; public Boolean CompleteThreadSafeExec; } /// &lt;summary&gt; /// /// &lt;/summary&gt; private struct ForEachContext { public Type DataCollectionType; public IEnumerable&lt;object&gt; DataCollection; public Action&lt;object&gt; WorkerDelegate; public Action WorkerCompleteDelegate; public Int32 WorkerID; public Boolean WorkerThreadSafeExec; public Boolean CompleteThreadSafeExec; } #endregion #region Public Spawn Methods public static void SpawnInToWait(Action&lt;object&gt; worker, object param, ref Wait waitObject, String workerName) { if (waitObject == null) throw new ArgumentNullException("waitObject cannot be null"); if (worker == null) throw new ArgumentNullException("worker cannot be null"); Thread thread = new Thread((ParameterizedThreadStart)(worker as Delegate)); thread.IsBackground = true; thread.Name = workerName; waitObject.AddThreadToWaitFor(thread); thread.Start(param); } #endregion #region Public While Methods /// &lt;summary&gt; /// Create a while loop usng &lt;paramref name="condition"/&gt; as a test condition /// &lt;/summary&gt; /// &lt;param name="condition"&gt;Delegate that must return true to continue the loop or false to exit&lt;/param&gt; /// &lt;param name="worker"&gt;Delegate that contains the body of the loop&lt;/param&gt; /// &lt;returns&gt;Wait object&lt;/returns&gt; public static Wait While(Func&lt;Object&gt; condition, Action worker) { return While(condition, worker, null); } /// &lt;summary&gt; /// Create a while loop usng &lt;paramref name="condition"/&gt; as a test condition /// &lt;/summary&gt; /// &lt;param name="condition"&gt;Delegate that must return true to continue the loop or false to exit&lt;/param&gt; /// &lt;param name="worker"&gt;Delegate that contains the body of the loop&lt;/param&gt; /// &lt;param name="workerComplete"&gt;Delegate that is called after each worker has completed&lt;/param&gt; /// &lt;returns&gt;Wait object&lt;/returns&gt; public static Wait While(Func&lt;Object&gt; condition, Action worker, Action workerComplete) { return While(condition, worker, workerComplete, Environment.ProcessorCount); } /// &lt;summary&gt; /// Create a while loop usng &lt;paramref name="condition"/&gt; as a test condition /// &lt;/summary&gt; /// &lt;param name="condition"&gt;Delegate that must return true to continue the loop or false to exit&lt;/param&gt; /// &lt;param name="worker"&gt;Delegate that contains the body of the loop&lt;/param&gt; /// &lt;param name="workerComplete"&gt;Delegate that is called after each worker has completed&lt;/param&gt; /// &lt;param name="workerCount"&gt;Number of workers to spawn&lt;/param&gt; /// &lt;returns&gt;Wait object&lt;/returns&gt; public static Wait While(Func&lt;Object&gt; condition, Action worker, Action workerComplete, Int32 workerCount) { return While(condition, worker, workerComplete, workerCount, false); } /// &lt;summary&gt; /// Create a while loop usng &lt;paramref name="condition"/&gt; as a test condition /// &lt;/summary&gt; /// &lt;param name="condition"&gt;Delegate that must return true to continue the loop or false to exit&lt;/param&gt; /// &lt;param name="worker"&gt;Delegate that contains the body of the loop&lt;/param&gt; /// &lt;param name="workerComplete"&gt;Delegate that is called after each worker has completed&lt;/param&gt; /// &lt;param name="workerCount"&gt;Number of workers to spawn&lt;/param&gt; /// &lt;param name="threadSafeWorker"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static Wait While(Func&lt;Object&gt; condition, Action worker, Action workerComplete, Int32 workerCount, Boolean threadSafeWorker) { return While(condition, worker, workerComplete, workerCount, threadSafeWorker, true); } /// &lt;summary&gt; /// Create a while loop usng &lt;paramref name="condition"/&gt; as a test condition /// &lt;/summary&gt; /// &lt;param name="condition"&gt;Delegate that must return true to continue the loop or false to exit&lt;/param&gt; /// &lt;param name="worker"&gt;Delegate that contains the body of the loop&lt;/param&gt; /// &lt;param name="workerComplete"&gt;Delegate that is called after each worker has completed&lt;/param&gt; /// &lt;param name="workerCount"&gt;Number of workers to spawn&lt;/param&gt; /// &lt;param name="threadSafeWorker"&gt;&lt;/param&gt; /// &lt;param name="threadSafeComplete"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static Wait While(Func&lt;Object&gt; condition, Action worker, Action workerComplete, Int32 workerCount, Boolean threadSafeWorker, Boolean threadSafeComplete) { if (condition == null) return null; if (worker == null) return null; Wait waitObject = new Wait(); Int32 numWorkers = workerCount &gt; 0 ? workerCount : Environment.ProcessorCount; for (Int32 i = 0; i &lt; numWorkers; i++) { SpawnInToWait( _While, new WhileContext() { ConditionDelegate = condition, WorkerDelegate = worker, WorkerCompleteDelegate = workerComplete, WorkerID = i, WorkerThreadSafeExec = threadSafeWorker, CompleteThreadSafeExec = threadSafeComplete }, ref waitObject, "While_Worker_" + i ); } return waitObject; } #endregion #region Private While Methods private static void _While(Object obj) { WhileContext whileCtx = (WhileContext)obj; ThreadSafeCall threadSafeCondition = new ThreadSafeCall(); while (((bool)threadSafeCondition.Call(whileCtx.ConditionDelegate))) { if (whileCtx.WorkerThreadSafeExec) (new ThreadSafeCall()).Call(whileCtx.WorkerDelegate); else whileCtx.WorkerDelegate(); } if (whileCtx.WorkerCompleteDelegate != null) { if (whileCtx.CompleteThreadSafeExec) (new ThreadSafeCall()).Call(whileCtx.WorkerCompleteDelegate); else whileCtx.WorkerCompleteDelegate(); } } #endregion #region Public Do Methods /// &lt;summary&gt; /// Create a do while loop usng &lt;paramref name="condition"/&gt; as a test condition /// &lt;/summary&gt; /// &lt;param name="condition"&gt;Delegate that must return true to continue the loop or false to exit&lt;/param&gt; /// &lt;param name="worker"&gt;Delegate that contains the body of the loop&lt;/param&gt; /// &lt;returns&gt;Wait object&lt;/returns&gt; public static Wait Do(Func&lt;Object&gt; condition, Action worker) { return Do(condition, worker, null, Environment.ProcessorCount); } /// &lt;summary&gt; /// Create a do while loop usng &lt;paramref name="condition"/&gt; as a test condition /// &lt;/summary&gt; /// &lt;param name="condition"&gt;Delegate that must return true to continue the loop or false to exit&lt;/param&gt; /// &lt;param name="worker"&gt;Delegate that contains the body of the loop&lt;/param&gt; /// &lt;param name="workerComplete"&gt;Delegate that is called after each worker has completed&lt;/param&gt; /// &lt;returns&gt;Wait object&lt;/returns&gt; public static Wait Do(Func&lt;Object&gt; condition, Action worker, Action workerComplete) { return Do(condition, worker, workerComplete, Environment.ProcessorCount); } /// &lt;summary&gt; /// Create a do while loop usng &lt;paramref name="condition"/&gt; as a test condition /// &lt;/summary&gt; /// &lt;param name="condition"&gt;Delegate that must return true to continue the loop or false to exit&lt;/param&gt; /// &lt;param name="worker"&gt;Delegate that contains the body of the loop&lt;/param&gt; /// &lt;param name="workerComplete"&gt;Delegate that is called after each worker has completed&lt;/param&gt; /// &lt;param name="workerCount"&gt;Number of workers to spawn&lt;/param&gt; /// &lt;returns&gt;Wait object&lt;/returns&gt; public static Wait Do(Func&lt;Object&gt; condition, Action worker, Action workerComplete, Int32 workerCount) { if (condition == null) return null; if (worker == null) return null; Wait waitObject = new Wait(); Int32 numWorkers = workerCount &gt; 0 ? workerCount : Environment.ProcessorCount; for (Int32 i = 0; i &lt; numWorkers; i++) { SpawnInToWait( _Do, new WhileContext() { ConditionDelegate = condition, WorkerDelegate = worker, WorkerCompleteDelegate = workerComplete, WorkerID = i }, ref waitObject, "Do_Worker_" + i ); } return waitObject; } #endregion #region Private Do Methods private static void _Do(Object obj) { WhileContext whileCtx = (WhileContext)obj; ThreadSafeCall threadSafeCondition = new ThreadSafeCall(); do { (new ThreadSafeCall()).Call(whileCtx.WorkerDelegate); } while ((bool)threadSafeCondition.Call(whileCtx.ConditionDelegate)); if (whileCtx.WorkerCompleteDelegate != null) { (new ThreadSafeCall()).Call(whileCtx.WorkerCompleteDelegate); } } #endregion #region Public For Methods public static Wait For(Int32 from, Int32 to, Action&lt;Object&gt; worker) { return For(from, to, worker, null); } public static Wait For(Int32 from, Int32 to, Action&lt;Object&gt; worker, Action workerComplete) { return For(from, to, worker, workerComplete, Environment.ProcessorCount); } public static Wait For(Int32 from, Int32 to, Action&lt;Object&gt; worker, Action workerComplete, Int32 workerCount) { return For(from, to, worker, workerComplete, workerCount, false); } public static Wait For(Int32 from, Int32 to, Action&lt;Object&gt; worker, Action workerComplete, Int32 workerCount, Boolean threadSafe) { return For(from, to, worker, workerComplete, workerCount, threadSafe, true); } public static Wait For(Int32 from, Int32 to, Action&lt;Object&gt; worker, Action workerComplete, Int32 workerCount, Boolean threadSafe, Boolean threadSafeComplete) { if (worker == null) return null; if (to &lt; from) return null; if (to == from) return null; Wait waitObject = new Wait(); Int32 numWorkers = workerCount &gt; 0 ? workerCount : Environment.ProcessorCount; Int32 itterations = to - from; numWorkers = numWorkers &gt; itterations ? itterations : numWorkers; Int32 step = (Int32)Math.Ceiling((Decimal)itterations / (Decimal)numWorkers); for (Int32 i = 0; i &lt; numWorkers; i++) { SpawnInToWait( _For, new ForContext() { WorkerDelegate = worker, WorkerCompleteDelegate = workerComplete, LoopFrom = i * step, LoopTo = Math.Min((i + 1) * step, to), WorkerID = i, WorkerThreadSafeExec = threadSafe, CompleteThreadSafeExec = threadSafeComplete }, ref waitObject, "For_Worker_" + i ); } return waitObject; } #endregion #region Private For Methods private static void _For(Object obj) { ForContext forCtx = (ForContext)obj; for (Int32 i = forCtx.LoopFrom; i &lt; forCtx.LoopTo; i++) { if (forCtx.WorkerThreadSafeExec) (new ThreadSafeCall()).Call(forCtx.WorkerDelegate, (object)i); else forCtx.WorkerDelegate((object)i); } if (forCtx.WorkerCompleteDelegate != null) { if (forCtx.CompleteThreadSafeExec) (new ThreadSafeCall()).Call(forCtx.WorkerCompleteDelegate); else forCtx.WorkerCompleteDelegate(); } } #endregion #region Public ForEach Methods public static Wait ForEach&lt;T&gt;(ICollection&lt;T&gt; collection, Action&lt;T&gt; worker) where T : class { return ForEach&lt;T&gt;(collection, worker, null); } public static Wait ForEach&lt;T&gt;(ICollection&lt;T&gt; collection, Action&lt;T&gt; worker, Action workerComplete) where T : class { return ForEach&lt;T&gt;(collection, worker, workerComplete, Environment.ProcessorCount); } public static Wait ForEach&lt;T&gt;(ICollection&lt;T&gt; collection, Action&lt;T&gt; worker, Action workerComplete, Int32 workerCount) where T : class { return ForEach((ICollection&lt;object&gt;)collection, (Action&lt;Object&gt;)worker, workerComplete, workerCount); } public static Wait ForEach(ICollection&lt;object&gt; collection, Action&lt;object&gt; worker) { return ForEach(collection, worker, null); } public static Wait ForEach(ICollection&lt;object&gt; collection, Action&lt;object&gt; worker, Action workerComplete) { return ForEach(collection, worker, workerComplete, Environment.ProcessorCount); } public static Wait ForEach(IEnumerable&lt;object&gt; collection, Action&lt;object&gt; worker, Action workerComplete, Int32 workerCount) { return ForEach(collection, worker, workerComplete, workerCount, false); } public static Wait ForEach(IEnumerable&lt;object&gt; collection, Action&lt;object&gt; worker, Action workerComplete, Int32 workerCount, Boolean threadSafe) { return ForEach(collection, worker, workerComplete, workerCount, false, true); } public static Wait ForEach(IEnumerable&lt;object&gt; collection, Action&lt;object&gt; worker, Action workerComplete, Int32 workerCount, Boolean threadSafe, Boolean threadSafeComplete) { Int32 total = collection.Count(); Int32 numWorkers = workerCount &gt; 0 ? workerCount : Environment.ProcessorCount; Int32 skip = total / numWorkers; Wait waitObject = new Wait(); for (Int32 i = 0; i &lt; numWorkers; i++) { SpawnInToWait( _ForEach, new ForEachContext() { DataCollection = collection.GetRange(i * skip, Math.Min(skip, total - (i * skip))), WorkerDelegate = worker, WorkerCompleteDelegate = workerComplete, WorkerID = i, DataCollectionType = collection.GetEnumerator().Current.GetType(), WorkerThreadSafeExec = threadSafe }, ref waitObject, "ForEach_Worker_" + i ); } return waitObject; } #endregion #region Private ForEach Methods private static void _ForEach(object obj) { ForEachContext forEachCtx = (ForEachContext)obj; foreach (object dataObject in forEachCtx.DataCollection) { if (forEachCtx.WorkerDelegate != null) { if (forEachCtx.WorkerThreadSafeExec) (new ThreadSafeCall()).Call(forEachCtx.WorkerDelegate, (object)dataObject); else forEachCtx.WorkerDelegate((object)dataObject); } } if (forEachCtx.WorkerCompleteDelegate != null) { if (forEachCtx.CompleteThreadSafeExec) (new ThreadSafeCall()).Call(forEachCtx.WorkerCompleteDelegate); else forEachCtx.WorkerCompleteDelegate(); } } #endregion #region Private Extension Methods /// &lt;summary&gt; /// Extension method that allows you to fetch a range from &lt;paramref name="start"/&gt; to &lt;paramref name="end"/&gt; /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;IEnumerable type&lt;/typeparam&gt; /// &lt;param name="source"&gt;Any IEnumerable (list, dictionary..)&lt;/param&gt; /// &lt;param name="start"&gt;start index&lt;/param&gt; /// &lt;param name="end"&gt;end index&lt;/param&gt; /// &lt;returns&gt;New IEnumerable of size end-start with the required items&lt;/returns&gt; private static IEnumerable&lt;T&gt; GetRange&lt;T&gt;(this IEnumerable&lt;T&gt; source, int start, int end) { using (var e = source.GetEnumerator()) { var i = 0; while (i &lt; start &amp;&amp; e.MoveNext()) { i++; } while (i &lt; end &amp;&amp; e.MoveNext()) { yield return e.Current; i++; } } } /// &lt;summary&gt; /// /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;IEnumerable type&lt;/typeparam&gt; /// &lt;param name="source"&gt;&lt;/param&gt; /// &lt;returns&gt;Number of items in &lt;paramref name="source"/&gt;&lt;/returns&gt; private static Int32 Count&lt;T&gt;(this IEnumerable&lt;T&gt; source) { Int32 result = 0; try { ICollection&lt;T&gt; c = source as ICollection&lt;T&gt;; if (c != null) throw new Exception("source is not a collection"); result = c.Count; } catch (Exception) { using (IEnumerator&lt;T&gt; enumerator = source.GetEnumerator()) { while (enumerator.MoveNext()) result++; } } return result; } #endregion #region Wait Class /// &lt;summary&gt; /// Class to allow the syncronisation of operations within Parallel /// &lt;/summary&gt; public class Wait { #region Public Events public event Action OnComplete; #endregion private Thread asyncThread = null; private List&lt;Thread&gt; threadList = new List&lt;Thread&gt;(); /// &lt;summary&gt; /// /// &lt;/summary&gt; /// &lt;param name="t"&gt;&lt;/param&gt; internal void AddThreadToWaitFor(Thread t) { threadList.Add(t); } /// &lt;summary&gt; /// /// &lt;/summary&gt; public void WaitForThreads() { foreach (Thread threadHandle in threadList) { if (threadHandle.IsAlive) threadHandle.Join(); } } /// &lt;summary&gt; /// /// &lt;/summary&gt; public void WaitForThreadsAsync() { WaitForThreadsAsync(null); } /// &lt;summary&gt; /// /// &lt;/summary&gt; /// &lt;param name="complete"&gt;&lt;/param&gt; public void WaitForThreadsAsync(Action complete) { asyncThread = new Thread(_ThreadChecker); asyncThread.Start(complete); } /// &lt;summary&gt; /// /// &lt;/summary&gt; /// &lt;param name="o"&gt;&lt;/param&gt; private void _ThreadChecker(object o) { Action onCompleteDelegate = (Action)o; WaitForThreads(); if (OnComplete != null) { Delegate[] onCompleteList = OnComplete.GetInvocationList(); foreach (Action onCompleteHandle in onCompleteList) { (new ThreadSafeCall()).Call(onCompleteHandle); } } if (onCompleteDelegate != null) { Delegate[] onCompleteList = onCompleteDelegate.GetInvocationList(); foreach (Action onCompleteHandle in onCompleteList) { (new ThreadSafeCall()).Call(onCompleteHandle); } } } } /// &lt;summary&gt; /// Wrapper class for making thread safe calls to any ISynchronizeInvoke based class, including Form's /// &lt;/summary&gt; private class ThreadSafeCall { /// &lt;summary&gt; /// Checks if &lt;paramref name="action"/&gt;'s target is ISynchronizeInvoke based, if so, invokes action, otherwise, simply calls action /// &lt;/summary&gt; /// &lt;param name="action"&gt;Zero param, null return delegate&lt;/param&gt; public void Call(Action action) { try { ISynchronizeInvoke invokable = action.Target as ISynchronizeInvoke; if (invokable != null &amp;&amp; invokable.InvokeRequired == true) { invokable.Invoke(action, null); } else { action(); } } catch (Exception) { //not really sure what to do with these in this particular instance } } /// &lt;summary&gt; /// Checks if &lt;paramref name="action"/&gt;'s target is ISynchronizeInvoke based, if so, invokes action, otherwise, simply calls action /// &lt;/summary&gt; /// &lt;param name="action"&gt;Single param, null return delegate&lt;/param&gt; /// &lt;param name="param"&gt;param to pass to &lt;paramref name="action"/&gt;&lt;/param&gt; public void Call(Action&lt;object&gt; action, object param) { try { ISynchronizeInvoke invokable = action.Target as ISynchronizeInvoke; if (invokable != null &amp;&amp; invokable.InvokeRequired == true) { invokable.Invoke(action, new object[] { param }); } else { action(param); } } catch (Exception) { //not really sure what to do with these in this particular instance } } /// &lt;summary&gt; /// Checks if &lt;paramref name="action"/&gt;'s target is ISynchronizeInvoke based, if so, invokes action, otherwise, simply calls action /// &lt;/summary&gt; /// &lt;param name="action"&gt;Zero param, object return delegate&lt;/param&gt; /// &lt;returns&gt;return value of &lt;paramref name="action"/&gt;&lt;/returns&gt; public object Call(Func&lt;object&gt; action) { try { ISynchronizeInvoke invokable = action.Target as ISynchronizeInvoke; if (invokable != null &amp;&amp; invokable.InvokeRequired == true) { return invokable.Invoke(action, null); } else { return action(); } } catch (Exception) { //not really sure what to do with these in this particular instance } return null; } /// &lt;summary&gt; /// Checks if &lt;paramref name="action"/&gt;'s target is ISynchronizeInvoke based, if so, invokes action, otherwise, simply calls action /// &lt;/summary&gt; /// &lt;param name="action"&gt;Single param, object return delegate&lt;/param&gt; /// &lt;param name="param"&gt;param to pass to &lt;paramref name="action"/&gt;&lt;/param&gt; /// &lt;returns&gt;return value of &lt;paramref name="action"/&gt;&lt;/returns&gt; public object Call(Func&lt;object, object&gt; action, object param) { try { ISynchronizeInvoke invokable = action.Target as ISynchronizeInvoke; if (invokable != null &amp;&amp; invokable.InvokeRequired == true) { return invokable.Invoke(action, new object[] { param }); } else { return action(param); } } catch (Exception) { //not really sure what to do with these in this particular instance } return null; } } #endregion } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T20:32:00.127", "Id": "45102", "Score": "3", "body": "What does this do that the [Task Parallel Library](http://msdn.microsoft.com/en-us/library/dd537609.aspx) doesn't?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T20:41:52.977", "Id": "45104", "Score": "0", "body": "my library creates the threads you ask for right away rather than being restricted to the threadpool" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T21:03:19.273", "Id": "45105", "Score": "5", "body": "@bizzehdee If you want a separate `Thread` for each `Task`, use `TaskCreationOptions.LongRunning`. But quite often, what `ThreadPool` does is going to be more efficient than that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T21:35:25.140", "Id": "45106", "Score": "0", "body": "@bizzehdee - It *can't* spawn more threads than the threadpool. As I understand it, the threadpool can be as large as your memory can handle, and runs as many tasks as your CPU will handle. So you're not going to break those limits with your own code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T21:36:43.480", "Id": "45107", "Score": "3", "body": "That being said, if you can post comparison numbers between using your code and using TPL or `Thread`s and yours is significantly better, I'll be really impressed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-04T21:12:30.353", "Id": "118564", "Score": "0", "body": "What's your reasoning for using `Int32` over `int`? Particularly for the loop index?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T20:19:12.343", "Id": "28733", "Score": "2", "Tags": [ "c#", ".net", "multithreading" ], "Title": "Improving class for parallelising parts of main codebase" }
28733
<p>I've made a Bash script to monitor some server log files for certain data and my method probably isn't the most efficient.</p> <p>One section specifically bugs me is that I have to write a newline to the monitored log so that the same line wont be read over continually.</p> <p>Feedback would be greatly appreciated!</p> <pre><code>#!/bin/bash serverlog=/home/skay/NewWorld/server.log onlinefile=/home/skay/website/log/online.log offlinefile=/home/skay/website/log/offline.log index=0 # Creating the file if [ ! -f "$onlinefile" ]; then touch $onlinefile echo "Name Date Time" &gt;&gt; "$onlinefile" fi if [ ! -f "$offlinefile" ]; then touch $offlinefile echo "Name Date Time" &gt;&gt; "$offlinefile" fi # Functions function readfile { # Login Variables loginplayer=`tail -1 $serverlog | grep "[INFO]" | grep "joined the game" | awk '{print $4}'` logintime=`tail -1 $serverlog | grep "[INFO]" | grep "joined the game" | awk '{print $2}'` logindate=`tail -1 $serverlog | grep "[INFO]" | grep "joined the game" | awk '{print $1}'` # Logout Variables logoutplayer=`tail -1 $serverlog | grep "[INFO]" | grep "left the game" | awk '{print $4}'` logouttime=`tail -1 $serverlog | grep "[INFO]" | grep "left the game" | awk '{print $2}'` logoutdate=`tail -1 $serverlog | grep "[INFO]" | grep "left the game" | awk '{print $1}'` # Check for Player Login if [ ! -z "$loginplayer" ]; then echo "$loginplayer $logindate $logintime" &gt;&gt; "$onlinefile" echo "Player $loginplayer login detected" &gt;&gt; "$serverlog" line=`grep -rne "$loginplayer" $offlinefile | cut -d':' -f1` if [ "$line" &gt; 1 ]; then sed -i "$line"d $offlinefile unset loginplayer unset line fi fi # Check for Player Logout if [ ! -z "$logoutplayer" ]; then echo "$logoutplayer $logoutdate $logouttime" &gt;&gt; "$offlinefile" echo "Player $loginplayer logout detected" &gt;&gt; "$serverlog" line=`grep -rne "$logoutplayer" $onlinefile | cut -d':' -f1` if [ "$line" &gt; 1 ]; then sed -i "$line"d $onlinefile unset logoutplayer unset line fi fi } # Loop while [ $index -lt 100 ]; do readfile done </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T21:37:14.113", "Id": "45108", "Score": "0", "body": "A minor remark: I think `! -z` is equivalent to `-n`." } ]
[ { "body": "<p>I have small suggestions for the function readfile to reduce the number of shell commands you need to run :</p>\n\n<ol>\n<li><p>Save the output of the following into a variable so it can be reused as shown in #2:</p>\n\n<pre><code>last_line=$(tail -1 $serverlog | grep \"[INFO]\")\n</code></pre></li>\n<li><p>As you are already using awk, use it to search and select columns both: </p>\n\n<pre><code>login_time=$(echo $last_line | awk '/joined the game/ {print $2}')\n</code></pre></li>\n<li><p>Since you are searching in a single file and not recursively, the -r flag to grep can be removed. </p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T11:15:35.167", "Id": "28741", "ParentId": "28734", "Score": "2" } }, { "body": "<p>Your goal is to monitor <code>$serverlog</code> continuously, and update <code>$onlinefile</code> and <code>$offlinefile</code> accordingly. The fact that you repeatedly close and reopen <code>$serverlog</code> is problematic, not only for performance reasons, but as you remarked, you risk processing the same line endlessly. Therefore, your general strategy should be to keep the file open, like this:</p>\n\n<pre><code>tail -f \"$serverlog\" | do_all_processing_here\n</code></pre>\n\n<p>Note that <code>grep \"[INFO]\"</code> doesn't do what you intend; instead, it matches lines that contain any of the characters <code>I</code>, <code>N</code>, <code>F</code>, or <code>O</code>. You probably meant <code>grep -F '[INFO]'</code> — the <code>-F</code> causes <code>grep</code> to treat your pattern as a fixed string rather than a regular expression. Then, your structure would be:</p>\n\n<pre><code>tail -f \"$serverlog\" | grep -F '[INFO]' | do_more_processing_here\n</code></pre>\n\n<p>I'm going to guess that <code>[INFO]</code> would appear in the third field of your server log. If so, the efficient solution would be…</p>\n\n<pre><code>tail -f \"$serverlog\" | \\\nwhile read date time severity player message ; do\n case \"$severity\" in\n \\[INFO\\])\n case \"$message\" in\n *joined the game*)\n echo \"$player $date $time\" &gt;&gt; \"$onlinefile\"\n sed -i -e \"$(\n awk -v player=\"$player\" '$1 == player { print NR \"d;\"}' \"$offlinefile\"\n )\" \"$offlinefile\"\n ;;\n *left the game*)\n echo \"$player $date $time\" &gt;&gt; \"$offlinefile\"\n sed -i -e \"$(\n awk -v player=\"$player\" '$1 == player { print NR \"d;\"}' \"$onlinefile\"\n )\" \"$onlinefile\"\n ;;\n esac # case $message\n ;;\n esac # case $severity\ndone\n</code></pre>\n\n<p>It's also possible to skip <code>awk</code> and edit <code>$offlinefile</code> and <code>$onlinefile</code> directly with</p>\n\n<pre><code>sed -i \"/^$player /d\" \"$offlinefile\"\n</code></pre>\n\n<p>but there could be a vulnerability if <code>$player</code> contained special characters such as <code>.*</code>. <a href=\"//stackoverflow.com/q/16529716/1157100\" rel=\"nofollow\">A better solution, if you have GNU awk ≥ 4.1.0</a>, is</p>\n\n<pre><code>awk -v player=\"$player\" '$1 != player' -i inplace \"$offlinefile\"\n</code></pre>\n\n<p>With other versions of <code>awk</code>, you could use <code>tempfile</code> to help you perform the edit.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-19T17:39:16.303", "Id": "29959", "ParentId": "28734", "Score": "4" } } ]
{ "AcceptedAnswerId": "29959", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T20:39:50.993", "Id": "28734", "Score": "6", "Tags": [ "bash", "logging", "awk" ], "Title": "Bash log monitoring" }
28734
<p>I'm building this website with PDO and Pattern MVC. I'm currently working on the login page and would like to know if this structure is correct for MVC pattern. I'd also like your opinions and advice on this.</p> <p>For my <strong>login view</strong> I have:</p> <pre><code>&lt;form action="test.php" name="loginform" method="post"&gt; &lt;input type="text" name="login"&gt; &lt;input type="password" name="password"&gt; &lt;input type="submit" name="login_submit" value="Se connecter"&gt; &lt;/form&gt; </code></pre> <p>For my <strong>login controller</strong> I have:</p> <pre><code>if(isset($_POST['login_submit'])){ if(!empty($_POST['login']) &amp;&amp; !empty($_POST['password'])){ $auth = new auth(); $auth-&gt;setLogin($_POST['login']); $auth-&gt;setPassword(md5(sha1($_POST['password']))); if(($row = $auth-&gt;login('u_login,u_email,u_id_level', 'users', 'u_login', 'u_password'))){ $_SESSION['back_office'] = array( 'login' =&gt; $row-&gt;u_login, 'email' =&gt; $row-&gt;u_email, 'level' =&gt; $row-&gt;u_id_level ); }else{ message::showError('Compte non reconnu'); } }else{ message::showError('Veuillez remplir tous les champs'); } } </code></pre> <p>For my <strong>login model</strong> I have:</p> <pre><code>class auth{ protected $rowUser; protected $login; protected $password; protected $email; public function setLogin($login){ $this-&gt;login = $login; } public function setPassword($password){ $this-&gt;password = $password; } /** * @return array $row */ public function login($fields, $table, $col_login, $col_password){ $query = Db::getInstance()-&gt;prepare('SELECT '.$fields.' FROM '.$table.' WHERE '.$col_login.' = :login AND '.$col_password.' = :password'); $query-&gt;bindValue(':login',$this-&gt;login,PDO::PARAM_STR); $query-&gt;bindValue(':password',$this-&gt;password,PDO::PARAM_STR); $query-&gt;execute(); if($query-&gt;rowCount() &gt; 0){ $row = $query-&gt;fetch(); return $row; }else{ return false; } $query-&gt;closeCursor(); } } </code></pre>
[]
[ { "body": "<p>Just a minor note: I'd reverse some conditions and use guard clauses to make the code flatten.</p>\n\n<pre><code>if(empty($_POST['login']) || empty($_POST['password'])){\n message::showError('Veuillez remplir tous les champs');\n return;\n}\n\n$auth = new auth();\n$auth-&gt;setLogin($_POST['login']);\n$auth-&gt;setPassword(md5(sha1($_POST['password'])));\nif(!($row = $auth-&gt;login('u_login,u_email,u_id_level', 'users', 'u_login', 'u_password'))){ \n message::showError('Compte non reconnu');\n return;\n}\n$_SESSION['back_office'] = array(\n 'login' =&gt; $row-&gt;u_login,\n 'email' =&gt; $row-&gt;u_email,\n 'level' =&gt; $row-&gt;u_id_level\n);\n</code></pre>\n\n<p>(You might need to extract this out to a function.)</p>\n\n<p>References: </p>\n\n<ul>\n<li><em>Replace Nested Conditional with Guard Clauses</em> in <em>Refactoring: Improving the Design of Existing Code</em> by Martin Fowler; </li>\n<li><a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">Flattening Arrow Code</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T15:10:33.570", "Id": "45332", "Score": "0", "body": "don't use return; inside the if statement. This makes it really hard to debug code. For instance the message class could decide that the code should continue executing. But it can't because of the return. Now the application logic is partly handling the error. This is bad design. Let the message class decide what to do and end with die();" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T15:12:00.060", "Id": "45333", "Score": "0", "body": "Also, you application logic should know how the password is encrypted. This should happen inside the auth class. Because know if the encryption is changed, you will have to change all occurences to the setPassword call. Also the setPAssword method name says that you should be setting the password. But in face you are setting a PasswordHash. This makes it really crap to debug in a few month time. More info: http://thc.org/root/phun/unmaintain.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T16:28:35.640", "Id": "45344", "Score": "0", "body": "@Pinoniq: Have you noticed the \"You might need to extract this out to a function.\" note? I agree with the second comment (I haven't noticed that) but I guess it should be a comment on the original code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T17:56:18.223", "Id": "28751", "ParentId": "28742", "Score": "-1" } }, { "body": "<p>A part of code in auth::login() of method you should move to other class, for example 'db'. Because you class auth has too much responsibility. For example if you want to have dynamic define fields in class auth:</p>\n\n<p>Db class:</p>\n\n<pre><code>class db {\n public function getItem($table, $fields = '*', $conditions = array()) {\n // you code ...\n return $row;\n }\n}\n</code></pre>\n\n<p>Your model:</p>\n\n<pre><code>class auth {\n private $table = 'users';\n private $fields = 'u_login, u_email, u_id_level';\n private $fieldLogin = 'u_login';\n private $fieldPassword = 'u_password';\n\n public function setTable($value) { $this-&gt;table = $value; }\n public function setFields($value) { $this-&gt;fields = $value; }\n public function setFieldLogin($value) { $this-&gt;fieldLogin = $value; }\n public function setFieldPassword($value) { $this-&gt;fieldPassword = $value; }\n\n public function login() {\n $db = new db();\n return $db-&gt;getItem($this-&gt;table, $this-&gt;fields, array(\n $this-&gt;fieldLogin =&gt; $this-&gt;login,\n $this-&gt;fieldPassword =&gt; $this-&gt;password\n ));\n } \n}\n</code></pre>\n\n<p>This code is more elastic and simpler will be change it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T13:55:19.173", "Id": "45258", "Score": "0", "body": "Ok but I ut what in my controller?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T14:43:42.047", "Id": "45326", "Score": "0", "body": "You should also pass in the DB instance in the constructor. Read on dependency injection to know why" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T10:04:21.620", "Id": "28771", "ParentId": "28742", "Score": "1" } }, { "body": "<p>This is just about the security:</p>\n\n<p><code>md5(sha1());</code> is the worst security you can do.</p>\n\n<p>Let's just say that I am a hack0r that happens to come accross a database dump of your user table. I can now start cracking your user's passwords.</p>\n\n<p>Because I am such a 1337 hack0r I have multiple ways of going at your code.</p>\n\n<p>There is the bruteforce way: simply trying all possibilities. But I don't think I need to explain that trying all possibilities is not that fast...</p>\n\n<p>Then I can use dictionary atack, simply try all most used passwords and combinations of those passwords.</p>\n\n<p>This greatly reduces the amount of time needed to crack a users password and is only held back by the time it takes to generate a hash. You use 2 hashes so it will take some time. Do that times the amount of passwords and maybe my grandson will have all passwords cracked.</p>\n\n<p>BUT, don't underestimate my hack1ng skillz, for I am the mast3r. I use a rainbow table. Since you are using the exace same algorithm for all users I can create a database table with all calculated hashes in it. Then I perform a simple <code>SELECT password FROM rainbowtable WHERE hash = :theHachedHash;</code> BOOM!</p>\n\n<p>But now the time creating a rainbow table is the one thing that is holding me back. Because there are still a lot of possibilities. But there is where <strong>you</strong> helped me out. You crate a <code>md5</code> hash of an <code>sha1</code> hash. Oh man, thank you!\nI now know that I only need to check for md5 hashes of 20-string long strings to get the sha1 string. And then I only need a rainbow table for password to sha1 (google will help me there). So by hashing you password twice you have succesfully helped me crack your passwords by using 2 rainbow tables. 1 for md5 -> 20string long string (that one will take a couple of minutes to create on a cheap laptop) and one of the many rainbow tables for sha1 you can find in google.</p>\n\n<p>But that is not is, you have not only choosen to fall for the trap of hashing a password twice, you are actually using hashing algorithms that are weak and have been cracked many years ago. So to say: your password hashing algorithm is a laugh and will only work against script kidd0s, but they won't even get to the database in the first place...</p>\n\n<p>So, as we saw above, with a technique called Rainbowtables I can easily hack your users password. You could upgrade the security by using a stronger hashing algorithm that takes more time to create.\nBut as computers get stronger, you would always have to upgrade your algorithm.</p>\n\n<p>But don't cry! there is a solution. It's called SALT. Instead of somply passing a password into a hashing algorithm, we first append a unique random string to the password. Then we hash it in a strong algorithm.\nNow the atacker will have to create a rainbow table for every user. Even is the users have the same passwords. <code>passwordRandomString1</code> has a different hash then <code>passwordRandomString2</code></p>\n\n<p>But now we have two things to secure, the unique SALT has to be absolutely random, so for instance <code>time()</code> will not suffice since it time based and that is not random. We could use the built in random generator of php. But this one uses time() to generate random numbers. So it is good enough for application logic, but not for security.</p>\n\n<p>But lucky for us, some really smart people did all the work for us. We have some very nice libraries for all languages.\n<a href=\"http://en.wikipedia.org/wiki/PBKDF2\" rel=\"nofollow\">pkbf2</a> being one of them with a <a href=\"http://be1.php.net/hash-pbkdf2\" rel=\"nofollow\">native implementation</a>. Or even better <a href=\"http://be1.php.net/manual/en/function.crypt.php\" rel=\"nofollow\">crypt</a> using the blowfish algorithm.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T15:07:48.103", "Id": "28836", "ParentId": "28742", "Score": "0" } } ]
{ "AcceptedAnswerId": "28751", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T12:16:35.443", "Id": "28742", "Score": "1", "Tags": [ "php", "object-oriented", "mysql", "mvc", "pdo" ], "Title": "Look over my code for PDO and MVC" }
28742
<p>This app is a simple taxi emulator. The only feedback I've got on it was "bad internal architecture", that's why I would be grateful to receive more adequate and humiliating review.</p> <p>Simply-speaking, it should be a static lib, all the functionality must execute in the same thread (but! thread-safe). There should be a taxi station with cash desk, drivers and cabs. Each driver has its own car and own cash desk. One can re-assign the car to another driver. Car breaks after each 50 000 km. The <code>DoMainProcessing</code> function should wake every 2 seconds from outside, check if driver already took passenger to his place, fill in cash desk and possibly fix cars.</p> <p><a href="http://pastebin.com/Dvd37pWi" rel="nofollow">Full description</a></p> <p>The weakest place in my code, I think, is <code>DoMainProcessing</code>. It just goes through all drivers and cars checking their condition. But I just had no better idea to do this in one thread.</p> <p>Main class header:</p> <pre><code>#pragma once #include "CashBox.h" #include "Driver.h" #include "Car.h" #include &lt;unordered_map&gt; #include &lt;unordered_set&gt; #include &lt;memory&gt; static const std::string DRIVER_CAR_LOCK = "DriverCar"; static const int NO_ERR = 0; static const int CAR_IS_BUSY = 1; static const int DRIVER_IS_BUSY = 2; static const int NO_DRIVER_FOUND = 3; static const int CAR_IS_BROKEN = 4; class TaxiPark { public: //Basic function. Checks if which trips are finished // and repairs broken cars void DoMainProcessing(); ~TaxiPark(void){}; TaxiPark(void){}; //Cars and drivers management int AddDriver(DWORD ID, std::shared_ptr&lt;Car&gt; car); int AddCar(DWORD ID); int ChangeCar(DWORD driverID, std::shared_ptr&lt;Car&gt; newCar); //Get driver/car info by ID const std::shared_ptr&lt;Driver&gt; GetDriverById(DWORD ID); const std::shared_ptr&lt;Car&gt; GetCarById(DWORD ID); //Get all ID's const std::vector&lt;DWORD&gt; GetAllCarID(); const std::vector&lt;DWORD&gt; GetAllDriverID(); //Try to set driver status as sick/on vacation if driver is not on trip int SetDriverStatus(DWORD driverID, bool onVacation, bool isSick); //Try to start trip for chosen passenger with chosen driver if it possible //(driver isn't already busy/on vacation/sick, car isn't broken) int TakeClients(Passenger client, DWORD driverID, DWORD distance, DWORD speed ); private: CashBox cashBox; std::unordered_map&lt;DWORD, std::shared_ptr&lt;Driver&gt;&gt; Drivers; std::unordered_map&lt;DWORD, std::shared_ptr&lt;Car&gt;&gt; Cars; }; </code></pre> <p>DoMainProcessing function:</p> <pre><code>void TaxiPark::DoMainProcessing() { auto mut = CreateMutex(NULL, FALSE, DRIVER_CAR_LOCK.c_str()); WaitForSingleObject(mut, INFINITE); { std::for_each(Drivers.begin(), Drivers.end(), [this] (std::pair&lt;DWORD, std::shared_ptr&lt;Driver&gt;&gt; it) { std::shared_ptr&lt;Driver&gt; driver(it.second); auto driverID = it.first; if (driver-&gt;IsTripFinished()) { Drivers.erase(driverID); driver-&gt;FinishTrip(); Drivers.emplace(std::make_pair&lt;DWORD,std::shared_ptr&lt;Driver&gt;&gt;(driverID, driver)); } }); std::for_each(Cars.begin(), Cars.end(), [this] (std::pair&lt;DWORD, std::shared_ptr&lt;Car&gt;&gt; it) { std::shared_ptr&lt;Car&gt; car(it.second); auto carID = it.first; if (car-&gt;IsBroken()) { Cars.erase(carID); if (cashBox.GetBalance() &gt;= CAR_REPAIR_COST) { cashBox.TakeCash(CAR_REPAIR_COST); car-&gt;Repair(); } Cars.emplace(std::make_pair&lt;DWORD,std::shared_ptr&lt;Car&gt;&gt;(carID, car)); } }); } } </code></pre> <p><a href="https://www.dropbox.com/s/prg9krpt2vr5kvf/TaxiPark.rar" rel="nofollow">Here's the full code listing</a>.</p> <p>P.S.: I know that <code>unordered_map</code> is a bad idea in this case. It gives no advantages in terms of speed, but requires exceed work in need of changing elements.</p>
[]
[ { "body": "<ul>\n<li>Use standard <code>#include</code> guards, not the non-standard <code>#pragma once</code>.</li>\n<li>Use standard data types, not <code>DWORD</code>.</li>\n<li>Change</li>\n</ul>\n\n<p>this:</p>\n\n<pre><code>static const int NO_ERR = 0;\nstatic const int CAR_IS_BUSY = 1;\nstatic const int DRIVER_IS_BUSY = 2;\nstatic const int NO_DRIVER_FOUND = 3;\nstatic const int CAR_IS_BROKEN = 4; \n</code></pre>\n\n<p>into an <code>enum</code>:</p>\n\n<pre><code>enum CarStatus { NO_ERROR, CAR_IS_BUSY, DRIVER_IS_BUSY, NO_DRIVER_FOUND, CAR_IS_BROKEN };\n</code></pre>\n\n<ul>\n<li><code>DoMainProcessing</code> is a horrible name and sounds like a function that does way too much. (<strong>Update:</strong> Okay, that's part of the exercise. Oh, well.)</li>\n<li>Consider <code>typedef std::shared_ptr&lt;Car&gt; CarPtr</code> or something, to make the code less cluttered.</li>\n<li>Avoid <code>bool</code> in interfaces, as it leads to poor readability and is error prone.</li>\n</ul>\n\n<p>Instead of:</p>\n\n<pre><code>int SetDriverStatus(DWORD driverID, bool onVacation, bool isSick);\n</code></pre>\n\n<p>Use an <code>enum</code> indicator (or a <code>string</code>) instead:</p>\n\n<pre><code>enum DriverStatus { /* ... */ };\nvoid SetDriverStatus(DriverID driver, DriverStatus newStatus)\n{\n // ...\n}\n</code></pre>\n\n<p>The function should be <code>void</code>. (If you are currently returning the old state: Stop doing that, and have a separate function for that. If you are returning a status number to indicate success or not: Use exceptions instead.)</p>\n\n<ul>\n<li><p>You should probably use the C++ threading library instead of your <code>CreateMutex</code>. (<strong>Update:</strong> Again, your exercise hinders you from doing the right thing.)</p></li>\n<li><p>Your use of <code>for_each</code> should be substituted with a range-based <code>for</code> loop.</p></li>\n<li><p>The exercise states:</p></li>\n</ul>\n\n<blockquote>\n <p>There must be some function, we call it <code>DoMainProcessing</code>, that periodically\n gets called by an external source using the emulator (for example, every second or two).\n It should detect when the driver made the carriage of the customer (depending\n distance and average speed) and is ready to perform the next one. Then, it should\n repair the broken car (subject of availability of sufficient\n number of funds).</p>\n</blockquote>\n\n<p>The way I understand this, you should update the state of each of your cars and drivers in this function. You should probably record the time between each call, and add the distance traveled to a counter.</p>\n\n<p>Very roughly something like this:</p>\n\n<pre><code>void TaxiPark::DoMainProcessing()\n{\n // Use a real library for time, I'm just illustrating.\n Time now = getTime();\n TimeDiff time_difference = now - previous_processing_time;\n previous_processing_time = now;\n\n for (auto&amp; driver : Drivers) {\n driver.update(time_difference);\n }\n\n // Updates for cars ...\n}\n</code></pre>\n\n<p>Then, in <code>Driver::update()</code>, you should increase distance traveled based on speed and time difference. If the distance is greater than or equal to the distance of the current ride, the ride is done. Do other state updates as necessary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T04:19:47.490", "Id": "45229", "Score": "1", "body": "No, #pragma once isn't standard, but you are unlikely to run into a compiler that doesn't support it (http://en.wikipedia.org/wiki/Pragma_once)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T19:44:13.313", "Id": "28754", "ParentId": "28745", "Score": "6" } } ]
{ "AcceptedAnswerId": "28754", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T16:11:32.963", "Id": "28745", "Score": "5", "Tags": [ "c++", "object-oriented", "design-patterns", "c++11", "simulation" ], "Title": "Simple taxi emulator" }
28745
<p>I've been asked to attach a C++ code sample to my application for an entry-level C++ programmer position in a videogame company. I've created a simple, yet complete console application to solve Sudoku problems. How can I improve the code that I have?</p> <p>Please do comment on the algorithm, the code practices, presentation, or anything else. It's one of my first attempts to also set up unit tests with my code.</p> <p>Also, I am interested in whether you think this would work well as a code sample in particular – i.e. does it show what people who look at the code samples want to see?</p> <p><a href="http://ideone.com/iaNvZ4" rel="nofollow">Complete code</a></p> <pre><code>#include &lt;set&gt; #include &lt;string&gt; #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;cassert&gt; // ====================================================================================== enum SolutionResult { // The position has been solved OK. SR_SOLVED, // The current position in invalid. // For that reason, it is useless to even attempt to solve it. SR_INVALID, // The current position is valid in its current state, but there // exists no complete solution that would uphold the sudoku rules. SR_UNSOLVABLE }; // ====================================================================================== class Sudoku { protected: // 0 = Empty cell short values[9][9]; // Returns whether all the rows are currently valid, // i.e. whether no rows contain any duplicate values. bool checkValidRows() { for (short row = 0; row &lt; 9; row++) { std::set&lt;short&gt; valuesInRow; for (short col = 0; col &lt; 9; col++) { short val = this-&gt;values[row][col]; if (!val) continue; if (valuesInRow.find(val) != valuesInRow.end()) { return false; } valuesInRow.insert(val); } } return true; } // Returns whether all the columns are currently valid, // i.e. whether no columns contain any duplicate values. bool checkValidCols() { for (short col = 0; col &lt; 9; col++) { std::set&lt;short&gt; valuesInCol; for (short row = 0; row &lt; 9; row++) { short val = this-&gt;values[row][col]; if (!val) continue; if (valuesInCol.find(val) != valuesInCol.end()) { return false; } valuesInCol.insert(val); } } return true; } // Returns whether all the partial squares are currently valid, // i.e. whether no 3x3 square contains a duplicate value. bool checkValidSquares() { for (short squareX = 0; squareX &lt; 3; squareX++) { for (short squareY = 0; squareY &lt; 3; squareY++) { std::set&lt;short&gt; valuesInSquare; for (short m = 0; m &lt; 3; m++) { for (short n = 0; n &lt; 3; n++) { short val = this-&gt;values[squareX*3+m][squareY*3+n]; if (val == 0) continue; if (valuesInSquare.find(val) != valuesInSquare.end()) { return false; } valuesInSquare.insert(val); } } } } return true; } // Returns whether the current position is valid, i.e., whether its rows, columns, // and squares are all valid and do not contain a duplicate value. bool checkValid() { return this-&gt;checkValidRows() &amp;&amp; this-&gt;checkValidCols() &amp;&amp; this-&gt;checkValidSquares(); } public: Sudoku() { // Start with a blank position. for (short row = 0; row &lt; 9; row++) { for (short col = 0; col &lt; 9; col++) { this-&gt;values[row][col] = 0; } } } Sudoku (const short values[9][9]) { for (short row = 0; row &lt; 9; row++) { for (short col = 0; col &lt; 9; col++) { // Values that are not between [0 .. 9] // are discarded and replaced with zeroes. short val = values[row][col]; if (val &gt;= 0 &amp;&amp; val &lt;= 9) { this-&gt;values[row][col] = val; } else { this-&gt;values[row][col] = 0; } } } } // This is the solver method. // The way to solution is a standard backtrack exercise. // // For the next empty space, we put the lowest possible value in, and recursively call the solver // to see whether it can complete all the other spaces in a valid manner – in which case, we are done. // In case that no possible value in the chosen space leads to a valid and complete solution, we clear // the space entirely and declare the position as unsolvable. In recursion terms, this means that // we need to attempt to put another value to the previous space, and so on. SolutionResult solve() { // Check that the situation is valid. if (!this-&gt;checkValid()) return SR_INVALID; // For the next empty space: for (short row = 0; row &lt; 9; row++) { for (short col = 0; col &lt; 9; col++) { if (this-&gt;values[row][col] &gt; 0) continue; // Put an arbitrary value into the space: for (short val = 1; val &lt;= 9; val++) { this-&gt;values[row][col] = val; // Recursively call the solver and see whether it can complete all // the other spaces in the same manner. In case that it can, we're done. if (this-&gt;solve() == SR_SOLVED) { return SR_SOLVED; } } // We tried all the possible values, and none has lead to a complete and // valid solution. Clear the space, and return that the position is unsolvable. this-&gt;values[row][col] = 0; return SR_UNSOLVABLE; } } // There are no more empty spaces. // We're done. return SR_SOLVED; } // Formatted output. friend std::ostream&amp; operator&lt;&lt; (std::ostream &amp;os, const Sudoku&amp; s) { for (short row = 0; row &lt; 9; row++) { os &lt;&lt; std::endl; for (short col = 0; col &lt; 9; col++) { os &lt;&lt; ' '; if (s.values[row][col] &gt; 0) { os &lt;&lt; s.values[row][col]; } else { os &lt;&lt; '.'; } if (col == 2 || col == 5) { os &lt;&lt; " |"; } } if (row == 2 || row == 5) { os &lt;&lt; std::endl &lt;&lt; " ------+-------+------"; } } os &lt;&lt; std::endl; return os; } // static void runUnitTests(); }; // ====================================================================================== int main (int argc, char* argv[]) { short pos[9][9] = { {0, 0, 4, 0, 0, 0, 0, 0, 0}, {6, 0, 2, 1, 0, 0, 0, 0, 0}, {1, 0, 8, 3, 4, 2, 5, 6, 7}, {0, 0, 9, 7, 0, 0, 4, 2, 3}, {4, 0, 6, 8, 0, 0, 0, 0, 1}, {7, 1, 3, 9, 2, 0, 8, 0, 0}, {0, 0, 0, 5, 3, 0, 2, 8, 4}, {0, 0, 0, 4, 1, 0, 6, 0, 0}, {3, 0, 0, 0, 0, 6, 1, 0, 0} }; // Let's test the entire unit. Sudoku::runUnitTests(); // Let's solve the particular position above: Sudoku s (pos); std::cout &lt;&lt; s &lt;&lt; std::endl; std::cout &lt;&lt; "Solver starts, please wait..." &lt;&lt; std::endl; switch (s.solve()) { case SR_SOLVED: std::cout &lt;&lt; "Solution: " &lt;&lt; std:: endl; std::cout &lt;&lt; s &lt;&lt; std::endl; break; case SR_INVALID: std::cout &lt;&lt; "The position is not valid." &lt;&lt; std:: endl; break; case SR_UNSOLVABLE: std::cout &lt;&lt; "The position cannot be solved." &lt;&lt; std:: endl; break; } std::cout &lt;&lt; "Press any key to exit..."; getchar(); return 0; } // ====================================================================================== void Sudoku::runUnitTests() { short dataZeroes[9][9] = { {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, 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} }; short dataValidPos1[9][9] = { {5, 3, 4, 6, 7, 8, 9, 1, 2}, {6, 7, 2, 1, 9, 5, 3, 4, 8}, {1, 9, 8, 3, 4, 2, 5, 6, 7}, {8, 5, 9, 7, 6, 1, 4, 2, 3}, {4, 2, 6, 8, 5, 3, 7, 9, 1}, {7, 1, 3, 9, 2, 4, 8, 5, 6}, {9, 6, 1, 5, 3, 7, 2, 8, 4}, {2, 8, 7, 4, 1, 9, 6, 3, 5}, {3, 4, 5, 2, 8, 6, 1, 7, 9} }; short dataValidPos2[9][9] = { {0, 0, 0, 0, 0, 0, 0, 0, 0}, {6, 0, 2, 1, 0, 0, 0, 0, 0}, {1, 0, 8, 3, 4, 2, 5, 6, 7}, {0, 0, 9, 7, 0, 0, 4, 2, 3}, {4, 0, 6, 8, 0, 0, 0, 0, 1}, {7, 1, 3, 9, 2, 0, 8, 0, 0}, {0, 0, 0, 5, 3, 0, 2, 8, 4}, {0, 0, 0, 4, 1, 0, 6, 0, 0}, {3, 0, 0, 0, 0, 6, 1, 0, 0} }; short dataInvalidRows[9][9] = { {5, 3, 4, 6, 7, 8, 9, 1, 5}, {6, 7, 2, 1, 9, 5, 3, 4, 8}, {1, 9, 8, 3, 4, 2, 0, 6, 7}, {8, 5, 9, 7, 6, 1, 4, 2, 3}, {4, 2, 6, 8, 5, 3, 7, 9, 1}, {7, 1, 3, 9, 2, 4, 8, 5, 6}, {9, 6, 1, 5, 3, 7, 2, 8, 4}, {2, 8, 7, 4, 1, 9, 6, 3, 0}, {3, 4, 5, 2, 8, 6, 1, 7, 9} }; short dataInvalidCols[9][9] = { {5, 3, 4, 6, 7, 8, 9, 1, 2}, {6, 7, 2, 1, 9, 0, 3, 4, 8}, {1, 9, 8, 3, 4, 2, 5, 6, 7}, {8, 5, 9, 7, 6, 1, 4, 2, 3}, {4, 2, 6, 8, 5, 3, 7, 9, 1}, {7, 1, 3, 9, 2, 4, 8, 5, 6}, {9, 6, 1, 5, 3, 7, 2, 8, 4}, {2, 8, 7, 4, 1, 9, 6, 3, 5}, {5, 4, 0, 2, 8, 6, 1, 7, 9} }; short dataInvalidSquares[9][9] = { {5, 3, 4, 6, 7, 8, 9, 1, 2}, {6, 5, 2, 1, 9, 0, 3, 4, 8}, {1, 9, 8, 3, 4, 2, 5, 6, 7}, {8, 0, 9, 7, 6, 1, 4, 2, 3}, {4, 2, 6, 8, 5, 3, 7, 9, 1}, {7, 1, 3, 9, 2, 4, 8, 5, 6}, {9, 6, 1, 5, 3, 7, 2, 8, 4}, {2, 8, 7, 4, 1, 9, 6, 3, 5}, {3, 4, 5, 2, 8, 6, 1, 7, 9} }; Sudoku zeroes (dataZeroes); Sudoku validPos1 (dataValidPos1); Sudoku validPos2 (dataValidPos2); Sudoku invalidRows (dataInvalidRows); Sudoku invalidCols (dataInvalidCols); Sudoku invalidSquares (dataInvalidSquares); std::cout &lt;&lt; "Unit tests start..." &lt;&lt; std::endl; assert(zeroes.checkValidRows()); assert(zeroes.checkValidCols()); assert(zeroes.checkValidSquares()); assert(zeroes.checkValid()); assert(zeroes.solve() == SR_SOLVED); assert(validPos1.checkValidRows()); assert(validPos1.checkValidCols()); assert(validPos1.checkValidSquares()); assert(validPos1.checkValid()); assert(validPos1.solve() == SR_SOLVED); assert(validPos2.checkValidRows()); assert(validPos2.checkValidCols()); assert(validPos2.checkValidSquares()); assert(validPos2.checkValid()); assert(validPos2.solve() == SR_SOLVED); assert(validPos2.values[0][0] == 5); assert(validPos2.values[0][1] == 3); assert(validPos2.values[0][2] == 4); assert(validPos2.values[0][3] == 6); assert(validPos2.values[0][4] == 7); assert(validPos2.values[0][5] == 8); assert(validPos2.values[0][6] == 9); assert(validPos2.values[0][7] == 1); assert(validPos2.values[0][8] == 2); assert(!invalidRows.checkValidRows()); assert( invalidRows.checkValidCols()); assert( invalidRows.checkValidSquares()); assert(!invalidRows.checkValid()); assert( invalidRows.solve() == SR_INVALID); assert( invalidCols.checkValidRows()); assert(!invalidCols.checkValidCols()); assert( invalidCols.checkValidSquares()); assert(!invalidCols.checkValid()); assert( invalidCols.solve() == SR_INVALID); assert( invalidSquares.checkValidRows()); assert( invalidSquares.checkValidCols()); assert(!invalidSquares.checkValidSquares()); assert(!invalidSquares.checkValid()); assert( invalidSquares.solve() == SR_INVALID); std::cout &lt;&lt; "All unit tests OK." &lt;&lt; std::endl; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T18:41:33.330", "Id": "45186", "Score": "2", "body": "Your commenting and huge amount of unneeded whitespace can be improved. I have suggested Jamal. I think he'll be reviewing that part soon." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T21:22:07.943", "Id": "45201", "Score": "4", "body": "You might be interested to read my series on writing a Sudoku solver in C#; I carefully describe the pros and cons of the various small and large choices that I make during the development of the algorithm. http://blogs.msdn.com/b/ericlippert/archive/tags/graph+colouring/" } ]
[ { "body": "<ul>\n<li><p>Read <a href=\"https://softwareengineering.stackexchange.com/questions/173118/should-comments-say-why-the-program-is-doing-what-it-is-doing-opinion-on-a-dic\">this</a> and <a href=\"https://softwareengineering.stackexchange.com/questions/119600/beginners-guide-to-writing-comments\">this</a> regarding your commenting. You also shouldn't have that extra whitespace within your functions.</p></li>\n<li><p>I cannot tell if your full solution uses a single file or separate files. Multiple files are preferred, but a single file is also okay if declarations and definitions are properly structured.</p>\n\n<p>Regarding declarations, you shouldn't have any function definitions in your header (considering you're not using accessors and mutators). Try this:</p>\n\n<pre><code>class Sudoku {\n\nprivate: // private is preferred over protected here\n short values[9][9];\n\n // these functions should be const\n bool checkValidRows() const;\n bool checkValidCols() const;\n bool checkValidSquares() const;\n\npublic:\n Sudoku();\n Sudoku(const short values[9][9]);\n SolutionResult solve();\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp;, Sudoku const&amp;);\n};\n</code></pre></li>\n<li><p>You could use a \"2D\" <code>std::array</code> instead. It gives you <a href=\"http://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow noreferrer\">these features</a>, but it looks a bit long as a nested structure (although you can use a <code>typedef</code>):</p>\n\n<pre><code>std::array&lt;std::array&lt;short, 9&gt;, 9&gt; values;\n</code></pre></li>\n<li><p><code>solve()</code> shouldn't be <code>public</code> since it's not part of the interface. Instead, make it <code>private</code> and <code>void</code>, and have another <code>public</code> function return the appropriate <code>SolutionResult</code>. You would then need to call <code>solve()</code> somewhere in the class as opposed to <code>main()</code>.</p></li>\n<li><p>For a serious application, you shouldn't need to hard-code your game board. Even after hiding this behind the class, it would be boring as you would be solving the same board each time (unless you're willing to keep changing it yourself).</p>\n\n<p>Instead, consider having the board randomized with values and making sure it's a valid starting board. Again, this would be done inside the class.</p>\n\n<p>You then won't need your second constructor.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T18:36:30.793", "Id": "45184", "Score": "1", "body": "I don't know C++ so I'll just ask you whether [this](http://programmers.stackexchange.com/questions/173118/should-comments-say-why-the-program-is-doing-what-it-is-doing-opinion-on-a-dic) and [this](http://programmers.stackexchange.com/questions/119600/beginners-guide-to-writing-comments) should be suggested to the OP for his comments? If you think that they are relevant please do so. It might be helpful to the OP." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T18:39:52.690", "Id": "45185", "Score": "0", "body": "@AseemBansal: Good point. I also just noticed all the whitespace, too. I'll add this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T20:55:40.647", "Id": "45196", "Score": "0", "body": "@Lstor: Thanks. I have much to learn from your answer, too. The one thing that I'm still not savvy with is error-handling." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T17:54:25.753", "Id": "28750", "ParentId": "28746", "Score": "9" } }, { "body": "<p>From a brief glance, I can see a number of issues with the code. I'm sorry if I am overly blunt, but it's better that you hear it from me than a recruiter.</p>\n\n<p>In no particular order:</p>\n\n<ul>\n<li><p><strong>Use the language.</strong> Structure your code better. Consider using more classes to represent the board. Don't write a sudoku-solving program. Make it a tiny sudoku-solver library, and include a driver program to use that library. Write reusable code.</p></li>\n<li><p>You have <code>protected</code> members of the class. This usually means the class is designed to be a base class. However, base classes should have a virtual destructor, but yours isn't. You probably want to change <code>protected</code> to <code>private</code>.</p></li>\n<li><p>Make your solver handle boards with multiple solutions.</p></li>\n<li><p>Your explicit use of <code>this</code> just creates clutter, in my opinion.</p></li>\n<li><p>Your code is not exception safe. There is no way to test the state of the solver if <code>solve()</code> throws an exception, for example. You should have a function in the public interface to query the state of the solver.</p></li>\n<li><p>Avoid excessive whitespace and comments.</p></li>\n<li><p>Make member functions that don't mutate state <code>const</code>.</p></li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>bool checkValidCols() const { /* ... */ }\n</code></pre>\n\n<ul>\n<li><p>Don't hard code sizes. Read your game board from a file. Accept variable-sized boards.</p></li>\n<li><p>Prefer pre-increment to post-increment when pre-increment is what you want. You want to say \"increment <code>i</code> by one\", not \"make a copy of <code>i</code> and then increment the original value by one\". This is a good habit in general, because post-increment for user-defined types <em>does</em> make an extra, unnecessary copy.</p></li>\n<li><p>Don't repeat yourself. <code>checkValidRows</code> and <code>checkValidCols</code> is more or less the same function. If you make a bit of an abstraction, the same goes for the square checking.</p></li>\n<li><p>Consider using a one-dimensional array, and/or using one-dimensional or two-dimensional <code>std::array</code> or <code>std::vector</code>.</p></li>\n<li><p>There are indentation issues in the code you have posted.</p></li>\n<li><p>Your solving algorithm is possibly the slowest one I can think of. Do a quick google search and do something smarter.</p></li>\n<li><p>You have very long functions defined inline. It gives the impression that you only know Java, but happen to be writing in C++. Move the implementation code out of the class definition, and structure your code into files.</p></li>\n<li><p>Use a separate unit test library, for example <a href=\"https://code.google.com/p/googletest/\">googletest</a>. Don't <em>always</em> run unit tests when the program runs.</p></li>\n<li><p>Drop the \"Press any key to exit\" part. It looks very unprofessional.</p></li>\n<li><p>Consider adding read-only access to your board tiles, so that your class can be used as a back-end for a GUI later.</p></li>\n<li><p>Don't pass parameters to <code>main</code> if you are not going to use them.</p></li>\n<li><p>Put a <code>default</code> in your <code>switch</code> to catch errors.</p></li>\n<li><p>Use assertions to ensure pre- and post-conditions and invariants of functions during debugging.</p></li>\n<li><p>Perform error handling, preferably using exceptions. Make your program very robust; you don't want <a href=\"http://en.wikipedia.org/wiki/Crash_to_desktop\">CTD</a> in a game.</p></li>\n<li><p>Have many small unit tests that test exactly a single thing. If a test fails, you should know from its name what has failed. Look at an <a href=\"https://github.com/cpputest/cpputest/blob/master/tests/SimpleStringTest.cpp#L56\">example of unit tests online</a>.</p></li>\n<li><p>Sort your <code>#include</code>s alphabetically.</p></li>\n<li><p>Consider making your solver multi-threaded.</p></li>\n<li><p>Remember to include the other important parts. Primarily: Documentation, and use a proper build system (<code>make</code> is enough for such a simple application). In the documentation, you can include a discussion of your solving algorithm, including analysis of its efficiency (asymptotic complexity/Big-O as a minimum.)</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T21:15:57.747", "Id": "45198", "Score": "0", "body": "Thanks, that is an excellent list of what I can indeed improve. I'll probably start over entirely." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T21:20:29.410", "Id": "45200", "Score": "1", "body": "It is absolutely OK (and encouraged!) to make a new code review when you have changed your code. Even more so if you start all over." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T21:15:47.960", "Id": "45269", "Score": "0", "body": "`Make your solver handle boards with multiple solutions.` Technically a sudoku board only has one solution. If it has more than one solution and you are guessing at any square then it is not really a sudoku board." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-11T19:31:56.743", "Id": "270029", "Score": "0", "body": "What is unprofessional about the \"press any key to exit\" part? (I agree it is not really useful, but I do not understand why it is unprofessional.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-13T09:20:33.443", "Id": "270325", "Score": "0", "body": "I'll respectfully disagree on \"Put a `default` in your `switch` to catch errors.\" If you have appropriate compiler warnings, a `default` can *hide* errors that the compiler can pick up when switching on an enumeration such as this. A `default` leaves that detection until runtime. (This works best of all when all cases `return`, because you can get the best of both worlds and put exceptional cases after the `switch`, that are reached only if you've casted an out-of-range integer into the enumerator value)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-13T09:22:44.977", "Id": "270326", "Score": "0", "body": "@Attillio - That's the first thing I removed when I tried running the code. It stops the process from termination when running it in a test environment that doesn't provide any stdin (I built and ran it in Emacs using `M-x compile`). It's really irritating to have to kill the process rather than just getting a sensible exit code." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T18:50:08.073", "Id": "28752", "ParentId": "28746", "Score": "13" } }, { "body": "<p>Other answers address the body of your code. I'm going to <s>pick on</s> <em>improve</em> the tests.</p>\n\n<p>Firstly, it's great that you have written some tests. I see far too much code written by those who believe they can \"just get it right\", but actually can't (yes, I confess I sometimes find some of my own code without automated tests). I'm a strong advocate of test-driven development, which forces you to think of how to test before even writing any code.</p>\n\n<p>Your tests will be much easier to read if each board was evaluated in its own test method:</p>\n\n<pre><code>// For test use, expose the protected methods for verification\nclass TestableSudoku : public Sudoku\n{\npublic:\n using Sudoku::Sudoku;\n using Sudoku::checkValidRows;\n using Sudoku::checkValidCols;\n using Sudoku::checkValidSquares;\n using Sudoku::checkValid;\n};\n\nstatic void testZeros()\n{\n\n short boardData[9][9] = {\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0}\n };\n\n TestableSudoku board (boardData);\n\n assert(board.checkValidRows());\n assert(board.checkValidCols());\n assert(board.checkValidSquares());\n assert(board.checkValid());\n assert(board.solve() == SR_SOLVED);\n}\n</code></pre>\n\n<p>Here, I've removed the test method from the <code>Sudoku</code> class. It's possibly a point of opinion, but to me, the tests are something you <em>do to</em> an object rather than part of the <em>function of</em> an object. The idea being that if <code>Sudoku</code> were a library, then the test program could link to that library just like any other client code.</p>\n\n<p>In order to expose the <code>protected</code> members, I've created a class just for the test that exposes these. We could possibly go further, by specifying in one go which conditions we expect to be true:</p>\n\n<pre><code>const int ROWS_VALID = 1;\nconst int COLS_VALID = 2;\nconst int SQUARES_VALID = 4;\nconst int BOARD_VALID = 8;\n\n// For test use, expose the protected methods for verification\nclass TestableSudoku : public Sudoku\n{\npublic:\n using Sudoku::Sudoku;\n\n inline static bool expect(int flags, int mask)\n {\n return flags &amp; mask;\n }\n\n void checkValidity(SolutionResult result, int flags)\n {\n assert(expect(flags, ROWS_VALID) == checkValidRows());\n assert(expect(flags, COLS_VALID) == checkValidCols());\n assert(expect(flags, SQUARES_VALID) == checkValidSquares());\n assert(expect(flags, BOARD_VALID) == checkValid());\n assert(solve() == result);\n }\n};\n\nstatic void testZeros()\n{\n\n short boardData[9][9] = {\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0}\n };\n\n TestableSudoku board (boardData);\n board.checkValidity(SR_SOLVED, ROWS_VALID | COLS_VALID | SQUARES_VALID | BOARD_VALID);\n}\n</code></pre>\n\n<p>The motivation for this is that it's taking us towards data-driven tests. Instead of each test having custom logic for its setup and assertions, the logic is the same for all tests, and only the inputs and outputs change:</p>\n\n<pre><code>// Common control for all tests\nconst int ROWS_VALID = 1;\nconst int COLS_VALID = 2;\nconst int SQUARES_VALID = 4;\nconst int BOARD_VALID = 8;\n\nclass TestableSudoku : public Sudoku\n{\npublic:\n using Sudoku::Sudoku;\n\n inline static bool expect(int flags, int mask)\n {\n return flags &amp; mask;\n }\n\n void checkValidity(SolutionResult result, int flags)\n {\n assert(expect(flags, ROWS_VALID) == checkValidRows());\n assert(expect(flags, COLS_VALID) == checkValidCols());\n assert(expect(flags, SQUARES_VALID) == checkValidSquares());\n assert(expect(flags, BOARD_VALID) == checkValid());\n assert(solve() == result);\n }\n\n void checkRow(int row, const short (&amp;expected)[9])\n {\n assert(!memcmp(values[row], expected, 9 * sizeof *expected));\n }\n};\n\nstatic TestableSudoku testBoard(short boardData[9][9],\n SolutionResult result,\n int flags)\n{\n TestableSudoku board (boardData);\n board.checkValidity(result, flags);\n return board;\n}\n</code></pre>\n\n\n\n<pre><code>// Our tests now just supply data to the logic above\nstatic void testZeros()\n{\n short board[9][9] = {\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0, 0}\n };\n testBoard(board, SR_SOLVED, ROWS_VALID | COLS_VALID | SQUARES_VALID | BOARD_VALID);\n}\n\nstatic void testValidPos1()\n{\n short board[9][9] = {\n {5, 3, 4, 6, 7, 8, 9, 1, 2},\n {6, 7, 2, 1, 9, 5, 3, 4, 8},\n {1, 9, 8, 3, 4, 2, 5, 6, 7},\n {8, 5, 9, 7, 6, 1, 4, 2, 3},\n {4, 2, 6, 8, 5, 3, 7, 9, 1},\n {7, 1, 3, 9, 2, 4, 8, 5, 6},\n {9, 6, 1, 5, 3, 7, 2, 8, 4},\n {2, 8, 7, 4, 1, 9, 6, 3, 5},\n {3, 4, 5, 2, 8, 6, 1, 7, 9}\n };\n testBoard(board, SR_SOLVED, ROWS_VALID | COLS_VALID | SQUARES_VALID | BOARD_VALID);\n}\n\nstatic void testValidPos2()\n{\n short board[9][9] = {\n {0, 0, 0, 0, 0, 0, 0, 0, 0},\n {6, 0, 2, 1, 0, 0, 0, 0, 0},\n {1, 0, 8, 3, 4, 2, 5, 6, 7},\n {0, 0, 9, 7, 0, 0, 4, 2, 3},\n {4, 0, 6, 8, 0, 0, 0, 0, 1},\n {7, 1, 3, 9, 2, 0, 8, 0, 0},\n {0, 0, 0, 5, 3, 0, 2, 8, 4},\n {0, 0, 0, 4, 1, 0, 6, 0, 0},\n {3, 0, 0, 0, 0, 6, 1, 0, 0}\n };\n auto solver = testBoard(board, SR_SOLVED, ROWS_VALID | COLS_VALID | SQUARES_VALID | BOARD_VALID);\n solver.checkRow(0, { 5, 3, 4, 6, 7, 8, 9, 1, 2});\n}\n\nstatic void testInvalidRows()\n{\n short board[9][9] = {\n {5, 3, 4, 6, 7, 8, 9, 1, 5},\n {6, 7, 2, 1, 9, 5, 3, 4, 8},\n {1, 9, 8, 3, 4, 2, 0, 6, 7},\n {8, 5, 9, 7, 6, 1, 4, 2, 3},\n {4, 2, 6, 8, 5, 3, 7, 9, 1},\n {7, 1, 3, 9, 2, 4, 8, 5, 6},\n {9, 6, 1, 5, 3, 7, 2, 8, 4},\n {2, 8, 7, 4, 1, 9, 6, 3, 0},\n {3, 4, 5, 2, 8, 6, 1, 7, 9}\n };\n testBoard(board, SR_INVALID, COLS_VALID | SQUARES_VALID);\n}\n</code></pre>\n\n<p>You now have something that's easier to maintain and reason about, and that's more amenable to being executed by a unit-test framework. Moving to such a framework is useful on bigger projects, because (unlike <code>assert()</code>) it can continue after the first failure (to report on all the failing tests) and it may give more informative failure messages (by printing the actual and expected values, as well as the failing expression).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-13T09:16:07.097", "Id": "144094", "ParentId": "28746", "Score": "0" } } ]
{ "AcceptedAnswerId": "28752", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T16:23:50.873", "Id": "28746", "Score": "8", "Tags": [ "c++", "recursion", "sudoku" ], "Title": "Entry-level recursive Sudoku solver" }
28746
<p>I have mongoose model:</p> <pre><code>var mongoose = require('mongoose'), Schema = mongoose.Schema, Imager = require('imager'), env = process.env.NODE_ENV || 'development', config = require('../../config/config')[env], imagerConfig = require(config.root + '/config/imager.js'); var LinkSchema = new Schema({ title: { type: String, 'default': '', trim: true }, siteName: { type: String, 'default': '', trim: true }, url: { type: String, 'default': '', trim: true }, description: { type: String, 'default': '', trim: true }, image: { cdnUri: String, files: [] }, tags: { type: [], 'default': [] }, createdAt: { type: Date, 'default': Date.now }, user: { type: Schema.ObjectId, 'default': null, ref: 'User' } }); var isStringPresence = function (value) { return !!value &amp;&amp; value.length &gt; 0; }; LinkSchema.path('title').validate(function (title) { return isStringPresence(title); }, 'Title cannot be blank'); LinkSchema.path('url').validate(function (url) { return isStringPresence(url); }, 'URL cannot be blank'); LinkSchema.path('user').validate(function (user) { return !!user; }, 'Link must be linked to a user'); LinkSchema.pre('remove', function (next) { var imager = new Imager(imagerConfig, 'S3'), files = this.image.files; // if there are files associated with the link, remove from the cloud too imager.remove(files, function (err) { if (err) { return next(err); } }, 'link'); next(); }); LinkSchema.methods = { uploadAndSave: function (images, callback) { if (!images || !images.length) { return this.save(callback); } var imager = new Imager(imagerConfig, 'S3'), self = this; imager.upload(images, function (err, cdnUri, files) { if (err) { return callback(err); } if (files.length) { self.image = { cdnUri: cdnUri, files: files }; } self.save(callback); }, 'link'); } }; LinkSchema.statics = { load: function (id, callback) { this.findOne({ _id : id }) .populate('user', 'name email') .exec(callback); }, list: function (options, callback) { var criteria = options.criteria || {}; this.find(criteria) .populate('user', 'name') .sort(options.sort || {'createdAt': -1}) // sort by date .limit(options.perPage) .skip(options.perPage * options.page) .exec(callback); } }; module.exports = mongoose.model('Link', LinkSchema); </code></pre> <p>I am trying to write correct test file for this model. I am using mocha for this. This is what I end up with:</p> <pre><code>if ( process.env.NODE_ENV !== 'test' ) { console.log('NODE_ENV=' + process.env.NODE_ENV + ' which might cause problems.'); process.exit(1); } var config = require('../config/config')[process.env.NODE_ENV]; var mongoose = require('mongoose'); var Link = require('../app/models/link'); var User = require('../app/models/link'); var should = require('should'); var Factory = require('./support/factories'); var helpers = require('./support/helpers'); var facebookUser = null; describe('Link Model', function() { before(function(done) { if (mongoose.connection.db) { return done(); } mongoose.connect(config.db, done); }); after(function(done){ mongoose.connection.db.dropDatabase(function(){ mongoose.connection.close(done); }); }); beforeEach(function(done){ mongoose.connection.db.dropDatabase(function(err){ if (err) return done(err); Factory.build('facebookUser', function(user) { facebookUser = user; done(); }); }); }); var saveLinkWithBlankTitle = function(done) { return function(link) { link.save(function (err, storedLink) { err.errors.title.type.should.equal('Title cannot be blank'); done(); }); }; }; it("Creates invalid link with title='')", function(done){ Factory.build('link', {user: facebookUser, title: ''}, saveLinkWithBlankTitle(done)); }); it('Creates invalid link with title=null)', function(done){ Factory.build('link', {user: facebookUser, title: null}, saveLinkWithBlankTitle(done)); }); it('Creates invalid link with title=undefined)', function(done){ Factory.build('link', {user: facebookUser, title: undefined}, saveLinkWithBlankTitle(done)); }); var saveLinkWithBlankUrl = function(done) { return function(link) { link.save(function (err, storedLink) { err.errors.url.type.should.equal('URL cannot be blank'); done(); }); }; }; it("Creates invalid link with url='')", function(done){ Factory.build('link', {user: facebookUser, url: ''}, saveLinkWithBlankUrl(done)); }); it('Creates invalid link with url=null)', function(done){ Factory.build('link', {user: facebookUser, url: null}, saveLinkWithBlankUrl(done)); }); it('Creates invalid link with url=undefined)', function(done){ Factory.build('link', {user: facebookUser, url: undefined}, saveLinkWithBlankUrl(done)); }); var saveLinkWithNoUser = function(done) { return function(link) { link.save(function (err, storedLink) { err.errors.user.type.should.equal('Link must be linked to a user'); done(); }); }; }; it('Creates invalid link with no user', function(done){ Factory.build('link', saveLinkWithNoUser(done)); }); it('Creates invalid link with user=null', function(done){ Factory.build('link', {user: null}, saveLinkWithNoUser(done)); }); it('Creates invalid link with user=undefined', function(done){ Factory.build('link', {user: undefined}, saveLinkWithNoUser(done)); }); it('Creates a valid link (without image)', function(done){ Factory.build('link', {user: facebookUser}, function(link) { link.save(function (err, storedLink) { if (err) return done(err); storedLink.title.should.equal(link.title); storedLink.siteName.should.equal(link.siteName); storedLink.url.should.equal(link.url); storedLink.description.should.equal(link.description); storedLink.tags.should.equal(link.tags); done(); }); }); }); it('Loads existing link', function(done){ Factory.create('link', {user: facebookUser}, function(storedLink) { Link.load(storedLink._id, function(err, loadedLink) { if (err) return done(err); loadedLink._id.equals(storedLink._id).should.be.true; done(); }); }); }); it('Loads links list', function(done){ Factory.create('link', {user: facebookUser, title: 'Title1', description: 'a'}, function(link1) { Factory.create('link', {user: facebookUser, title: 'Title2', description: 'b'}, function(link2) { Factory.create('link', {user: facebookUser, title: 'Title3', description: 'a'}, function(link3) { Factory.create('link', {user: facebookUser, title: 'Title4', description: 'b'}, function(link4) { Factory.create('link', {user: facebookUser, title: 'Title5', description: 'a'}, function(link5) { Factory.create('link', {user: facebookUser, title: 'Title6', description: 'b'}, function(link6) { Factory.create('link', {user: facebookUser, title: 'Title7', description: 'a'}, function(link7) { Link.list({ criteria: {description: 'a'}, sort: {'createdAt': 1}, perPage: 2, page: 1 }, function(err, list) { if (err) return done(err); list.length.should.equal(2); list[0].title.should.equal('Title5'); list[1].title.should.equal('Title7'); done(); }); }); }); }); }); }); }); }); }); }); </code></pre> <p>I am using factory lady, here is the code:</p> <pre><code>var Factory = require('factory-lady'); var Link = require('../../app/models/link'); var User = require('../../app/models/user'); Factory.define('link', Link, { title: 'My title', siteName: 'My site name', url: 'http://www.example.com', description: 'My description', tags: ['MyFirstTag', 'MySecondTag', 'MyThirdTag'] }); Factory.define('facebookUser', User, { name: 'Facebook User', email: 'user@facebook.com', username: 'fbuser', provider: 'facebook', hashed_password: 'hashed', salt: 'salt', facebook: { } }); module.exports = Factory; </code></pre> <ol> <li>This is my first time of writing tests. Does my code fine? </li> <li>Do I miss anything things? </li> <li>How can I make my code shorter? </li> <li>How can I prevent the callbacks pyramid?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T18:08:08.610", "Id": "70452", "Score": "1", "body": "As for the \"callbacks pyramid\". You can use the module async https://github.com/caolan/async. There is a bunch of control flow helpers. This one might become one of your new friend https://github.com/caolan/async#waterfall." } ]
[ { "body": "<p>Fun code,</p>\n\n<p>there are a few Mocha / Jasmine submissions on this site, and this one is by far the easiest to follow. Which is all kinds of funny since this is the first time you are writing tests ;)</p>\n\n<p>For your questions:</p>\n\n<ul>\n<li>Your code looks fine, it seems that Mocha and should.js play very nice together and naturally drive you to grokkable code.</li>\n<li>I did not find anything obviously missing</li>\n<li>I did not find your code too long, you have to set up the test and you have to validate the result, seems fine to me</li>\n<li>Callback pyramids -> There are a bunch of modules for that our there, you need to do some research, I like <a href=\"https://github.com/kriskowal/q\" rel=\"nofollow\">Q</a> myself</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-11T15:33:37.917", "Id": "46935", "ParentId": "28758", "Score": "3" } }, { "body": "<p>The code looks pretty good. There are just a few stylistic things I would do differently.</p>\n\n<p><strong>1. Nested Describes</strong></p>\n\n<p>You have quite a few tests which essentially test the same method of your model. Specifically, your tests which call functions like: <code>saveLinkWithNoUser</code> are all testing the <code>Link.save</code>. In cases like this, you can further organize your tests to be more descriptive by running those in a nested define.</p>\n\n<p>eg:</p>\n\n<pre><code>describe( 'Link Model', function() {\n // ... setup code, helper functions, etc\n describe( '#save', function() {\n it(\"Creates invalid link with title='')\", function(done){\n //.. run the test\n });\n });\n});\n</code></pre>\n\n<p><strong>2. Improper 'it' descriptions</strong>\nThe output of your tests should be a definition of your model. On lines like:</p>\n\n<p><code>it('Creates invalid link with title=null)' ...)};</code></p>\n\n<p>you are describing the test, not the model. Your output will say something like: </p>\n\n<pre><code>Link Model\n Creates invalid link with title=null\n</code></pre>\n\n<p>The preferred description in my opinion would describe the models actual behavior with invalid links:</p>\n\n<pre><code>Link Model\n Disallows creation of links with title=null\n</code></pre>\n\n<p>If you follow bold points 1 and 2 your output would be something like:</p>\n\n<pre><code>Link Model\n #save\n Disallows creation of links with title=null\n</code></pre>\n\n<p><strong>3. Explicitly changing property values in Factory build chain</strong></p>\n\n<p>This point may be caused to improvements to <code>factory-lady</code> since the time of your post. But the <a href=\"https://github.com/petejkim/factory-lady#defining-factories\" rel=\"nofollow\">factory-lady documentation</a> shows that you can use functions to change properties of contiguously built instances. This would take quite a bit of the hardcoded values out of your links list test.</p>\n\n<p>Sidenote: consider switching to <a href=\"https://github.com/aexmachina/factory-girl\" rel=\"nofollow\">factory-girl</a> which is an enhanced fork of factory-lady that implements some candy like <code>Factory.buildMany</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-01T19:10:03.397", "Id": "88572", "ParentId": "28758", "Score": "9" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T20:26:57.263", "Id": "28758", "Score": "15", "Tags": [ "javascript", "unit-testing", "node.js", "mongodb", "mocha" ], "Title": "Test mongoose model" }
28758
<p>I want a task scheduler with some specific capabilities for my application. I've searched for a good library that provides me with the following, but found nothing.</p> <ul> <li>Queuing awaitable tasks.</li> <li>Ability to stop started jobs.</li> <li>Ability to repeat some jobs.</li> <li>Ability to cancel repeat enabled jobs.</li> <li>Specifying a priority foreach schedule.</li> <li>Running schedulers on a separate thread [optionable].</li> <li>Add <code>Task&lt;string&gt;</code> and <code>Task&lt;bool&gt;</code></li> </ul> <p>So, I've decided to create my own and I want you to review my code for improvements:</p> <ul> <li>Detailed review of my code for errors, drawbacks.</li> <li>How I can make my code run every scheduler on a separate thread in an efficient way.</li> <li>Any more suggestions to help making my code more reliable and more professional, along with new features.</li> </ul> <p></p> <pre><code>public static class TaskManager { private static List&lt;Scheduler&gt; _schedulers; /// &lt;summary&gt; /// Gets a list of currently running schedulers. /// &lt;/summary&gt; public static IEnumerable&lt;Scheduler&gt; RunningSchedulers { get { return _schedulers.Where(scheduler =&gt; scheduler.IsRunning()); } } /// &lt;summary&gt; /// Gets all scheduleres. /// &lt;/summary&gt; public static IEnumerable&lt;Scheduler&gt; AllSchedulers(string name) { return _schedulers; } /// &lt;summary&gt; /// Gets a scheduler by it's name. /// &lt;/summary&gt; public static Scheduler GetScheduler(string name) { return _schedulers.Find(scheduler =&gt; scheduler.Name == name); } /// &lt;summary&gt; /// Attempts to remove a scheduler from the list. /// &lt;/summary&gt; public static bool RemoveScheduler(Scheduler scheduler) { return _schedulers.Remove(scheduler); } /// &lt;summary&gt; /// Creates a new scheduler and adds it the the list. /// &lt;/summary&gt; public static Scheduler CreateScheduler(int priority, string name = null) { if (_schedulers == null) _schedulers = new List&lt;Scheduler&gt;(); var scheduler = new Scheduler(priority, name); _schedulers.Add(scheduler); return scheduler; } } public class Scheduler : Queue&lt;Job&gt; { public string Name { get; private set; } public int Priority { get; set; } private Timer _triggerTimer; public int Interval { get; private set; } public EventHandler&lt;Job&gt; Trigger; public Scheduler(int priority, string name = null) { Priority = priority; Name = name; Interval = 20; } private void TriggerTimerCallBack(object state) { foreach (Job job in this.Where(job =&gt; DateTime.Now &gt;= job.Execution &amp;&amp; !job.Triggered)) { job.Triggered = true; if (job.Repeating) job.StartRepeating(); Trigger(this, job); } } /// &lt;summary&gt; /// Sets the trigger timer interval. /// &lt;/summary&gt; public void SetRefreshInterval(int interval) { Interval = interval; } /// &lt;summary&gt; /// Gets all the triggered jobs. /// &lt;/summary&gt; public IEnumerable&lt;Job&gt; GetTriggeredJobs() { return this.Where(job =&gt; job.Triggered); } /// &lt;summary&gt; /// Gets all the repeat enabled jobs. /// &lt;/summary&gt; public IEnumerable&lt;Job&gt; GetRepeatingJobs() { return this.Where(job =&gt; job.Repeating); } /// &lt;summary&gt; /// Returns whether the schedular is running. /// &lt;/summary&gt; public bool IsRunning() { return _triggerTimer != null; } /// &lt;summary&gt; /// Stops the scheduler. /// &lt;/summary&gt; public void Stop() { if (null == _triggerTimer) return; _triggerTimer.Dispose(); _triggerTimer = null; } /// &lt;summary&gt; /// Starts the scheduler. /// &lt;/summary&gt; public void Start() { if (_triggerTimer != null) return; _triggerTimer = new Timer(TriggerTimerCallBack, null, 0, Interval); } } public class Job : EventArgs, IDisposable { public string Name { get; set; } public Func&lt;Task&gt; Task { get; set; } public DateTime Execution { get; private set; } public bool Triggered { get; set; } public bool Repeating { get; set; } private int _interval; private Timer _triggerTimer; public Job(Func&lt;Task&gt; task, DateTime executionTime, string name = null) { Name = name; Task = task; Execution = executionTime; } public Job TriggerEvery(int interval) { _interval = interval; Repeating = true; return this; } public Job Seconds() { _interval = (_interval)*1000; return this; } public Job Minutes() { _interval = _interval*(1000*60); return this; } public Job Hours() { _interval = _interval*(60*60*1000); return this; } public Job Days() { _interval = _interval*(60*60*24*1000); return this; } public void TriggerTimerCallBack(object sender) { if (Triggered) Triggered = false; } public void StartRepeating() { if (null != _triggerTimer) return; _triggerTimer = new Timer(TriggerTimerCallBack, null, _interval, _interval); } public void StopRepeating() { if (null == _triggerTimer) return; _triggerTimer.Dispose(); _triggerTimer = null; } public void Dispose() { StopRepeating(); } } </code></pre> <p><strong>Usage</strong></p> <pre><code>#region Initializing Schedulers var meetings = TaskManager.CreateScheduler(0, "Meeting Scheduler"); var jobs = TaskManager.CreateScheduler(1, "Work Scheduler"); #endregion #region EventHandler Registration meetings.Trigger += (sender, job) =&gt; Console.WriteLine(job.Name); jobs.Trigger += (sender, job) =&gt; Console.WriteLine(job.Name); #endregion #region Adding Jobs //One time meeting to be triggered after 15 seconds. meetings.Add(new Job(Job, DateTime.Now.AddSeconds(15), "Meet Barack Obama")); //Repeated meeting to be triggered after 5 days and repeated every 5 days. meetings.Add(new Job(Job, DateTime.Now.AddDays(5), "Visit Your Dad").TriggerEvery(5).Days()); //Repeated job to be triggered after 5 minutes and repeated every 2 hours. jobs.Add(new Job(Job, DateTime.Now.AddMinutes(5), "Make a cheese sandwich").TriggerEvery(2).Hours()); #endregion #region Starting Schedulers meetings.Start(); jobs.Start(); #endregion #region Extra Features //Get all running schedulers var allRunningSchedulers = TaskManager.RunningSchedulers; //Get all schedulers var allSchedulers = TaskManager.AllSchedulers; //Get specific scheduler by name var meetingScheduler = TaskManager.GetScheduler("Meeting Scheduler"); //Remove specific scheduler bool succeed = TaskManager.RemoveScheduler(meetingScheduler); //Get repeating jobs from scheduler IEnumerable&lt;Job&gt; steveJobs = meetingScheduler.GetRepeatingJobs(); //Get triggered jobs from scheduler IEnumerable&lt;Job&gt; triggeredJobs = meetingScheduler.GetTriggeredJobs(); #endregion Console.ReadLine(); </code></pre>
[]
[ { "body": "<p>The issues i see off the bat:</p>\n\n<p>1) In my experience this <code>Scheduler : Queue&lt;Job&gt;</code> is almost always a bad idea. If you are not directly overriding a <code>Queue</code> class methods - there is no reason to derive <code>Scheduler</code> from it. Futhermore, adding/removing schedules will cause exceptions, if it happens at the same time, as you enumerate your queue in timer callback. You should use aggregation instead and synchronize your queue.</p>\n\n<p>2) You should extract <code>IJob</code> interface. And use it in <code>Scheduler</code>. Because, for example, some guy might want to use your scheduler but he might not want to use <code>Task</code> class at all. Why force him? You could declare <code>IJob</code> like this (for example):</p>\n\n<pre><code>interface IJob : IDisposable\n{\n string Name {get;}\n DateTime ExecutionTime {get;}\n\n void Start();\n void Cancel();\n\n bool Repeat {get;}\n bool InProgress {get;}\n\n event Action&lt;IJob&gt; Started;\n event Action&lt;IJob&gt; Completed;\n event Action&lt;IJob, int&gt; ProgressChanged;\n}\n</code></pre>\n\n<p>It will give your scheduler and task manager all the control they need, without mentioning tasks at all. While you can still use tasks in your base implementation (<code>Job</code> class).</p>\n\n<p>3) Same goes for <code>IScheduler</code>.</p>\n\n<p>4) Methods such as <code>public Job TriggerEvery(int interval)</code>, <code>public Job Seconds()</code>, etc. do not belong to Job class and will only lead to confusion. There are better ways. You can declare them as extension methods. You can implement job factory and impelent those expressions there. Either way you should avoid forcing a guy, who is going to use your code, to use those expressions. You should allow him to simply set <code>_interval</code> (via property or constructor).</p>\n\n<p>5) <code>private int _interval;</code> what is int? Is it seconds? Is it ticks? Is it milliseconds? No way to tell without digging into your code. Use better naming, or use <code>TimeSpan</code>.</p>\n\n<p>6) <code>Job.StartRepeating()</code>, <code>Job.StopRepeating()</code> - those do not belong to job class either. Job class should have an indicator whether the task should be repeated forever or not and thats it. It should not run itself or repeat itself - that is the job for scheduler/task manager. Not to mention that im not even sure, what those methods do and if they work.</p>\n\n<p>7) You should never call events like that <code>Trigger(this, job);</code>. You can check Jeffrey Richter's books if you need details.</p>\n\n<p>8) <code>public bool IsRunning()</code> this should be a property.</p>\n\n<p>9) The idea behind your <code>TaskManager</code> is not quite clear. At the moment it looks like an overcomplicated dictionary. </p>\n\n<p>10) Your <code>Job</code>s are not being executed at any point. This is counter intuitive. If i add my job to scheduler/task manager, i expect it to run at designed time. Instead of triggering an event and let some external code handle the task itself, you should run the task with your scheduler/task manager instead (using the interface i suggested in (2) or your own). Because thats the whole point, no? You can still generate an event tho.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T08:54:50.557", "Id": "28812", "ParentId": "28760", "Score": "4" } } ]
{ "AcceptedAnswerId": "28812", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T21:44:34.150", "Id": "28760", "Score": "3", "Tags": [ "c#", "library", "scheduled-tasks" ], "Title": "Custom Task Scheduler" }
28760
<p>Please review this:</p> <pre><code>class KoolDailyReminderAfterWeek(webapp2.RequestHandler): def get(self): logging.info('sending reminders') timeline = datetime.now () - timedelta (days = 7) edge = datetime.now () - timedelta (days = 8) ads = Ad.all().filter("published =", True).filter("added &lt;", timeline).filter("url IN", ['www.koolbusiness.com']).filter("added &gt;", edge).fetch(99999) for ad in ads: logging.info('sending reminder to %s', ad.name) if ad.title: subject= ad.title else: subject = 'Reminder' message = mail.EmailMessage(sender='Kool Business &lt;info@koolbusiness.com&gt;', subject=subject) message.body = """ Hello!&lt;br&gt;Now your ad &lt;a href="http://www.koolbusiness.com/vi/%d.html"&gt;%s&lt;/a&gt; has been out for a week. If you already have sold your product you can remove your ad.&lt;br&gt;&lt;br&gt;Some advice to promote your ad:&lt;br&gt;Change + Renew the ad and it will be on top of the list. You can also change text and price.&lt;br&gt;Change the ad if you only want to lower the price or change the ad text&lt;br&gt;Renew so that the ad will be on top if the list. &lt;br&gt;&lt;br&gt;Best regards,&lt;br&gt;Koolbusiness.com """ % (ad.key().id(),ad.title) message.html = """ &lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt; Hello!&lt;br&gt;Now your ad &lt;a href="http://www.koolbusiness.com/vi/%d.html"&gt;%s&lt;/a&gt; has been out for a week. If you already have sold your product you can remove your ad.&lt;br&gt;&lt;br&gt;Some advice to promote your ad:&lt;br&gt;Change + Renew the ad and it will be on top of the list. You can also change text and price.&lt;br&gt;Change the ad if you only want to lower the price or change the ad text&lt;br&gt;Renew so that the ad will be on top if the list. &lt;br&gt;&lt;br&gt;Best regards,&lt;br&gt;Koolbusiness.com &lt;/body&gt;&lt;/html&gt; """ % (ad.key().id(),ad.title) message.to=ad.email message.send() logging.info('sent email to: ' +ad.email) </code></pre> <p>YAML</p> <pre><code> - description: daily mailout url: /report/dailyafterweek schedule: every 24 hours </code></pre> <p><a href="https://stackoverflow.com/questions/17767524/email-framework-for-appengine">Background</a></p>
[]
[ { "body": "<p>I'm not familiar with that framework, so I can only provide some general points:</p>\n\n<ul>\n<li>You can rewrite the <code>if</code> statement to <code>subject = ad.title or 'Reminder'</code> (see <a href=\"https://codereview.stackexchange.com/questions/27461/refactor-python-code-with-lots-of-none-type-checks/28002#28002\">here</a>).</li>\n<li>You are a bit inconsistent with spacings (before and after <code>=</code>, <code>,</code>, <code>()</code>, etc.), and string formatting (your second and third <code>logging.info</code>)</li>\n<li>I'd recomment spreading both those chained <code>filters</code> and overly long strings over multiple lines.</li>\n<li>Maybe you could use some helper method to derive the HTML version of the message from the plain-text version or vice versa?</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T08:03:53.553", "Id": "28770", "ParentId": "28768", "Score": "1" } } ]
{ "AcceptedAnswerId": "28770", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T04:37:04.267", "Id": "28768", "Score": "1", "Tags": [ "python", "email", "google-app-engine" ], "Title": "Email-sending class for GAE" }
28768
<p>I have written a sample immutable binary search tree using Scala. However, I am not sure whether or not I was doing it the proper way since I am not an expert at functional programming. Is there a better or more efficient way of, say, traversing the tree or adding an item to it using a purely functional approach?</p> <p>The add (+) method:</p> <pre><code>def +(data: T): Bst = { def insert(optTree: OptBst): Bst = optTree match { case None =&gt; BST(data)(comparison) case Some(tree) =&gt; comparison(data, tree.data) match { case cmp if cmp &lt; 0 =&gt; tree(left = Some(insert(tree.left))) case cmp if cmp &gt; 0 =&gt; tree(right = Some(insert(tree.right))) case _ =&gt; tree } } insert(Some(this)) } </code></pre> <p>Delete (-) method:</p> <pre><code>def -(data: T): OptBst = { def remove(optTree: OptBst): OptBst = optTree match { case None =&gt; None case Some(tree) =&gt; comparison(data, tree.data) match { case cmp if cmp &gt; 0 =&gt; Some(tree(right = remove(tree.right))) case cmp if cmp &lt; 0 =&gt; Some(tree(left = remove(tree.left))) case _ =&gt; (tree.hasLeft, tree.hasRight) match { case (false, false) =&gt; None case (true, false) =&gt; tree.left case (false, true) =&gt; tree.right case (true, true) =&gt; val rightMinData = tree.rightMin.get.data Some(tree(data = rightMinData, right = tree.right.get - rightMinData)) } } } remove(Option(this)) } </code></pre> <p>Search method:</p> <pre><code> def search(data: T) = { @tailrec def search(optTree: OptBst): OptBst = optTree match { case None =&gt; None case Some(tree) =&gt; comparison(data, tree.data) match { case cmp if cmp &lt; 0 =&gt; search(tree.left) case cmp if cmp &gt; 0 =&gt; search(tree.right) case _ =&gt; optTree } } search(Some(this)) } </code></pre>
[]
[ { "body": "<p>I think it would be an improvement to define an empty element. Currently you have no way to represent an empty collection. But that is required if you would want to integrate your data structure with scala collections.</p>\n\n<p>(In scala collections, you usually build up an immutable data structure like a Set or Map by starting with the empty element and adding elements. The apply methods defined in the companion objects are just convenience methods)</p>\n\n<p>Defining an empty element will also simplify your code a lot. For example: you won't have to use Option for left and right, but can just use the empty value if e.g. left does not contain elements. For iteration for example you don't have to check whether left or right is empty by checking for None, but just call the method on the child.</p>\n\n<p>In the simplest case this will look something like this:</p>\n\n<pre><code>object BST {\n def empty[T](implicit c:(T,T) =&gt; Int) : BST[T] = new EmptyBST(c)\n}\n\nsealed abstract class BST[T] {\n // abstract: whatever methods you want to support\n}\n\ncase class EmptyBST[T](c:(T,T) =&gt; Int) extends BST[T] {\n // trivial implementation of all methods for an empty BST\n}\n\ncase class NonEmptyBST[T](left:BST[T], right:BST[T], value:T, c:(T,T) =&gt; Int) extends BST {\n // non-trivial implementation of all methods for the non-empty case\n}\n</code></pre>\n\n<p>Another thing: using (T,T) => Int is perfectly fine for educational purposes. But if you want this to match the style of other scala collections, you should use <a href=\"http://www.scala-lang.org/api/current/index.html#scala.math.Ordering\">scala.math.Ordering</a>. There are already predefined orderings and some utility methods to create orderings for composite objects like tuples.</p>\n\n<p>For the traversal, I would not return a List[T] of all elements but instead just implement the Traversable[T] trait by defining a foreach method for each traversal order. That is much more efficient in case the user is not interested in everything but just the first few elements. And if the user wants a List[T] he can always make one by calling .toList. Traversal using foreach uses side effects internally, but for the end user these are not observable, so it's OK.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T10:45:04.650", "Id": "28775", "ParentId": "28773", "Score": "6" } } ]
{ "AcceptedAnswerId": "28775", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T10:29:36.160", "Id": "28773", "Score": "4", "Tags": [ "scala", "tree" ], "Title": "Immutable binary search tree using Scala" }
28773
HDL stands for hardware description language. The most common examples are VHDL and verilog.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T10:57:07.697", "Id": "28778", "Score": "0", "Tags": null, "Title": null }
28778
<p>How could this VHDL counter and its test bench be improved? I am interested in anything you see that could be done better, but especially in the test bench:</p> <ul> <li>Is <code>wait for 10 ns</code> better or worse than any other time delay?</li> <li>The test is very minimal. Should it do more?</li> </ul> <p><strong>counter32.vhdl</strong>:</p> <pre><code>library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; entity counter32 is port ( clk: in std_ulogic; ena: in std_ulogic; rst: in std_ulogic; q : out std_ulogic_vector(31 downto 0)); end entity; architecture rtl of counter32 is signal count : unsigned(31 downto 0); begin process(clk, rst) begin if rst = '1' then count &lt;= X"00000000"; elsif rising_edge(clk) then if ena = '1' then count &lt;= count + 1; end if; end if; end process; q &lt;= std_ulogic_vector(count); end architecture; </code></pre> <p><strong>counter32_tb.vhdl</strong>:</p> <pre><code>library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; entity counter32_tb is end counter32_tb; architecture tb of counter32_tb is component counter32 port ( clk: in std_ulogic; ena: in std_ulogic; rst: in std_ulogic; q : out std_ulogic_vector(31 downto 0)); end component; signal clk: std_ulogic; signal ena: std_ulogic; signal rst: std_ulogic; signal q : std_ulogic_vector(31 downto 0); begin dut : counter32 port map ( clk =&gt; clk, ena =&gt; ena, rst =&gt; rst, q =&gt; q); process begin -- Reset clk &lt;= '0'; ena &lt;= '1'; rst &lt;= '1'; wait for 10 ns; rst &lt;= '0'; wait for 10 ns; -- Counts on clock leading edge if enabled clk &lt;= '1'; wait for 10 ns; assert q = x"00000001"; -- Does not count on clock trailing edge clk &lt;= '0'; wait for 10 ns; assert q = x"00000001"; -- Does not count when not enabled ena &lt;= '0'; clk &lt;= '1'; wait for 10 ns; assert q = x"00000001"; -- Clears on reset rst &lt;= '1'; wait for 10 ns; assert q = x"00000000"; wait; end process; end tb; </code></pre> <p>Shell script to run the test bench in <a href="http://home.gna.org/ghdl/">GHDL</a>:</p> <pre><code>OPTS=--workdir=build ghdl -a ${OPTS} *.vhdl ghdl -e ${OPTS} counter32_tb ghdl -r ${OPTS} counter32_tb --vcd=counter32.vcd </code></pre>
[]
[ { "body": "<p>Contrary to what Aseem Bansal states, there is no need to use <code>std_logic</code> alone. Your use of <code>std_ulogic</code> is fine.</p>\n\n<p>One place where there is a trade-off to be pondered is on your top-level entity (the one which defines the whole chip). The tools that generate the output will create you a simulation model with all the gates and delays in, but it will have std_logic on the IO pins. This can be plugged straight into your existing testbench if you've already used <code>std_logic</code> at the top. </p>\n\n<p>You can avoid lots of duplicated typing by using direct instantiation. You don't need this at all:</p>\n\n<pre><code>component counter32\n port (\n clk: in std_ulogic;\n ena: in std_ulogic;\n rst: in std_ulogic;\n q : out std_ulogic_vector(31 downto 0));\n end component;\n</code></pre>\n\n<p>if you do this:</p>\n\n<pre><code> dut : entity work.counter32 port map (\n clk =&gt; clk,\n ena =&gt; ena,\n rst =&gt; rst,\n q =&gt; q);\n</code></pre>\n\n<p>This is the preferred method these days.</p>\n\n<p>In your testbench, I would separate out the clock generation to its own process. Or even to a single line:</p>\n\n<pre><code>clk &lt;= not clock after 10 ns when finished /= '1' else '0';\n</code></pre>\n\n<p>Create a signal called <code>finished</code> which is <code>std_logic</code>. You can then drive it low from every source and data-checking entity in the testbench, and drive it to '1' as each of them finish. Once they have all finished, the signal will finally resolve to '1' and the clock will stop.</p>\n\n<p>You can then use <code>wait for rising_edge(clk)</code> in your checking process, to wait for the appropriate clock edges (I'm sure you can guess how to wait for a falling edge :)</p>\n\n<p>I would also add a test to check it rolls over correctly. This can be a pain for such a big counter, so you might want to have a <code>generic</code> to control the width and then you can test a smaller counter to start with. You can wait for multiple clock ticks with a <code>for</code> loop with a <code>wait for rising_edge</code> inside. </p>\n\n<p>While I'm here, some good stuff you've already done:</p>\n\n<ul>\n<li>Full marks for using <code>numeric_std</code>. </li>\n<li>And for <code>std_ulogic</code> - it helps avoid multiple driver mistakes very early on!</li>\n<li>Creating a self-checking testbench is something often overlooked, it's a great habit to get into.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T10:48:17.657", "Id": "28823", "ParentId": "28784", "Score": "7" } }, { "body": "<p>Nice with some HDL on Code Review. I'll contribute with my opinions. All-in-all, I find the code all well-written.</p>\n<h1>Opinions not already covered in previous answers</h1>\n<ul>\n<li><p>A more standard way of setting <code>count</code> at reset would be <code>(others =&gt; '0')</code>.</p>\n<ul>\n<li>That is, as opposed to hard-coding a bit/hex literal - <em>even</em> if you for some reason hard-code the width as you have done, <code>(others =&gt; '0')</code> is more standard in this case.</li>\n</ul>\n</li>\n<li><p>You might have a good reason for asynchronous reset, but if not, synchronous reset is a better habit.</p>\n<ul>\n<li>You often see these asynchronous resets, it is unfortunately a more common habit, since that's what is (or was) most often taught.</li>\n<li>See my motivations here: <a href=\"http://www.fpga-dev.com/resets-make-them-synchronous-and-local/\" rel=\"noreferrer\">http://www.fpga-dev.com/resets-make-them-synchronous-and-local/</a></li>\n</ul>\n</li>\n</ul>\n<h1>Opinions already covered/partly covered</h1>\n<p>Somewhat in order of importance (in my subjective opinion).</p>\n<ul>\n<li><p>Define the roll-over behaviour.</p>\n<ul>\n<li>The behaviour <em>is</em> actually defined for an <code>unsigned</code> in <code>numeric_std</code>: any carry bits will be ignored so the <code>unsigned</code> will roll-over. However, neither simulators nor synthesis tools should be trusted on following this. (And even less, humans reading the code.) Also; it is good to really think about what behaviour you desire, or is the most stable: roll-over or saturate? I'll take the chance to give two comments on this choice:\n<ul>\n<li>For synthesis, roll-over rather than saturation will yield less logic and improved timing. The tool will be able to use a counter macro right-off.</li>\n<li>If reaching max count is expected never to happen, add an assertion so a simulation will flag in that case. Then still code the RTL behaviour explicitly to roll-over (less logic, better timing) if there aren't stability reasons to code it to saturate.</li>\n</ul>\n</li>\n</ul>\n</li>\n<li><p>Parameterize the width. Put it in a constant or generic.</p>\n</li>\n<li><p>Generate the clock separately (e.g. <code>clk &lt;= not(clk) after 10 ns;</code>, and make sure to init <code>clk</code> to <code>'1'</code>.</p>\n<ul>\n<li>This is more standard and more readable.</li>\n<li>Then, when coding your stimuli, do not dead-reckon the time for stimuli assignments, instead, use <code>wait until rising_edge(clk);</code> etc. This makes code more stable, and gives deterministic and proper times for the stimuli changes (not only in regards to time, but also to simulation deltas, which is equally important).</li>\n</ul>\n</li>\n<li><p>Use entity instantiation</p>\n<ul>\n<li>More details and motivation: <a href=\"http://www.fpga-dev.com/leaner-vhdl-with-entity-instantiation/\" rel=\"noreferrer\">http://www.fpga-dev.com/leaner-vhdl-with-entity-instantiation/</a></li>\n</ul>\n</li>\n</ul>\n<h1>Simulation performance</h1>\n<ul>\n<li>There's nothing wrong in coding the RTL of the counter like this, but it could be noted that there is a simulation performance gain possible: Make <code>count</code> a <code>variable</code>, local to the process, do tests and arithmetics on this variable, and in the end of the process drive the variable to a counter <code>signal</code> (defined in the architecture).</li>\n</ul>\n<h1>Others</h1>\n<ul>\n<li>Thumbs up for self-checking test benches.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-03T13:43:23.807", "Id": "105925", "Score": "0", "body": "Thank you for the outstanding contribution, and welcome to codereview!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-03T11:55:33.170", "Id": "58908", "ParentId": "28784", "Score": "8" } } ]
{ "AcceptedAnswerId": "58908", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T16:12:31.523", "Id": "28784", "Score": "14", "Tags": [ "unit-testing", "vhdl", "hdl" ], "Title": "32-bit counter and test bench" }
28784
<p>The point of my code is to:</p> <ul> <li><p>Read in the observed data from the a catalog of stars (whitespace separated table).</p></li> <li><p>Do some unit conversions on the observed data (math stuff).</p></li> <li><p>Apply an interstellar correction factor to the observed data (more math).</p></li> <li><p>Compare the scaled observed data to the DUSTY model data using the BC table, using a least-squares approach (comparison of observed data to theoretical models found in a large table).</p></li> <li><p>Find the best fit models for the observed data (should be obvious).</p></li> </ul> <p>I'm trying to rewrite 'spaghetti code' I was handed, that doesn't function quickly, nor does it allow for easy updating (adding different statistical calculations, etc.). I'm pretty new to Python, so I'm struggling with the idea of classes and this is my attempt at it.</p> <pre><code>class Stellar_setup: Fbol=5.01333e-10 c=2.99792458e+8 L=1000 star_list=[] dusty_models=np.array([]) #Array of all the dusty models incoming_stars='' #List of incoming stars def __init__(self): """Initiates the below modules.""" self.star_catalog() self.InputKey() def star_catalog(self): """Imports the star catalog""" try: star_catalog=raw_input('Input pathname of stellar catalog: ') star_list=[] with open(star_catalog) as incoming_stars: for line in incoming_stars.readlines(): x=[item for item in line.split()] star_list.append(x) #Appends the individual star-IDs to the empty array star_list. print 'Stars imported successfully.' except IOError: print 'Star import unsuccessful. Check that the star catalog file-path is correct. Program exiting now.' sys.exit() def InputKey(self): """Imports the Input (.inp) file. Historically, InputUt.inp. Allows for definition of parameters which are utilized later in the script.""" input_script=raw_input('Pathname of .inp file: ') InputKey=[] try: with open(input_script) as input_key: for line in input_key.readlines(): x=[item for item in line.split()] InputKey.append(x) if InputKey[0][0]=='1' or InputKey[0][0]=='2': #Checks to see if .inp file is valid or not by checking the first row/column which should be 1 or 2. print 'Your .inp file was successfully imported' else: print 'Your .inp file import failed. Check the validity of your file.\n Program exiting now.' sys.exit() except IOError: print 'The .inp file import was unsuccessful. Check that your file-path is valid.\n Program exiting now.' sys.exit() # You probably need to put a module here that pulls in the DUSTY tables. if __name__=='__main__': Stellar_setup() </code></pre> <p>I was thinking about making about three other classes that:</p> <ul> <li>Identify necessary attributes from the tables (pulling data from columns/rows)</li> <li>Do analysis of information, and model/data comparison to find the best theoretical models that match up with the observed data. This uses a least-squares approach.</li> </ul> <p>From what I understand classes can 'inherit' attributes from other classes. The way I think I understand this is that my class <code>Stellar_setup</code> will be inherited by my class <code>Attribute_Identification</code> (which haven't been written yet), and so on. I'm not sure if I'm going about this the right way, can anyone clear things up for me.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T18:21:34.370", "Id": "45265", "Score": "0", "body": "Ironically, I read the last sentence first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T18:22:06.637", "Id": "45266", "Score": "0", "body": "Damn. Shoulda placed that in the middle." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-22T15:00:59.570", "Id": "152487", "Score": "0", "body": "The title of your post should be the function/purpose of your code." } ]
[ { "body": "<p>I am not used to classes till now either but I can offer some other optimizations for your code.</p>\n\n<p>Firstly you should go over <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>. These are style conventions but they would help you write code that is considered good. Maybe <a href=\"http://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow\">PEP257</a> also for how to write docstrings.</p>\n\n<p>You can use <a href=\"http://www.python.org/dev/peps/pep-0202/\" rel=\"nofollow\">list comprehensions - PEP202</a>. They are more efficient and readable. So this </p>\n\n<pre><code>star_list=[]\nwith open(star_catalog) as incoming_stars:\n for line in incoming_stars.readlines():\n x=[item for item in line.split()]\n star_list.append(x)\n</code></pre>\n\n<p>can be made this</p>\n\n<pre><code>with open(star_catalog) as incoming_stars:\n star_list = [[item for item in line.split()]\n for line in incoming_stars.readlines()]\n</code></pre>\n\n<p>You should read Python tutorials on exceptions specifically <a href=\"http://docs.python.org/2/tutorial/errors.html#handling-exceptions\" rel=\"nofollow\">this section</a>. In this the part about use of <code>else</code> is relevant here. Combining that with list comprehensions this</p>\n\n<pre><code>InputKey=[]\ntry:\n with open(input_script) as input_key:\n for line in input_key.readlines():\n x=[item for item in line.split()]\n InputKey.append(x)\n if InputKey[0][0]=='1' or InputKey[0][0]=='2': #Checks to see if .inp file is valid or not by checking the first row/column which should be 1 or 2.\n print 'Your .inp file was successfully imported'\n else:\n print 'Your .inp file import failed. Check the validity of your file.\\n Program exiting now.'\n sys.exit()\nexcept IOError:\n print 'The .inp file import was unsuccessful. Check that your file-path is valid.\\n Program exiting now.' \n sys.exit()\n</code></pre>\n\n<p>becomes this</p>\n\n<pre><code>try:\n with open(input_script) as input_key:\n InputKey = [[item for item in line.split()]\n for line in input_key.readlines()]\nexcept IOError:\n print '''The .inp file import was unsuccessful.\nCheck that your file-path is valid.\\n Program exiting now.'''\n sys.exit()\nelse:\n if InputKey[0][0]=='1' or InputKey[0][0]=='2':\n print 'Your .inp file was successfully imported'\n else:\n print ''''Your .inp file import failed. Check the\nvalidity of your file.\\n Program exiting now.'\n sys.exit()\n</code></pre>\n\n<p>Note that I used triple quotes to wrap around the stings to be printed. Read PEP 8 for why so be sure to read it. Any text editor with syntax highlighting would offset in reading due to strings being wraped around.</p>\n\n<p>Hope this was helpful. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-10T09:51:48.830", "Id": "46798", "Score": "2", "body": "Misses the big picture, and also doesn't answer the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-10T23:31:38.423", "Id": "46825", "Score": "0", "body": "You might also want to note the pointlessness of `[item for item in line.split()]`. Except for a side effect that isn't being used, it's equivalent to `list(line.split())`, which, too, is pointless, because `split` returns a list anyway, further simplifying it to `line.split()`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T17:52:49.330", "Id": "28888", "ParentId": "28787", "Score": "1" } }, { "body": "<p>This looks like procedural code, poorly dressed up in object-oriented style. Python doesn't require you to write object-oriented code, but if you do, you should model it properly.</p>\n\n<p>Think of objects as \"smart\" data structures. If your classes are well designed, you can ask the objects to perform operations on themselves in such a way that you don't have to worry about the details of how it performs the task.</p>\n\n<p>For example, <code>StarCatalog</code> should definitely be a class of its own. There should probably be a <code>Star</code> class as well. The outline of those classes might look like:</p>\n\n<pre><code>class Star:\n def __init__(self, id, magnitude, right_ascension, declination):\n ...\n def id(self):\n ...\n def magnitude(self):\n ...\n def coordinates(self):\n ...\n\nclass StarCatalog:\n def __init__(self):\n ...\n def add_star(self, star):\n ...\n def remove_star(self, id):\n ...\n def get_star(self, id):\n ...\n def __iter__(self):\n ...\n\nclass StarCatalogImporter:\n def __init__(self, catalog):\n ...\n def import_file(filename):\n ...\n</code></pre>\n\n<p>Once your model is defined, you can start using it!</p>\n\n<pre><code>catalog = StarCatalog()\n\nimporter = StarCatalogImporter(catalog)\ntry:\n importer.import_file(raw_input('Input pathname of stellar catalog: '))\n print 'Stars imported successfully.'\nexcept IOError:\n print 'Star import unsuccessful. Check that the star catalog file-path is correct. Program exiting now.'\n raise\n\ncorrector = InterstellarCorrector(correction_factor=0.2342)\ncorrected_catalog = corrector.correct(catalog)\n\nresult = least_sq_correlator.correlate(corrected_catalog, dusty_model)\n</code></pre>\n\n<p>Notice how the classes are designed to separate concerns. The <code>StarCatalogImporter</code> class knows how to add the stars listed in a file into a <code>StarCatalog</code>; once that is done, you can ask the catalog to enumerate its stars. The <code>StarCatalogImporter</code> interface should be as reusable as possible. For example, if it encounters an error while importing, it raises an exception, rather than printing a message and exiting. The code that uses the <code>StarCatalog</code> decides how to handle those situations. (It might print an error message and exit. It might be a GUI application, in which case it would display the error in a dialog box. It might translate the error message into another language. It might try to load a different catalog instead.) On the other hand, the code that uses a <code>StarCatalog</code> should make no assumptions about how the star catalog is implemented. It doesn't know if the <code>StarCatalog</code> internally uses an array, a dict, or a numpy matrix. Therefore, it should only use the functions exposed by the class.</p>\n\n<p>The class interfaces that you design are what prevent your code from being spaghetti. If you design your class interfaces well, you will have a loose coupling, such that you will be able to reuse the class in other programs, and modify the inner workings of the class without disturbing the code that uses your class.</p>\n\n<p>A good rule to follow is that each class should represent one thing. If you can't think of a short, descriptive name for the class, that's a sign that you're on the wrong track. Also, the class name must be a noun; if it's a verb, you're using procedural rather than object-oriented thinking.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-10T17:47:58.753", "Id": "46816", "Score": "0", "body": "Wow, you're clearing things up for me more than I thought was possible. So let me ask another question. Let's say I pull the data in using a class called 'StarCatalog', the only thing that would do is pull the data in. Then the next class would enumerate it. How exactly (using my code as an example), do you 'put' the data pulled by StarCatalog into the next class, call it 'EnumerateStarData'. And a BIG thank you for such a clarifying write-up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-10T23:40:03.330", "Id": "46826", "Score": "0", "body": "In other words, how could `corrector.correct(catalog)` possibly return another `StarCatalog`? Good point. My original model, which had StarCatalog emerging from its constructor fully formed, was too simplistic. Catalogs need to be mutable, so that other objects (importers, correctors, or transformations) can manipulate them. I've amended my answer accordingly. (A design using immutable star catalogs would be awkward, but possible, using many subclasses of StarCatalog.) Also, class names must be nouns. `EnumerateStarData` as a class name indicates that you are still thinking procedurally." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-10T09:47:41.907", "Id": "29583", "ParentId": "28787", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T18:19:38.970", "Id": "28787", "Score": "4", "Tags": [ "python", "inheritance" ], "Title": "Performing calculations with a catalog of stars" }
28787
<p>I am new to Python and can't quite make my <code>if</code>-cases any shorter. Any ideas on how to do that?</p> <pre><code>import csv fileheader = csv.reader(open("test.csv"), delimiter=",") # Defines the header of the file opened header = fileheader.next() # Loop into the file for fields in fileheader: # For each header of the file, it does the following : # 1/ Detect if the header exists in the file # 2/ If yes and if the cell contains datas, it's added to the payload that will be used for an HTTP POST request. # 3/ If not, it doesn't add the cell to the payload. if 'url_slug' in header: url_slug_index = header.index('url_slug') if fields[url_slug_index] == "": print "url_slug not defined for %s" % fields[url_index] else: payload['seo_page[path]'] = fields[url_slug_index] if 'keyword' in header: keyword_index = header.index('keyword') if fields[keyword_index] == "": print "keyword not defined for %s" % fields[url_index] else: payload['seo_page[keyword]'] = fields[keyword_index] </code></pre>
[]
[ { "body": "<p>I would consider wrapping the conditions up inside a function:</p>\n\n<pre><code>def is_header(pattern):\n if pattern in header:\n pattern_index = header.index(pattern)\n if fields[pattern_index]:\n pattern_key = \"path\" if pattern == \"url_slug\" else \"keyword\"\n payload['seo_page[{}]'.format(pattern_key)] = fields[pattern_index] \n else:\n print(\"{} not defined for {}\".format(pattern, fields[pattern_index])\n</code></pre>\n\n<p>Because the tests are essentially the same, you could create a common function and pass in the pattern to test against (<code>url_slug</code> or <code>keyword</code>). There is some extra hocus pocus to get <code>pattern_key</code> to be the right thing in order to point to the right key in your seo_page dict (I assume it is a dict?).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T20:47:58.213", "Id": "28789", "ParentId": "28788", "Score": "1" } }, { "body": "<p>Instead of <code>fileheader = csv.reader(open(\"test.csv\"), delimiter=\",\")</code> you should do</p>\n\n<pre><code>with open(\"test.csv\") as f:\n fileheader = csv.reader(f, delimiter=\",\")\n</code></pre>\n\n<p>to ensure that the file is property closed at the end of the script.</p>\n\n<p>Also, why is the reader holding the entire CSV file named <code>fileheader</code>? This seems odd.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T14:27:16.257", "Id": "28831", "ParentId": "28788", "Score": "0" } } ]
{ "AcceptedAnswerId": "28789", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T19:01:12.267", "Id": "28788", "Score": "2", "Tags": [ "python", "beginner", "csv" ], "Title": "Loop in a .csv file with IF cases" }
28788
<p>I'm on the road to prepare for the 70-480 Microsoft exam and I'm learning the basics of jQuery.</p> <p>Now I wrote the following JavaScript function to create a table dynamically:</p> <pre><code>function MakeTableJavascript() { var rows = document.getElementById("rows").value; var cols = document.getElementById("cols").value; var placeholder = document.getElementById("placeholder"); var table = document.createElement("table"); table.setAttribute("border", "1"); for (var r = 0; r &lt;= rows; r++) { var row = document.createElement("tr"); for (var c = 0; c &lt; cols; c++) { if (r == 0) { var head = document.createElement("th"); var texthead = document.createTextNode("Column " + c); head.appendChild(texthead); row.appendChild(head); } else { var col = document.createElement("td"); var textrow = document.createTextNode(c.toString() + r.toString()); col.appendChild(textrow); row.appendChild(col); } } table.appendChild(row); } placeholder.appendChild(table); } </code></pre> <p>Then I re-wrote the same function with jQuery:</p> <pre><code>function MakeTablejQuery() { var rows = $('#rows').val(); var cols = $('#cols').val(); var placeholder = $('#placeholder').val(); var table = document.createElement("table"); $('table').attr("border", 1); for (r = 0; r &lt;= rows; rows++) { var row = document.createElement("tr"); for (var c = 0; c &lt; cols; c++) { if (r == 0) { var head = document.createElement("th"); var texthead = document.createTextNode("Column " + c); head.appendChild(texthead); row.appendChild(head); } else { var col = document.createElement("td"); var textrow = document.createTextNode(c.toString() + r.toString()); col.appendChild(textrow); row.appendChild(col); } } table.appendChild(row); } placeholder.appendChild(table); } </code></pre> <p>The result in term of lines of written code is practically the same.</p> <p>Surely I can use jQuery in a better way to write less code, but at the actual state I have no idea on how to do so.</p> <p>Can anyone more experienced in jQuery give me a suggestion to narrow the above code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T10:01:04.707", "Id": "45270", "Score": "12", "body": "Well, you're using jQuery, but that looks nothing like jQuery." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T10:02:39.290", "Id": "45271", "Score": "1", "body": "Look up everything you write in JavaScript and search for jQuery alternatives." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T10:02:39.480", "Id": "45272", "Score": "0", "body": "`$('table').attr(\"border\", 1);` Will look for *existing* tables in the DOM. It will have no effect on your `table` DOM element that you haven't put in the DOM yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T10:02:42.120", "Id": "45273", "Score": "4", "body": "This question appears to be off-topic because it is just a rant, not a constructive programming question.\n" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T10:03:27.310", "Id": "45274", "Score": "2", "body": "Just because you throw in one `$` somewhere does not mean you're using jQuery to its full potential. I don't see an answerable question here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T10:09:36.057", "Id": "45275", "Score": "2", "body": "@ user1422845: The code can be a lot shorter whether you use the DOM or jQuery: http://pastie.org/8160759 (I also fixed a couple of bugs, like the missing declaration for `r`, which mean you were falling prey to [*The Horror of Implicit Globals*](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html), and the fact you were trying to use `appendChild` on the **value** held by `#placeholder`, rather than on `#placeholder`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T10:10:54.483", "Id": "45276", "Score": "0", "body": "It happens that jQuery only helps a little bit with this particular problem. There are other classes of problems where it helps dramatically more, such as hooking up event handlers (particularly delegated ones), traversing complex DOM trees, doing simple effects, and working around browser inconsistencies." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T10:11:25.907", "Id": "45277", "Score": "5", "body": "There's a clear and constructive question in there: how to achieve this using jQuery to its full potential. Not sure why this post is getting so much criticism." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T10:13:16.040", "Id": "45278", "Score": "0", "body": "@Stuart: I agree. I'm certainly not seeing the rant Barmar and apparently at least three other people are seeing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T10:36:59.007", "Id": "45279", "Score": "0", "body": "@Stuart Yes, that is the question - that is only constructive for codereview." } ]
[ { "body": "<p>Well, how about</p>\n\n<pre><code>function MakeTablejQuery(rows, cols) {\n var table = $(\"&lt;table/&gt;\").attr(\"border\", 1);\n for (r = 0; r &lt; rows; r++) {\n var row = $(\"&lt;tr/&gt;\");\n for (var c = 0; c &lt; cols; c++) {\n if (r == 0) {\n row.append($(\"&lt;th/&gt;\").text(\"Column \" + c))\n } else {\n row.append($(\"&lt;td/&gt;\").text(c.toString() + r.toString()))\n }\n }\n table.append(row);\n }\n $(\"#placeholder\").append(table);\n}\n\nMakeTablejQuery(5, 3);\n</code></pre>\n\n<p>And here's a more elegant version in a functional style:</p>\n\n<pre><code>Number.prototype.times = function(fn) {\n for(var r = [], i = 0; i &lt; this; i++)\n r.push(fn(i));\n return r;\n}\n\nfunction MakeTablejQuery(numRows, numCols) {\n\n var header = numCols.times(function(c) {\n return $(\"&lt;th/&gt;\").text(\"Column \" + c);\n });\n\n var row = function(r) {\n return $(\"&lt;tr/&gt;\").append(numCols.times(function(c) {\n return $(\"&lt;td/&gt;\").text([c, r].join(\"\"));\n }));\n };\n\n return $(\"&lt;table/&gt;\")\n .append(header)\n .append(numRows.times(row))\n .attr(\"border\", 1);\n}\n\n$(\"#placeholder\").append(MakeTablejQuery(5, 3));\n</code></pre>\n\n<p>Also, jQuery is not about \"less\" code, it's about more readable code - note how the last \"return\" statement reads almost like an english sentence.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-01T10:31:00.640", "Id": "105537", "Score": "0", "body": "Just a quick FYI you can append strings with HTML in, and jQuery will automatically handle the conversion, there's no need to call: `row.append($(\"<th/>\").text(\"Column \" + c))` when jquery will happily accept: `row.append(\"<th>Column \" + c)` (the tag will close itself if left open as well, which can make things a little easier to work with)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T11:19:31.420", "Id": "28791", "ParentId": "28790", "Score": "4" } }, { "body": "<p>There are many ways to approach this, but since you complained (at least clearly in your <a href=\"https://stackoverflow.com/revisions/17771105/1\">original question</a>) your code not seeming \"less\", here's something that illustrate why jQuery says <em>\"write less\"</em>:</p>\n\n<pre><code>function MakeTablejQuery() {\n var rows = $('#rows').val(), row;\n var cols = $('#cols').val();\n var table = $(\"&lt;table&gt;\").attr(\"border\", \"1\");\n $('#placeholder').append(table);\n\n for (var r = 0; r &lt;= rows; r++) {\n table.append(row = $(\"&lt;tr&gt;\"));\n for (var c = 0; c &lt; cols; c++) {\n row.append($(r ? \"&lt;td&gt;\" : \"&lt;th&gt;\").text(r ? c+\"\"+r : \"Column \" + c));\n }\n }\n}\n</code></pre>\n\n<p>Check a <a href=\"http://jsfiddle.net/acdcjunior/6Gbwe/2/\" rel=\"nofollow noreferrer\">fiddle with both (plain JavaScript and jQuery) implementations</a>.</p>\n\n<p>Kinda nice, eh? When <a href=\"http://api.jquery.com/jQuery/#creating-new-elements\" rel=\"nofollow noreferrer\">using jQuery to create elements</a>, we have <code>$('&lt;tr&gt;')</code><sup>[1]</sup>, which is an alternative to <code>document.createElement('tr')</code>.</p>\n\n<p>But that's not the biggest advantage here. The main difference is that, when you use <code>append()</code> and <code>text()</code>, jQuery returns the element in where you called those functions, whereas JavaScript's <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild\" rel=\"nofollow noreferrer\"><code>.appendChild()</code></a> returns the appended element (used as parameter). jQuery's approach allows a more <a href=\"http://en.wikipedia.org/wiki/Fluent_interface\" rel=\"nofollow noreferrer\">fluent programming</a>. (Also, just calling <code>.text()</code> instead of having to call <code>.createTextNode()</code> and <code>.appendChild()</code> is so much sweeter.) </p>\n\n<p>And, yeah, ok, I may have gone too far using the ternary operator, but, hey, isn't it great that even with it you can still read the code? If you only had <code>.createTextNode()</code>, it wouldn't even be possible. But your question asks for <em>less lines of code to show the power of jQuery</em> not a plugin for table creation, right?</p>\n\n<p><sub>[1] You don't have to close the tag: <code>$('&lt;tr&gt;')</code> works just as well as <code>$('&lt;tr/&gt;')</code> or <code>$('&lt;tr&gt;&lt;/tr&gt;')</code>. But don't take my word for it: <a href=\"http://api.jquery.com/jQuery/#creating-new-elements\" rel=\"nofollow noreferrer\">check the docs</a>.</sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T20:02:02.643", "Id": "45283", "Score": "0", "body": "Hm. It seems the question was a bit misleading. You are aware that creating functions and extending prototypes is not a jQuery-specific, just plain JavaScript, feature and your question asked for a jQuery demonstration, right? I guess that if that was on the table, then asking for jQuery in here was kinda pointless, as you could just have created substitutes for `.appendChild()` (and others) that behaved just like `.append()`, making jQuery simply unecessary in this scenario." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T11:24:34.797", "Id": "28792", "ParentId": "28790", "Score": "2" } } ]
{ "AcceptedAnswerId": "28791", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T09:59:29.433", "Id": "28790", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Optimizing dynamic table creation: JavaScript vs. jQuery" }
28790
<p>So I'm relatively new to programming in general, and I've finally strapped in and started learning Python. This is my first significant project using it and I'm trying to build good habits with layout of my code, readability, comments, when to make functions, when not to etc.</p> <p>The problem I was solving was that I have about 20 hard drives that I wanted to run the same tests on using smartmontools on my ubuntu server system and make nice files detailing their status/health before I put them into a cluster system.</p> <p>Some specific concerns of mine are:</p> <ol> <li><p>Overall workflow. Did I implement use of my <code>main()</code> function correctly? I figured some functions that I could use outside of this script I left outside of <code>main()</code> so I could possibly call them in other scripts. But left ones specific to <code>main()</code> inside.</p></li> <li><p>Commenting. More? Less? This is just for me for now, but would you be able to see whats going on?</p></li> <li><p>I do lots of string manipulation and it looks sorta messy to me at a glance. Are there cleaner/easier ways to do this? </p></li> </ol> <p>Any other critiques are welcome!</p> <pre><code>#!/usr/bin/python ##---------------- ##Script Name: hd-diag ##Description of Script: Runs diagnostics on harddrives and writes results to ##file ##Date: 2013.07.09-11:48 ##Version: 0.1.0 ##Requirements: python2, smartmontools, posix environment ##TODO: add support for other incorrect input in YN questions ##---------------- import os import sys import subprocess import getopt def unix_call(cmd): '''(str) -&gt; str Calls unix terminal process cmd and returns stdout upon process completion. ''' output = [] global errordic p = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) for line in iter(p.stdout.readline, ''): output.append(line.strip('\n')) if p.stderr: for line in iter(p.stderr.readline, ''): errordic['unix_call'] = line.strip('\n') return '\n'.join(output).strip("'[]'") def test_call(cmd): p = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE) test_results_raw = p.stdout.read() return test_results_raw def write_str_to_file(string, filenamepath): '''(str) -&gt; string in file Writes the contents of str to file as array. Assumes current directory if just filename is given. Full path must be given. ''' def do_write(string, destination): to_file = open(destination, 'w') for item in string: to_file.write(str(item)) to_file.close() if '/' not in filenamepath: cur_dir = os.getcwd() dest = cur_dir + '/' + filenamepath do_write(string, dest) elif '/' in filenamepath: if filenamepath[0] != '/': dest = '/' + filenamepath do_write(string, dest) elif filenamepath[0] == '/': do_write(string, filenamepath) #set global variables errordic = {} driveloc = '' outputloc = '' def main(): global driveloc, outputloc, errordic def getargs(argv): global driveloc, outputloc, errordic try: opts, args = getopt.getopt( argv, 'hd:o:', ['driveloc=', 'outputloc=']) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt == '-h': usage() sys.exit() elif opt in ('-d', '--driveloc'): driveloc = arg elif opt in ('-o', '--outputloc'): outputloc = arg def usage(): print "hd-diag.py -d &lt;hdpath&gt; -o &lt;outputloc&gt;" getargs(sys.argv[1:]) print "Selected drive is: ", driveloc if outputloc != '': if outputloc[-1] != '/': outputloc = outputloc + '/' print "File output location is: ", outputloc elif outputloc[-1] == '/': print "File output location is: ", outputloc elif outputloc == '': print "No output location selected. Using current directory." outputloc = os.getcwd() + '/' print "File output location is: ", outputloc #TODO: detect here if drive is ata or sata and print #make sure harddrive is unmounted while unix_call("mount | grep '%s'" % driveloc): unix_call("sudo umount %s" % driveloc) if unix_call("mount | grep '%s'" % driveloc): print"Can't unmount %s" % driveloc print"Err:", errordic['unix_call'] print"Exiting." sys.exit(1) else: print"%s is not mounted, continuing" % driveloc #check if drive supports SMART capability, enabled if need be if 'Available' in unix_call( "sudo smartctl -i %s | grep 'SMART support is:'" % driveloc): print "SMART support is available on %s..." % driveloc if 'Enabled' in unix_call( "sudo smartctl -i %s | grep 'SMART support is:'" % driveloc): print "...and enabled" else: print "...but disabled" while not 'Enabled' in unix_call("smartctl -i %s" % driveloc): enableYN = raw_input( "Would you like to enable SMART support? [y/n]:") if enableYN in ('yYes'): unix_call("sudo smartctl -s %s" % driveloc) elif enableYN in ('nNo'): print "Script cannot continue without SMART capability " "enabled" print "Exiting." sys.exit(1) else: print 'Sorry, but "%s" is not a valid input.' % enableYN #run desired tests on harddrive #get estimated time for extended test est_ttime = unix_call( "sudo smartctl -c %s | grep -A 1 'Extended self-test'" % driveloc) est_ttime = est_ttime[est_ttime.rfind('('):].replace('( ', '(').rstrip('.') testYN = raw_input("The estimated time for the test is %s, would you " "like to proceed?[y/n]: " % est_ttime) #run test if testYN in ('Yy'): console_tstart = test_call("sudo smartctl -t long %s" % driveloc) print console_tstart elif testYN in ('Nn'): print 'Test cancelled. Exiting.' sys.exit(1) #prompt for continue contCE = raw_input( "\nThe test is running. After the estimated time listed " "above has passed, press 'c' to coninue or type 'exit' to " "exit.[c/exit]: ") #extract test result data if contCE in 'cC': console_tinfo = test_call( "sudo smartctl -i %s" % driveloc).split('\n', 2) console_thealth = test_call( "sudo smartctl -H %s" % driveloc).split('\n', 2) console_tresults = test_call( "sudo smartctl -l selftest %s" % driveloc).split('\n', 2) console_terror = test_call( "sudo smartctl -l error %s" % driveloc).split('\n', 2) log_tinfo = str(console_tinfo[2]).lstrip('\n') log_thealth = str(console_thealth[2]).lstrip('\n') log_tresults = str(console_tresults[2]).lstrip('\n') log_terror = str(console_terror[2]).lstrip('\n') print log_tinfo + log_thealth + log_tresults + log_terror elif contCE in 'Exitexit': print 'Test cancelled. Exiting.' sys.exit(1) #write output to file #extract brand, model, serial no., and size for file naming deviceinfo = [i.strip('\n').lstrip() for i in test_call( "sudo smartctl -i %s" % driveloc).split(':')] devicebrand = deviceinfo[2].split(' ')[0] devicemodel = deviceinfo[3].split(' ')[0].split('\n')[0] deviceserial = deviceinfo[4].split(' ')[0].split('\n')[0] devicesize = deviceinfo[6].split(' ')[2].strip('[') filename = '-'.join([devicebrand, devicemodel, deviceserial, devicesize]) #write data to file finalwrite = outputloc + filename write_confirm = raw_input( "The data is ready to be written to:\n\t%s\n\n" "would you like to continue?[y/n]: " % finalwrite) if write_confirm in 'Yy': #TODO test for already existing file write_str_to_file( log_tinfo + log_thealth + log_tresults + log_terror, finalwrite) print "File writen. Test complete. Exiting" sys.exit(1) elif write_confirm in 'Nn': print "File write canceled. Exiting" sys.exit(1) #main if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>Don't open files as this. Its a bad habit. It is easy to forget to close it.</p>\n\n<pre><code>to_file = open(destination, 'w')\n</code></pre>\n\n<p>Use it as this.</p>\n\n<pre><code>def do_write(string, destination):\n with open(destination, 'w') as to_file: \n for item in string:\n to_file.write(item)\n</code></pre>\n\n<p>Also when you are passing a string then there is no need to use <code>str</code> again. Redundant.</p>\n\n<p>You are making redundant <code>elif</code> checks. Obviously <code>if '/' not in filenamepath:</code> is <code>False</code> then you don't need to check whether it is in <code>filepath</code>. Use <code>else</code> instead.</p>\n\n<p>Use <a href=\"http://docs.python.org/2/library/os.path.html#os.path.join\" rel=\"nofollow noreferrer\">os.path.join</a> instead of string manipulation to join paths. It is os independent. Also checking for <code>/</code> isn't a good idea. You can use <code>os.sep</code> which again is os independent. But it would be a good idea to make sure that <code>filename</code> does not contain <code>/</code> by itself. </p>\n\n<p>In the comments you are saying that full path must be given but in the function you are checking for that. Why? Decide what you want the function to do. It does both? Then you can use this</p>\n\n<pre><code>def write_str_to_file(string, filenamepath):\n '''Writes the contents of str to file as array.\n\n Assumes current directory if just filename is given\n otherwise full path must be given\n '''\n if os.sep not in filenamepath:\n dest = os.path.join(os.getcwd(), filenamepath)\n else:\n dest = filenamepath\n\n with open(dest, 'w') as to_file:\n for item in string:\n to_file.write(str(item))\n</code></pre>\n\n<p>Don't define global variables in the middle of nowhere. It makes it harder to find them. Put all globals at the top. Don't use global variables if you don't have to. Declare them in the <code>main</code> function and pass them around. You can return more than one values so problems with passing and returning all of them. Having global variables when you don't need them shows bad design. It might be necessary sometimes but it doesn't seem to be the in this case.</p>\n\n<p>You don't need the additional variable <code>test_results_raw</code> in case of <code>test_call</code>. You can instead use</p>\n\n<pre><code>def test_call(cmd):\n p = subprocess.Popen(\n cmd, shell=True, stdout=subprocess.PIPE)\n return p.stdout.read()\n</code></pre>\n\n<p>Is the function <code>usage</code> actually necessary in the <code>main</code> function. You can define a constant at the beginning of the module and print that instead. Function calls are expensive and doing them for 1 <code>print</code> statement doesn't seem to be a good idea.</p>\n\n<p>Again in the <code>main</code> function you are using <code>if outputloc != ''</code> and then <code>elif outputloc == ''</code>. It can be a simple <code>else</code>. Same goes for the nested <code>if</code> and <code>elif</code>. Checking for more conditions costs you in performance.</p>\n\n<p>When checking for <code>enableYN</code> you can use <code>enable.lower()[0] == 'y'</code> instead of using <code>enableYN in ('yYes')</code>. In that case it checks for <code>e</code> and <code>s</code> also. People would be entering <code>y</code>, <code>Y</code>, <code>yes</code> or some other variation but with a <code>y</code> in the beginning. Same goes for checking for no.</p>\n\n<p>I skipped a lot of the code because it is quite big.<br/>\nHope this helped.</p>\n\n<p><hr>\nAbout me being able to see what's going on by the comments. Not really. You missed what the <code>main</code> function is doing</p>\n\n<p>About the strings being messy. Yes, they are. Try to change the things I have mentioned and I'll take a look again. Add your updated code like done in <a href=\"https://codereview.stackexchange.com/questions/28373/is-this-the-proper-way-of-doing-timing-analysis-of-many-test-cases-in-python-or\">this question</a> instead of modifying it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T04:38:06.690", "Id": "28801", "ParentId": "28794", "Score": "2" } }, { "body": "<p>Having a look at your edited code :</p>\n\n<p>a) In :</p>\n\n<pre><code> output = []\n global errordic\n p = subprocess.Popen(\n cmd, shell=True,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n for line in iter(p.stdout.readline, ''):\n output.append(line.strip('\\n'))\n if p.stderr:\n for line in iter(p.stderr.readline, ''):\n errordic['unix_call'] = line.strip('\\n')\n return '\\n'.join(output).strip(\"'[]'\")\n</code></pre>\n\n<p>1) the way you play with <code>output</code> seems way too complicated : if you want to do :</p>\n\n<pre><code>a=[]\nfor b in c\n a.append(f(b))\n</code></pre>\n\n<p>Python gives you an nice and efficient way to do so with <a href=\"http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow\">List Comprehension</a> : <code>a=[f(b) for b in c]</code>.</p>\n\n<p>In your case, you could write :</p>\n\n<pre><code>return '\\n'.join([l.strip('\\n') for l in iter(p.stdout.readline,'')]).strip(\"'[]'\")\n</code></pre>\n\n<p>but I am not quite sure to understand why your remove newline characters only to put them back afterwards.</p>\n\n<p>2) the way you populate <code>errordic['unix_call']</code> is quite weird too as you keep replacing the value in such a way that at the end, you only have the latest line. Assuming this is wrong and that I understand what you want to do, list comprehension can help you once again : </p>\n\n<pre><code>errordic['unix_call'] = '\\n'.join(l.strip('\\n') for l in iter(p.stderr.readline, ''))\n</code></pre>\n\n<p>Now, this is to be verified but I'd expect my 2 pieces of code to be (roughly) the same as :</p>\n\n<pre><code>errordic['unix_call'] = ''.join(iter(p.stderr.readline, ''))\nreturn ''.join(iter(p.stdout.readline,'')).strip(\"'[]'\")\n</code></pre>\n\n<p>Also, you could return a pair of strings (stdout and stderr) instead of using global variables in a weird way</p>\n\n<p>b) Then later, do you need <code>unix_call</code> and <code>test_call</code> even though they look quite similar ?</p>\n\n<p>c) In </p>\n\n<pre><code>if path.lower() == 'current':\n new_path = os.getcwd()\nelse:\n if os.sep not in path: # unrecognized filepath\n new_path = os.getcwd()\n else:\n if path[0] != os.sep:\n new_path = os.path.join(os.sep, path)\n else:\n new_path = path\n</code></pre>\n\n<p>You could make things slightly more straigthforward my using </p>\n\n<pre><code>if (path.lower() == 'current' or os.sep not in path):\n new_path = os.getcwd()\nelif path[0] == os.sep:\n new_path = path\nelse:\n new_path = os.path.join(os.sep, path)\n</code></pre>\n\n<p>d) This :</p>\n\n<pre><code>if filename.lower() == 'null':\n new_filename = ''\nelse:\n new_filename = filename\n</code></pre>\n\n<p>could be a simple :</p>\n\n<pre><code>new_filename = '' if (filename.lower() == 'null') else filename\n</code></pre>\n\n<p>e) This :</p>\n\n<pre><code>if outputloc != '':\n outputloc = file_path_check(outputloc, 'null')\n print \"File output location is: \", outputloc\nelse:\n print \"No output location selected. Using current directory.\"\n outputloc = file_path_check('current', 'null')\n print \"File output location is: \", outputloc\n</code></pre>\n\n<p>could be :</p>\n\n<pre><code>if outputloc == '':\n print \"No output location selected. Using current directory.\"\n outputloc = 'current'\noutputloc = file_path_check(outputloc, 'null')\nprint \"File output location is: \", outputloc\n</code></pre>\n\n<p>f) This :</p>\n\n<pre><code>#make sure drive is unmounted\nif not unix_call(\"mount | grep '%s'\" % driveloc):\n print \"%s is not mounted, continuing\" % driveloc\nelse:\n while unix_call(\"mount | grep '%s'\" % driveloc):\n unix_call(\"sudo umount %s\" % driveloc)\n if unix_call(\"mount | grep '%s'\" % driveloc):\n print\"Can't unmount %s\" % driveloc\n print\"Err:\", errordic['unix_call']\n print\"Exiting.\"\n sys.exit(2)\n</code></pre>\n\n<p>could be written :</p>\n\n<pre><code>#make sure drive is unmounted\nwhile unix_call(\"mount | grep '%s'\" % driveloc):\n unix_call(\"sudo umount %s\" % driveloc)\n if unix_call(\"mount | grep '%s'\" % driveloc):\n print\"Can't unmount %s\" % driveloc\n print\"Err:\", errordic['unix_call']\n print\"Exiting.\"\n sys.exit(2)\nprint \"%s is not mounted, continuing\" % driveloc\n</code></pre>\n\n<p>g) It would probably be worth defining a method taking a string as an argument, prompting it to the user and asking him for a y/n answer until a proper value is given and return a boolean.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-24T20:18:35.943", "Id": "45563", "Score": "0", "body": "so many good things, thanks @Josay. If I could sum up most of what you were doing above, these would be \"syntax optimizations\" for clarity and brevity is that correct? They don't run any faster, but just get rid of redundant code and use little tricks to lessen overall length (like E for example. I would have never thought to use `outputloc = 'current'` like that to get to the next step)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-24T20:42:09.263", "Id": "45567", "Score": "0", "body": "I'm mostly about making things more simple by removing duplicated logic and using the good things Python provides us. The simpler the code, the easier is it not to have bugs. Then, it might also be slightly faster but this is just a side-effect." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T23:32:35.090", "Id": "28853", "ParentId": "28794", "Score": "2" } }, { "body": "<p>Why are you using errordic? If you're trying to have a function return to variables, just do that.</p>\n\n<pre><code>def one_two():\n return 1, 2\none, two = one_two\n</code></pre>\n\n<p>It also seems like <a href=\"http://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate\" rel=\"nofollow\"><code>subprocess.communicate</code></a> does what you want.</p>\n\n<p><code>test_call</code> seems to be a clone of <a href=\"http://docs.python.org/2/library/subprocess.html#subprocess.check_output\" rel=\"nofollow\"><code>subprocess.check_output</code></a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-29T17:44:26.300", "Id": "45950", "Score": "0", "body": "Honestly, `errordic` was a half attempt to try and collect any and all errors that could have arose throughout the program using the dictionary key as the \"category\" and the value as the error message string. I ended up not developing it further. It definitely should be taken out I think or just make it a simple variable and the print it when needed like you said." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-26T01:53:32.793", "Id": "29006", "ParentId": "28794", "Score": "0" } } ]
{ "AcceptedAnswerId": "28853", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T00:38:07.403", "Id": "28794", "Score": "4", "Tags": [ "python", "beginner", "linux" ], "Title": "Performing SMART tests on many disks" }
28794
<p>This is my solution for HackerRank's first "Algorithm Challenge, Insertion Sort Part 1". The challenge is to sort the array from least to greatest, the input being an array in sorted order, except for the last entity, i.e. {2, 3, 4, 5, 6, 7, 8, 9, 1}</p> <p>It works fine, but it's definitely not an optimal solution. Could anybody provide any insights on how I should look at it so as to optimize it? This is for learning purposes, so I can apply the same concepts to future code.</p> <pre><code> static void insertionSort(int[] ar) { int i, j; int inserted = 0; i = ar[ar.length-1]; for (j = ar.length-2; j &gt; -1; j--){ if (ar[j] &gt; i){ ar[j+1] = ar[j]; printArray(ar); } else if (ar[j] &lt;= i){ ar[j+1] = i; inserted = 1; break; } } if(inserted == 0){ ar[0] = i; } printArray(ar); } </code></pre> <p>This is the rest of the code, but it's preset and is already available: </p> <pre><code> static void printArray(int[] ar) { for(int n: ar){ System.out.print(n+" "); } System.out.println(""); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] ar = new int[n]; for(int i=0;i&lt;n;i++){ ar[i]=in.nextInt(); } insertionSort(ar); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T06:34:44.020", "Id": "45294", "Score": "0", "body": "`if (ar[j] > i)`is wrong then you don't need to check `else if (ar[j] <= i)` because it is going to be true." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T09:45:10.250", "Id": "45734", "Score": "0", "body": "Since the array is sorted untile the last element, you could find the position of the element to insert using a binary search. http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#binarySearch%28int[],%20int,%20int,%20int%29" } ]
[ { "body": "<p>You could <a href=\"https://en.wikipedia.org/wiki/Binary_search_algorithm\" rel=\"nofollow noreferrer\">binary search</a> the list (without the last element) to get the new position of the last element. The JDK already has a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#binarySearch%28int[],%20int,%20int,%20int%29\" rel=\"nofollow noreferrer\">method for that</a> but you can write your own too for practice.</p>\n\n<p>Some other notes:</p>\n\n<ol>\n<li>\n\n<pre><code>int i, j;\n</code></pre>\n\n<p>I'd put the variable declarations to separate lines. From Code Complete, 2nd Edition, p759:</p>\n\n<blockquote>\n <p>With statements on their own lines, the code reads from top to bottom, instead\n of top to bottom and left to right. When you’re looking for a specific line of code,\n your eye should be able to follow the left margin of the code. It shouldn’t have to\n dip into each and every line just because a single line might contain two statements.</p>\n</blockquote></li>\n<li><p>About the <code>j</code> variable: Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used. (<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p>\n\n<pre><code>int i = ar[ar.length - 1];\n\nfor (int j = ar.length - 2; j &gt; -1; j--) {\n ...\n</code></pre></li>\n<li><p>I would use longer variable names than <code>ar</code>. Longer names would make the code more readable since readers don't have to decode the abbreviations every time and when they write/maintain the code don't have to guess which abbreviation the author uses: Was it <code>a</code>? <code>ar</code>? <code>arr</code>? (It's a bigger problem in more complex cases.) </p>\n\n<p>Furthermore, <code>i</code> could be <code>newElement</code>. It would be easier to read.</p></li>\n<li><p>The sort method should validate its input parameter. Does it make sense to call it with <code>null</code>? If not, check it and throw a <code>NullPointerException</code>. Currently it throws an <code>ArrayIndexOutOfBoundsException</code> when it's been called with an empty array. It should throw an exception (<code>IllegalArgumentException</code>) with better error message. (<em>Effective Java, Second Edition, Item 38: Check parameters for validity</em>)</p></li>\n<li><p>Currently the <code>insertionSort</code> method violates the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single responsibility principle</a>. It sorts the array and prints the array. If a client wants to print the array they should call the print method. It should not be in the sort method.</p></li>\n<li><p>The <code>inserted</code> integer could be a <code>boolean</code>. It would be <a href=\"https://stackoverflow.com/questions/5554725/which-value-is-better-to-use-boolean-true-or-integer-1\">less error prone</a> (booleans have only two states, not 2^32).</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-28T05:04:06.867", "Id": "45838", "Score": "0", "body": "2. is controversy but all other points are very solid, the reason why i don't find it that good is because you can have long variable declarations scattered everywhere, which is bad" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T21:08:05.037", "Id": "28850", "ParentId": "28797", "Score": "1" } }, { "body": "<p>Two components in particular are unnecessary. This test:</p>\n\n<pre><code> } else if (ar[j] &lt;= i){ \n</code></pre>\n\n<p>is redundant. <code>else</code> means <code>if (ar[j] &lt;= i)</code>, since the latter is the negation of the earlier <code>if (ar[j] &gt; i)</code>.</p>\n\n<p>And then, the <code>inserted</code> variable is used to track whether <code>i</code> was inserted within the loop. To simplify, I'd only do it outside the loop -- we can do this because <code>j</code> is still useful. (If you're not using <code>j</code> outside the loop, as in your original code, it's better -- safer, more readable -- style to declare it in the for statement.)</p>\n\n<p>This is the heart of what you're doing:</p>\n\n<pre><code>static void insertionSort(int[] ar) {\n int i, j;\n i = ar[ar.length-1];\n\n for (j = ar.length-2; j &gt; -1; j--){\n if (ar[j] &gt; i){\n ar[j+1] = ar[j];\n printArray(ar);\n } else {\n break;\n } \n }\n ar[j+1] = i;\n printArray(ar);\n}\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>static void insertionSort(int[] ar) {\n int i = ar[ar.length-1];\n int j;\n for (j = ar.length-2; (j &gt;= 0) &amp;&amp; (ar[j] &gt; i); j--) {\n ar[j+1] = ar[j];\n printArray(ar);\n }\n ar[j+1] = i;\n printArray(ar);\n}\n</code></pre>\n\n<p>There are some style quibbles, but that's the big stuff. I'd take the printing out of it, except that the purpose of this function doesn't seem to be \"perform an insertion sort\", but rather \"show how an insertion sort inserts an element\". I don't see any advantage to using a binary search, since that only helps you find the insertion point, and you still need to iterate over all elements > ar[i] to move their values.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-27T17:42:48.270", "Id": "29067", "ParentId": "28797", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T01:37:19.000", "Id": "28797", "Score": "5", "Tags": [ "java", "optimization", "algorithm", "programming-challenge", "insertion-sort" ], "Title": "HackerRank Algorithm Challenge 1: Insertion sort" }
28797
<p>Would like some assistance in improving my jQuery validation code. I have some repeated code, but I am not sure how to write it in a way so that I don't have to keep repeating the same code over and over again for different variable names etc... (such as the <code>if</code> statement part) My goal is to make it so that I can easily apply it to any other form I create.</p> <p><a href="http://jsfiddle.net/9gZhc/1/" rel="nofollow">Here is the jsFiddle</a></p> <pre><code>(function($) { $('.commentForm').submit(function () { var error = 'error'; var name = $(this).find('.name') nameVal = name.attr('value') email = $(this).find('.email') comment = $(this).find('textarea') commentVal = comment.html(); if (!(name.val() === nameVal || name.val() === '' || name.val().length &lt; 3) &amp;&amp; !(comment.val() === commentVal || comment.val() === '' || comment.val().length &lt; 3) &amp;&amp; validateEmail(email.val()) ) { console.log('Form is good'); return true; } else { (name.val() === nameVal || name.val() === '' || name.val().length &lt; 3) ? name.addClass(error) : name.removeClass(error); (comment.val() === commentVal || comment.val() === '' || comment.val().length &lt; 3) ? comment.addClass(error) : comment.removeClass(error); (!validateEmail(email.val())) ? email.addClass(error) : email.removeClass(error); console.log('Form is BAD'); return false; } }); function validateEmail(email) { var re = /^(([^&lt;&gt;()[\]\\.,;:\s@\"]+(\.[^&lt;&gt;()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } }) (jQuery); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T02:51:18.393", "Id": "45397", "Score": "0", "body": "If you can use plugin, jquery validation plugin comes with email validation. If not, you can have a look at their implementation. You can find it here: http://validation.bassistance.de/email-method/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T14:24:05.100", "Id": "58130", "Score": "1", "body": "Likely moot at this point, but you can remove the check for `$this.val() === ''` as it is true if `$this.val().length < 3` is true." } ]
[ { "body": "<p>You could replace your if block with: </p>\n\n<pre><code>(name.val() === nameVal || name.val() === '' || name.val().length &lt; 3) ? name.addClass(error) : name.removeClass(error);\n(comment.val() === commentVal || comment.val() === '' || comment.val().length &lt; 3) ? comment.addClass(error) : comment.removeClass(error);\n(!validateEmail(email.val())) ? email.addClass(error) : email.removeClass(error);\n\nif(name.hasClass(error) || comment.hasClass(error) || email.hasClass(error))\n{\n console.log('Form is BAD');\n return false;\n}\nelse\n{\n console.log('Form is good');\n return true;\n}\n</code></pre>\n\n<p>This would run your validation logic once and then look for error classes on the objects</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-13T20:28:26.243", "Id": "96821", "ParentId": "28798", "Score": "0" } }, { "body": "<p>This confuses me:</p>\n\n<pre><code>name.val() === nameVal\n</code></pre>\n\n<p>The variable <code>nameVal</code> is equal to the <code>value</code> attribute of <code>name</code>. And, the calling <code>val()</code> on <code>name</code> returns the <code>value</code> attribute of <code>name</code> so of course they are going to be equal.</p>\n\n<p>I may be missing something here, but I think this is unnecessary.</p>\n\n<hr>\n\n<p>Long chunks of mush like this:</p>\n\n<pre><code>(name.val() === nameVal || name.val() === '' || name.val().length &lt; 3) ? name.addClass(error) : name.removeClass(error);\n (comment.val() === commentVal || comment.val() === '' || comment.val().length &lt; 3) ? comment.addClass(error) : comment.removeClass(error);\n (!validateEmail(email.val())) ? email.addClass(error) : email.removeClass(error);\n</code></pre>\n\n<p>and this:</p>\n\n<pre><code>!(name.val() === nameVal || name.val() === '' || name.val().length &lt; 3) &amp;&amp; \n !(comment.val() === commentVal || comment.val() === '' || comment.val().length &lt; 3) &amp;&amp; \n validateEmail(email.val())\n</code></pre>\n\n<p>are in no way whatsoever readable. You need to either</p>\n\n<ul>\n<li><p>Break this up. Maybe everything here is not necessary.</p></li>\n<li><p>Split this into variables and check with the variables.</p></li>\n</ul>\n\n<p>I think you should go with the first option, because these can be simplified:</p>\n\n<hr>\n\n<p>1:</p>\n\n<p>As I stated above, having</p>\n\n<pre><code>name.val() === nameVal\n</code></pre>\n\n<p>is unnecessary. You can just remove this.</p>\n\n<hr>\n\n<p>2:</p>\n\n<p>The value <code>\"\"</code> is called a falsey value. That means that <code>\"\"</code> can be treated as though it were false.</p>\n\n<p>So, for example, this here:</p>\n\n<pre><code>name.val() === ''\n</code></pre>\n\n<p>can be reduced to:</p>\n\n<pre><code>!name.val()\n</code></pre>\n\n<hr>\n\n<p>Constantly calling the <code>.val</code> function on these elements in each of your conditionals is inefficient. You should store the result of <code>.val()</code> in a variable, and just use that for the conditionals (I think <code>nameVal</code> should already hold the <code>.val()</code> for <code>name</code>).</p>\n\n<hr>\n\n<p>Now, for example, one of your conditional chunks becomes:</p>\n\n<pre><code>( !nameVal || nameVal.length &lt; 3) ? name.addClass(error) : name.removeClass(error);\n\n(! commentVal || commentVal.length &lt; 3) ? comment.addClass(error) : comment.removeClass(error);\n\n(!validateEmail(email.val())) ? email.addClass(error) : email.removeClass(error);\n</code></pre>\n\n<p><em>Where <code>commentVal</code> is <code>comment.val()</code> and <code>nameVal</code> is <code>name.val()</code></em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-13T20:31:15.963", "Id": "96822", "ParentId": "28798", "Score": "3" } } ]
{ "AcceptedAnswerId": "96822", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T02:05:35.140", "Id": "28798", "Score": "1", "Tags": [ "javascript", "jquery", "form", "validation" ], "Title": "jQuery validation code" }
28798
<p>This code works nicely for my purposes, but I would like to improve it exponentially.</p> <p>What are some steps I can take? I'm interested in optimization, refactoring, and clean-code.</p> <pre><code> def do_GET(self): qs = {} path = self.path print path if path.endswith('robots.txt'): self.send_response(500) self.send_header('Connection', 'close') return if '?' in path: path, tmp = path.split('?', 1) qs = urlparse.parse_qs(tmp) print path, qs if 'youtube' in path: ID = qs.get('vID') LTV = qs.get('channelID') EMAIL = qs.get('uEmail') TIME = qs.get('Time') userID = qs.get('uID') URL = qs.get('contentUrl') channelID = str(LTV)[2:-2] print channelID uEmail = str(EMAIL)[2:-2] print uEmail ytID = str(ID)[2:-2] print ytID ytURL = str("https://www.youtube.com/tv#/watch?v=%s" % ytID) print ytURL uTime = str(TIME)[2:-2] print uTime uID = str(userID)[2:-2] print uID contentUrl = str(URL)[2:-2] print contentUrl if sys.platform == "darwin": subprocess.Popen('./killltv', shell=True) sleep(1) subprocess.Popen('./killltv', shell=True) sleep(1) subprocess.Popen('./test.py %s'%ytURL, shell=True) elif sys.platform == "linux2": subprocess.Popen('./killltv', shell=True) sleep(1) subprocess.Popen('./test.py %s'% ytURL, shell=True) #subprocess.Popen('chromium-browser https://www.youtube.com/tv#/watch?v=%s'% ytID, shell=True) sleep(2) #subprocess.Popen("./fullscreen", shell=True) elif sys.platform == "win32": os.system('tskill chrome') browser = webbrowser.open('http://youtube.com/watch?v="%s"'% ytID) log.warn("'%s':,video request:'%s' @ %s"% (channelID, ytID, time)) #playyt = subprocess.Popen("/Users/Shared/ltv.ap </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T05:00:50.163", "Id": "45291", "Score": "1", "body": "Some explanation of its purpose would be helpful. That way we don't accidentally break it. That is the first feedback. Always use [docstring at the beginning of a function explaining its purpose](http://stackoverflow.com/questions/3898572/what-is-the-standard-python-docstring-format)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-26T02:06:17.753", "Id": "45693", "Score": "0", "body": "Why are you running ./killtv a bunch of times and then running another python script (test.py) from your python script?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-26T02:25:28.690", "Id": "45695", "Score": "0", "body": "http get request opens a pyside window (test.py), killtv just closes the previous request/window" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-30T13:12:48.913", "Id": "46033", "Score": "0", "body": "About your os specific code why are you only opening the browser when `sys.platform` is `win32`? If you add certain details about what you are trying to do by `test.py` then the os specific code can be converted into loops based on values stored in dictionaries with key being `sys.platform`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-03T01:32:51.813", "Id": "46305", "Score": "0", "body": "@AseemBansal can you elaborate... I think this is something i'm searching for. test.py opens up a pyside window with a url passed in from the get request." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-03T12:47:36.357", "Id": "46330", "Score": "0", "body": "@sirvonandrethomas I updated my answer to add details regarding the os-specific code." } ]
[ { "body": "<p>How about using</p>\n\n<pre><code>IS, LTV, EMAIL, TIME, userID, URL = map(\\\n qs.get, ['vID', 'channelID', 'uEmail', 'Time', 'uID', 'contentUrl'])\n\nchannelID, uEmail, ytID, uTime, uID, contentUrl = map(\\\n lambda x : str(x)[2:-2], [LTV, EMAIL, ID, TIME, userID, URL])\n\nfor i in (channelID, uEmail, ytID, uTime, uID, contentUrl):\n print i\n\nytURL = str(\"https://www.youtube.com/tv#/watch?v=%s\" % ytID)\nprint ytURL\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>ID = qs.get('vID')\nLTV = qs.get('channelID')\nEMAIL = qs.get('uEmail')\nTIME = qs.get('Time')\nuserID = qs.get('uID')\nURL = qs.get('contentUrl')\nchannelID = str(LTV)[2:-2]\nprint channelID\nuEmail = str(EMAIL)[2:-2]\nprint uEmail\nytID = str(ID)[2:-2]\nprint ytID\nytURL = str(\"https://www.youtube.com/tv#/watch?v=%s\" % ytID)\nprint ytURL\nuTime = str(TIME)[2:-2]\nprint uTime\nuID = str(userID)[2:-2]\nprint uID\ncontentUrl = str(URL)[2:-2]\nprint contentUrl\n</code></pre>\n\n<p>The first one just prints <code>ytURL</code> at the end but it can be changed easily if you really want. Other than that they do the same thing. But I am sure the first one is much easier to modify and maintain.</p>\n\n<p>Other than that I can only say after I know what this program is about.</p>\n\n<p>It might also be a good idea to keep os-specific functions(like you are doing after checking for the os) into separate functions. It would make maintaining and modifying the code much easier.</p>\n\n<p>You should also read <a href=\"http://www.python.org/dev/peps/pep-0008\" rel=\"nofollow\">PEP8</a>, particularly the part about code-layout. Your indentation is not good.</p>\n\n<p>What I meant was that this can be converted into</p>\n\n<pre><code>if sys.platform == \"darwin\":\n subprocess.Popen('./killltv', shell=True)\n sleep(1)\n subprocess.Popen('./killltv', shell=True)\n sleep(1)\n subprocess.Popen('./test.py %s'%ytURL, shell=True)\nelif sys.platform == \"linux2\":\n subprocess.Popen('./killltv', shell=True)\n sleep(1)\n subprocess.Popen('./test.py %s'% ytURL, shell=True)\n</code></pre>\n\n<p>this equivalent structure</p>\n\n<pre><code>OS_DETAIL = { 'darwin' : 2, 'linux2' : 1}\nfor i in xrange(OS_DETAIL[sys.platform]):\n subprocess.Popen('./killltv', shell=True)\n sleep(1)\nelse:\n subprocess.Popen('./test.py %s'% ytURL, shell=True)\n</code></pre>\n\n<p>It doesn't solve the complete problem because I am not sure whether you'll need those commented statements or not. If the <code>sleep(2)</code> is actually needed in case of <code>linux2</code> then you can store a tuple in the <code>OS_DETAILS</code> dictionary. But the problem with this approach is your <code>win32</code> part. It is totally different. It can be taken care of using an structure like this.</p>\n\n<pre><code>if sys.platform in ['darwin', 'linux2`]:\n #place the code I have just suggested for these 2 \nelif sys.platform == \"win32\"\n #place your code for win32\n</code></pre>\n\n<p>But as you can see this isn't the best way. It is better than the current solution but if the code for <code>win32</code> can be refactored in some way (I don't know its functionality so don't ask) to fit the same pattern then it all comes down to a simple dictionary and a loop structure.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T05:21:31.580", "Id": "28803", "ParentId": "28799", "Score": "5" } }, { "body": "<p>Some notes about your code:</p>\n\n<ul>\n<li>Use 4 spaces for indentation.</li>\n<li>Local variables should use the underscore style: <code>name_of_variable</code>.</li>\n<li>This function is too long. Split code in functions.</li>\n<li>When writing conditionals, try to keep a <code>if</code>/<code>elif</code>/<code>else</code> layout, without early returns, you'll see that readability is greatly enhanced.</li>\n<li>Use dictionaries to hold multiple named values, not one variable per value, that's too messy.</li>\n<li>Some patterns are repeated all over the place, abstract them.</li>\n<li>Don't update variables in-place unless there is a good reason for it (99% of the time there isn't).</li>\n</ul>\n\n<p>I'd write (<code>show_video</code> has been left out, it's clearly another function's task):</p>\n\n<pre><code>def do_GET(self):\n url = urlparse.urlparse(self.path)\n if 'youtube' not in url.path:\n sys.stderr.write(\"Not a youtube path: {0}\".format(self.path))\n elif url.path == '/robots.txt':\n self.send_response(500)\n self.send_header('Connection', 'close')\n else:\n url_params = urlparse.parse_qs(url.query)\n keys = [\"vID\", \"channelID\", \"uEmail\", \"Time\", \"uID\", \"contentUrl\"]\n params = dict((key, url_params[key][2:-2]) for key in keys)\n yt_url = \"https://www.youtube.com/tv#/watch?v={0}\".format(params[\"vID\"])\n show_video(yt_url)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T14:47:52.830", "Id": "28834", "ParentId": "28799", "Score": "4" } } ]
{ "AcceptedAnswerId": "28803", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T02:45:04.277", "Id": "28799", "Score": "3", "Tags": [ "python", "optimization" ], "Title": "Optimization of \"def do_GET(self)\"" }
28799
<p>I'm sure this has probably been asked before (although I couldn't find a question akin to this one).</p> <p>I have a canvas "app" that is refreshing persistently, but performance is awful on mobile devices. I just wondered if there was a nice alternative to <code>requestAnimFrame()</code> or the like.</p> <p>Here is my "app": <a href="http://www.barriereader.co.uk/Principality/" rel="nofollow">http://www.barriereader.co.uk/Principality/</a></p> <p>Here is the main rendering methods (I've removed the actual rendering - you can view that here <a href="http://www.barriereader.co.uk/Principality/System/Engine.js" rel="nofollow">http://www.barriereader.co.uk/Principality/System/Engine.js</a>)</p> <pre><code>var fps = 0; var oldtime = +new Date(); var time; var Engine = { /** FOR DEBUGGING **/ FPS: true, /*******************/ Canvas : null, CTX : null, GameLooper : null, NodeSize : 10, MapSize : 32, Init : function (w, h) { Engine.Canvas = document.createElement('canvas'); document.body.appendChild(Engine.Canvas); Engine.CTX = Engine.Canvas.getContext('2d'); Engine.Canvas.width = w; Engine.Canvas.height = h; Engine.GameLoop(); }, Update : function (time) { fps = 1000/(time-oldtime) oldtime = time; Engine.Draw(); }, Draw : function () { Engine.CTX.save(); Engine.CTX.setTransform(1, 0, 0, 1, 0, 0); Engine.CTX.clearRect(0, 0, Engine.Canvas.width, Engine.Canvas.height); Engine.CTX.restore(); /**************DRAW_SCENE_HERE*****************/ //A BUNCH OF RENDERING GOES HERE... //Performance is bad on mobiles :( /**********************************************/ Engine.GameLoop(); }, GameLoop : function () { Engine.GameLooper = setTimeout(function () { requestAnimFrame(Engine.Update, Engine.Canvas); }, 10); }, }; window.requestAnimFrame = (function () { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback, element) { window.setTimeout(callback(+new Date), 1000 / 60); }; }()); window.onload = function () { Engine.Init(320, 320); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T08:30:08.670", "Id": "45296", "Score": "0", "body": "Are you sure your code is optimized and really appropriate for mobile? Maybe you could show us a little bit more. Accusing requestAnimationFrame is maybe an easy way to not review your own code. Because requestAnimationFrame is supposed to be the most optimized thing which will act according to your device capacities." } ]
[ { "body": "<p>As far I understand your code, here's are some bumps:</p>\n\n<h1>Cache your values</h1>\n\n<p>Property access in objects causes a very minor overhead. A very common example of this case is a normal loop. In this version of the loop, you'd be accessing <code>length</code> <code>i</code> times during the course of the loop.</p>\n\n<pre><code>for(i = 0; i &lt; someArray.length; ++i){\n</code></pre>\n\n<p>It may not matter in normal array use, where array length is less than a hundred records at best. But when you are aiming for at least 60fps and doing pixel operations in between, these minor optimizations do give you that edge.</p>\n\n<p><sub>Just to point you to the right perspective, a canvas of 1024x768 has 3,145,728 entries in the image data array! Imagine doing a loop at that scale, manipulating pixels on every iteration, do this on every frame for 60fps. I tell you, my CPU (fan) screamed.</sub></p>\n\n<p>So instead of the code above, the following code solves the problem by caching the <code>length</code>, and in effect, only accessing <code>length</code> on the object once.</p>\n\n<pre><code>var arrayLength = someArray.length;\nfor(i = 0; i &lt; arrayLength; ++i){\n</code></pre>\n\n<h1>Use a closure</h1>\n\n<p>Sure, cache the variables, but where? I assume you made the <code>Engine</code> object as your namespace to avoid globals. But if property access is an overhead, where should we place your code?</p>\n\n<p>Well, you should create a closure for your code. That way, you have a scope to play with, where:</p>\n\n<ul>\n<li><p>You can place your code freely without using a namespace (thus avoiding property access).</p></li>\n<li><p>At the same time not polluting the global space. </p></li>\n</ul>\n\n<p>Consider this:</p>\n\n<pre><code>(function(ns){\n\n var Update = function(){/*Engine.Update code*/}\n var Canvas = function(){/*Engine.Canvas code*/}\n var GameLooper;\n\n function GameLoop(){\n requestAnimationFrame(GameLoop);\n Update();\n Canvas();\n }\n\n //Expose init to our namespace\n var Init = ns.Init = function(){/*Init code*/}\n\n}(this.Engine = this.Engine || {}));\n\nwindow.onload = function(){\n Engine.Init(320, 320);\n}\n</code></pre>\n\n<p>As you can see, you don't need to call <code>Engine.something()</code>. You can directly do <code>something()</code> directly. This solves your property access and namespacing problems, two birds with one stone.</p>\n\n<h1>rAF</h1>\n\n<p><code>requestAnimationFrame</code>, often abbreviated as <code>rAF</code>, is a more optimized timer compared to <code>setTimeout</code> and <code>setInterval</code>. It's basically built with animations in mind, and is optimized to give you the best framerates as possible. It's also an efficient timer since it slows down if the tab is set to the background, thus not eating up processing time.</p>\n\n<p>However, I notice that you are hampering the <code>rAF</code> call with a <code>setTimeout</code>.</p>\n\n<pre><code>GameLoop : function () {\n Engine.GameLooper = setTimeout(function () {\n requestAnimFrame(Engine.Update, Engine.Canvas);\n }, 10);\n},\n</code></pre>\n\n<p>This code has several bad effects as well, aside from those mentioned earlier:</p>\n\n<ul>\n<li><p>Your game loop runs in intervals of ~10ms. You are not reaping the benefits of <code>rAF</code> at all. You are basically slowing down the game loop.</p></li>\n<li><p>Also, timer delays don't really reflect the actual time they execute, thus in this code, the delay isn't 10ms. It could be greater, depending on what JS is doing at the moment.</p></li>\n<li><p>You are creating a timer and an anonymous function on every iteration. <code>setInterval</code> would have been a better option (but not better that <code>rAF</code>) because it creates only one timer and one anonymous function.</p></li>\n</ul>\n\n<p>With <code>rAF</code>, try this instead:</p>\n\n<pre><code>// Aapplying our no-property access policy\nvar GameLoop = function () {\n\n // Schedule the next frame ASAP\n requestAnimFrame(GameLoop);\n\n // In the meantime, call the functions for this frame\n Update();\n Canvas();\n}\n</code></pre>\n\n<p>Notice that the scheduled call is <code>GameLoop</code>. This way, your functions <code>Update</code> and <code>Canvas</code> don't need to call back <code>GameLoop</code> to run the next frame. The next frame is already scheduled with this call.</p>\n\n<h1>Date....now()!</h1>\n\n<p>Yes, in recent browsers, there's <code>Date.now()</code> which is an optimized substitute to <code>+new Date()</code> and <code>new Date().getTime()</code> to get the current timestamp.</p>\n\n<p>In classical OOP terms, it's a \"static\" member, which means you don't need to create an instance of <code>Date</code> to use it. This way, you are not generating a new object every time just to get the current time, thus saving you memory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T08:57:31.377", "Id": "45297", "Score": "0", "body": "This, my friend, is an awesome answer! Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T08:27:25.330", "Id": "28808", "ParentId": "28806", "Score": "3" } } ]
{ "AcceptedAnswerId": "28808", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T08:07:02.167", "Id": "28806", "Score": "1", "Tags": [ "javascript", "performance", "canvas" ], "Title": "Canvas performance and stable frames per second" }
28806
<p>I've developed this spreadsheet in order to scrape a website's number of indexed pages through Google and Google Spreadsheets.</p> <p>I'm not a developer, so how can I improve this code in order to have less code, to use less resources, or to go faster?</p> <p>I've explained everything <a href="http://www.alsaseo.fr/recuperer-nombre-pages-indexees-spreadsheet-google-drive/" rel="nofollow">here</a>.</p> <pre><code>//------------------------------------------- // scrape a website's number of indexed pages through Google and Google Spreadsheets. //------------------------------------------- function indexedpages(myUrl) { var request = "http://www.google.com/search?&amp;hl=en&amp;q=site:http://" + unescape(myUrl); // Google Request for indexed pages var sourcecode = UrlFetchApp.fetch(request).getContentText(); // scrape the page content Utilities.sleep(1000); // 1000ms pause to prevent spam var codebefore = '&lt;div id="resultStats"&gt;About '; // the code before the number we want var codeafter = ' results&lt;'; // the code after the number we want var theresult = sourcecode.substring(sourcecode.indexOf(codebefore)+codebefore.length, sourcecode.indexOf(codeafter)); // scrape the number we want var theresult = theresult.replace(",", ""); // delete the "," if (isNaN(theresult)) // if the result is not a number { var codebefore = '&lt;div id="resultStats"&gt;'; // the code before the number we want var codeafter = ' result&lt;'; // the code after the number we want var theresult = sourcecode.substring(sourcecode.indexOf(codebefore)+codebefore.length, sourcecode.indexOf(codeafter)); // scrape the number we want if (isNaN(theresult)) // if the result is not a number { var codebefore = '&lt;div id="resultStats"&gt;'; // the code before the number we want var codeafter = ' results&lt;'; // the code after the number we want var theresult = sourcecode.substring(sourcecode.indexOf(codebefore)+codebefore.length, sourcecode.indexOf(codeafter)); // scrape the number we want if (isNaN(theresult)) // if the result is not a number (0 result) { return 0; // returns 0 } else { return theresult; // returns the number we want } } else { return theresult; // returns the number we want } } else { return theresult; // returns the number we want } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T09:14:28.507", "Id": "45299", "Score": "0", "body": "I'm afraid somebody who doesn't speak French can't understand your question as the blog, the variable names and the comments are all in French. You should at least translate the variables and comments for this question here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T09:43:46.053", "Id": "45301", "Score": "2", "body": "I just translated it ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T09:45:26.640", "Id": "45302", "Score": "0", "body": "Good. Especially useful for the variables. This one could probably not win the prize for the most useful comment ever : `// fonction name`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T11:15:42.230", "Id": "45312", "Score": "0", "body": "Of course ^^\nI added all the comments for my blog visitors, because some of them really don't know nothing about developement." } ]
[ { "body": "<h1>Comments</h1>\n\n<ul>\n<li><p>Never place them between the closing parenthesis and the opening bracket of the statement.</p></li>\n<li><p>Comments are meant to be read, and not set aside. Here are suggestions for cleaner comments:</p>\n\n<pre><code>//Before the lines concerned, like this one\nsomeObject.someFunction();\n\n//Inside blocks of statements\nif(foo){\n //If foo, then call foo\n foo();\n} else if(bar){\n //If bar, then call bar\n bar();\n}\n</code></pre></li>\n</ul>\n\n<h1>Prettify Code</h1>\n\n<p>To make your code a bit readable, but save yourself the hassle of formatting it manually, use a prettifier. An example is <a href=\"http://jsbeautifier.org/\" rel=\"nofollow\">jsbeautifier</a>.</p>\n\n<h1>Code</h1>\n\n<pre><code>function indexedpages(myUrl) {\n\n // JavaScript doesn't have block scope like C. Variables declared in blocks\n // other than functions are pulled up and declared in the nearest scope.\n var i;\n var codeBefore;\n var codeAfter;\n var result;\n\n // So I assume your code was about looking for numbers between a certain set\n // of strings. It's a repetetive task, we'll use an array to store these set\n // of strings and a loop that accesses them using an index.\n var wrappers = [\n ['&lt;div id=\"resultStats\"&gt;About ', ' results&lt;'],\n ['&lt;div id=\"resultStats\"&gt;', ' result&lt;'],\n ['&lt;div id=\"resultStats\"&gt;', ' results&lt;']\n //add more wrappers if you want\n ];\n\n var wrappersLength = wrappers.length;\n\n // Make the request\n var request = \"http://www.google.com/search?&amp;hl=en&amp;q=site:http://\" + unescape(myUrl);\n var sourceCode = UrlFetchApp.fetch(request).getContentText();\n\n Utilities.sleep(1000);\n\n // Then loop through each of the wrappers and testing them\n for (i = 0; i &lt; wrappersLength; ++i) {\n\n // Get the codeBefore and codeAfter from an entry in the array\n codeBefore = wrappers[i][0];\n codeAfter = wrappers[i][1];\n\n // Parse\n result = sourceCode.substring(sourceCode.indexOf(codeBefore) + codeBefore.length, sourceCode.indexOf(codeAfter)).replace(\",\", \"\");\n\n // Then check if the number is not NaN and if so, return which effectively\n // make the code break out of the loop and of the function as well.\n if (!isNaN(result)) return result;\n else return \"0\"; \n }\n}\n</code></pre>\n\n<p>When free of comments, it's just this short:</p>\n\n<pre><code>function indexedpages(myUrl) {\n var i;\n var codeBefore;\n var codeAfter;\n var result;\n var wrappers = [\n ['&lt;div id=\"resultStats\"&gt;About ', ' results&lt;'],\n ['&lt;div id=\"resultStats\"&gt;', ' result&lt;'],\n ['&lt;div id=\"resultStats\"&gt;', ' results&lt;']\n ];\n var wrappersLength = wrappers.length;\n var request = \"http://www.google.com/search?&amp;hl=en&amp;q=site:http://\" + unescape(myUrl);\n var sourceCode = UrlFetchApp.fetch(request).getContentText();\n Utilities.sleep(1000);\n for (i = 0; i &lt; wrappersLength; ++i) {\n codeBefore = wrappers[i][0];\n codeAfter = wrappers[i][1];\n result = sourceCode.substring(sourceCode.indexOf(codeBefore) + codeBefore.length, sourceCode.indexOf(codeAfter)).replace(\",\", \"\");\n if (!isNaN(result)) return result;\n else return \"0\"\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T17:19:37.233", "Id": "45348", "Score": "0", "body": "Thanks a lot ! I just edited your code, i found 2 mistakes and added the \"0\" return." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T14:44:45.700", "Id": "28833", "ParentId": "28807", "Score": "1" } }, { "body": "<p>Use a regular expression to look for the relevant text in the page.</p>\n\n<p>It makes more sense to return a number instead of a string.</p>\n\n<p>In the parameter name, \"my…\" is pointless. Just call the parameter <code>site</code>.</p>\n\n<p>Google now encourages the use of HTTPS everywhere, so it's probably a good idea to scrape Google using HTTPS as well. Also, Google doesn't need the <code>site:...</code> query argument to start with \"http://\". Finally, the correct way to build a query string is to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent\" rel=\"nofollow\"><code>encodeURIComponent()</code></a>.</p>\n\n<pre><code>function indexedpages(site) {\n // Google request for relevant pages\n var request = \"https://www.google.com/search?&amp;hl=en&amp;q=site:\" + encodeURIComponent(site);\n // scrape the page content\n var sourcecode = UrlFetchApp.fetch(request).getContentText();\n // 1000ms pause for rate limiting\n Utilities.sleep(1000);\n\n var match = /&lt;div id=\"resultStats\"&gt;(?:About )?([0-9,]*) results?&lt;/.exec(sourcecode);\n return (match) ? parseInt(match[1].replace(',', '', 'g')) : 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-21T13:05:06.840", "Id": "52792", "Score": "0", "body": "Thanks a lot ! Your code is great.\nJust saw an error with a site having more than 1000000 pages.\nCould you check ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-21T13:20:39.633", "Id": "52793", "Score": "1", "body": "Fixed with the `g` flag when calling `replace()`. (The bug was propagated from your original code.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-24T11:57:49.650", "Id": "53139", "Score": "0", "body": "You are a boss ! :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-20T21:50:09.030", "Id": "32979", "ParentId": "28807", "Score": "1" } } ]
{ "AcceptedAnswerId": "32979", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T08:21:08.210", "Id": "28807", "Score": "5", "Tags": [ "javascript", "web-scraping", "google-apps-script", "google-sheets" ], "Title": "Spreadsheet function that gives the number of Google indexed pages" }
28807
<p><strong>Method implemented in parent class (<code>extends SherlockFragmentActivity</code>)</strong> <a href="https://github.com/smarek/Simple-Dilbert/blob/master/src/com/mareksebera/simpledilbert/DilbertFragmentActivity.java" rel="nofollow">(source)</a></p> <pre><code>ViewPager viewPager; // initialized in onCreate method public void toggleActionBar() { try { FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT); if (getSupportActionBar().isShowing()) { getSupportActionBar().hide(); lp.topMargin = 0; } else { getSupportActionBar().show(); lp.topMargin = getSupportActionBar().getHeight(); } viewPager.setLayoutParams(lp); } catch (Throwable t) { Log.e(TAG, "Toggle of Actionbar failed", t); } } </code></pre> <p><strong>Call made from one of Fragments in ViewPager</strong> <a href="https://github.com/smarek/Simple-Dilbert/blob/master/src/com/mareksebera/simpledilbert/DilbertFragment.java" rel="nofollow">(source)</a></p> <pre><code>try { ((DilbertFragmentActivity) getSherlockActivity()).toggleActionBar(); } catch (Throwable t) { Log.e(TAG, "Toggle of Actionbar failed", t); } </code></pre> <p>MinSdkVersion is equal 8, ActionBar support is done by ActionBarSherlock library.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T10:05:21.520", "Id": "45304", "Score": "1", "body": "[Is it a bad idea to use printStackTrace() in Android Exceptions?](http://stackoverflow.com/q/3855187/843804) at Stack Overflow" } ]
[ { "body": "<p>Three points:</p>\n\n<ol>\n<li><code>getSupportActionBar()</code> is called four times within the same method. Store it as a local variable and use the variable four times instead, to improve code cleaniness and readability.</li>\n<li>When catching exceptions, <a href=\"https://stackoverflow.com/questions/6083248/is-it-a-bad-practice-to-catch-the-throwable\">be as specific as possible</a>. Catching <code>Throwable</code> is a <strong>horrible</strong> idea. <strong>Only catch the exceptions you need to catch</strong> (Which involves neither <code>Error</code>s or <code>RuntimeException</code>s. You shouldn't even wrap <code>((DilbertFragmentActivity) getSherlockActivity()).toggleActionBar();</code> inside a try-catch statement. If you think that something can go wrong (like a <code>NullPointerException</code>), <em>make sure that it doesn't go wrong before you try to do it</em> (by checking if something is not null for example).</li>\n<li>If <code>viewPager</code> can be marked as <code>private</code>, it is good practice to also mark it as <code>private</code>.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T21:30:19.240", "Id": "35881", "ParentId": "28809", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T08:40:57.047", "Id": "28809", "Score": "3", "Tags": [ "java", "android" ], "Title": "Toggling ActionBar visibility for SherlockFragmentActivity" }
28809
<p><a href="http://en.wikipedia.org/wiki/VHDL" rel="nofollow">VHDL</a> (Very High Speed Integrated Circuit HDL) is a hardware description language (<a href="http://en.wikipedia.org/wiki/Hardware_description_language" rel="nofollow">HDL</a>) maintained by the <a href="http://www.eda.org/twiki/bin/view.cgi/P1076/WebHome" rel="nofollow">VHDL Analysis and Standardization Group (VASG)</a> and standardized as <a href="http://dx.doi.org/10.1109/IEEESTD.2009.4772740" rel="nofollow">IEEE Standard 1076</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T08:54:32.220", "Id": "28810", "Score": "0", "Tags": null, "Title": null }
28810