body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Note:</p> <ol> <li>I am very new to Javascript. </li> <li>The code I provided is long but not complicated.</li> </ol> <p>The code below works and runs fine. But I would like to seperate it out into logical 'pure' functions to make it clearer whats going on. I started to re-factor this myself and made some good progress, however, I quickly started to return to problems with dependencies and embedded functions. </p> <p>I'd be interested to see how others would write the following:</p> <pre><code> var contactsController = { fetch: function() { // Parses the returned JSON into the database var fetchSuccess = function(json) { var NAME = "Contact", COLUMNS = ['Name', 'GivenNames', 'FamilyName', 'Telephone']; if (json.Response.Code == 0) { database.open(); database.dropTable(NAME); database.createTable(NAME, COLUMNS); // .Contact is an array of contact objects var contacts = json.Contacts.Contact; for (var contact in contacts) { var contact = contacts[contact]; database.insert(NAME, COLUMNS, [contact.Name, contact.GivenNames, contact.FamilyName, contact.Telephone] ); } contactsController.populateList(); } } ServerConn.fetchContacts(fetchSuccess); }, populateList: function() { var $page = $("#contactsPage"); $page.find(".content").empty(); $page.find(".content").html("&lt;ul data-role='listview' data-filter='true'&gt;&lt;\/ul&gt;"); $list = $page.find(".content ul"); var render = function(character) { return function(tx, result) { var max = result.rows.length; if (max &gt; 0) { var header = "&lt;li data-role='list-divider'&gt;" + character + "&lt;/li&gt;", listItem = $(header); $list.append(header); for (var i = 0; i &lt; result.rows.length; i++) { var contact = result.rows.item(i), strHtml = "&lt;li&gt;&lt;a href='#contactPage'&gt;" + contact.Name + "&lt;\/a&gt;&lt;\/li&gt;"; listItem = $(strHtml); $list.append(listItem); // store the data in the DOM $list.find("a:last").data("contactObj", contact); } $list.find("a").click(function() { var $this = $(this); $("#contactPage").data("contactObj", $this.data("contactObj")); }); $list.listview(); //Only fires once? $list.listview('refresh'); } } } var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for(var i = 0; i &lt; str.length; i++) { var sql = "SELECT * FROM Contact WHERE Exclude = ? AND Name LIKE ? ORDER BY Name", nextChar = str.charAt(i), selargs = ['0', nextChar + "%"]; database.open(); database.query(sql, selargs, render(nextChar)); } } </code></pre> <p>};</p>
[]
[ { "body": "<p>A lot of the logic in your code belongs to a template, not directly in code.\nYou can find tons of templating engines for javascript or make your own.</p>\n\n<p>An example of a template that could be used here is:</p>\n\n<pre><code>&lt;script type=\"text/html\" id=\"letter-index-view\"&gt;\n@if( model.result.rows.length ) {\n &lt;li data-role=\"list-divider\"&gt;@model.result.character&lt;/li&gt;\n @foreach( contact in model.result.rows ) {\n &lt;li&gt;&lt;a href=\"#contactPage\" id=\"@contact.ContactID\"&gt;@contact.Name&lt;/a&gt;&lt;/li&gt;\n }\n}\n&lt;/script&gt;\n</code></pre>\n\n<p>Now <code>populateList</code> becomes this:</p>\n\n<pre><code>populateList: function()\n {\n var $page = $(\"#contactsPage\"),\n tmpl = Template.getById(\"letter-index-view\"),\n str = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n $list = $(\"&lt;ul&gt;\", {\n \"data-role\": \"listview\",\n \"data-filter\": \"true\"\n });\n\n $list.on( \"click\", \"a\", function() {\n $(\"#contactPage\").data(\"contactId\", this.id);\n });\n\n $page.find(\".content\").empty().append( $list );\n\n for(var i = 0; i &lt; str.length; i++)\n {\n var nextChar = str.charAt(i),\n sql = \"SELECT *, ? AS character FROM Contact WHERE Exclude = ? AND Name LIKE ? ORDER BY Name\",\n selargs = [nextChar, '0', nextChar + \"%\"];\n\n database.open();\n database.query(sql, selargs, function(tx, result){\n $list.append( tmpl( {\n result: result\n }));\n\n $list.listview(); //Only fires once?\n $list.listview('refresh'); \n });\n }\n }\n</code></pre>\n\n<p>Note that I made some other changes as well, since template is kind of static html it cannot have object references like\n<code>$list.find(\"a:last\").data(\"contactObj\", contact);</code> so the links are uniquely identified with their database row id.</p>\n\n<p>I also modified the query to return the character used in that query so a static function\ncan be used for the query callback instead of 26 different ones.</p>\n\n<p>Another reason for <code>populateList</code> being lengthy is that it's doing view and model stuff at the same time. You should move\nall the DOM stuff into a view.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T11:15:00.870", "Id": "17196", "Score": "0", "body": "There are some really nice bits of code here. I particularly like storing the character in the SQL rather than using the immediately returning function. Is the template from scratch or have you used a framework?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T11:39:07.470", "Id": "17198", "Score": "0", "body": "@CrimsonChin Not sure what you mean... I just wrote the template according to your code. A template engine would convert that to real javascript function (`Template.getById(\"letter-index-view\")`) which can be called to generate HTML according to the templating language used." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T11:31:27.343", "Id": "10612", "ParentId": "10610", "Score": "2" } } ]
{ "AcceptedAnswerId": "10612", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T09:22:35.957", "Id": "10610", "Score": "-1", "Tags": [ "javascript" ], "Title": "Refactoring Javascript into pure functions to make code more readable and maintainable" }
10610
<p>I have a method which loads data from a remote app (send TCP request and parse response). Now, I have a simple class for sending a TCP request:</p> <pre><code>public class PremieraTcpClient { public PremieraTcpClient() { QueryItems = new NameValueCollection(); int port; int.TryParse(ConfigurationManager.AppSettings["PremieraPort"], out port); Port = port; ServerIp = ConfigurationManager.AppSettings["PremieraServerIp"]; ServiceId = ConfigurationManager.AppSettings["PremieraServiceId"]; } public NameValueCollection QueryItems { get; set; } private int Port { get; set; } private string ServerIp { get; set; } private string ServiceId { get; set; } private string ReadyQuery { get; set; } public string SendQuery() { StringBuilder parameters = new StringBuilder(); //... // build query for request //... ReadyQuery = parameters.ToString(); return Connect(); } private string Connect() { string responseData; try { TcpClient client = new TcpClient(ServerIp, Port); client.ReceiveBufferSize = Int32.MaxValue; Byte[] data = Encoding.GetEncoding(1251).GetBytes(ReadyQuery); NetworkStream stream = client.GetStream(); // send data stream.Write(data, 0, data.Length); var sizeBuffer = new byte[10]; stream.Read(sizeBuffer, 0, 10); var sizeMessage = int.Parse(Encoding.GetEncoding(1251).GetString(sizeBuffer, 0, 10)); data = new Byte[sizeMessage]; var readSoFar = 0; //read data while (readSoFar &lt; sizeMessage) { readSoFar += stream.Read(data, readSoFar, data.Length - readSoFar); } responseData = Encoding.GetEncoding(1251).GetString(data, 0, data.Length); responseData = responseData.TrimStart('&amp;'); stream.Close(); client.Close(); return responseData; } catch (ArgumentNullException e) { //return responseData = string.Format("ArgumentNullException: {0}", e); } catch (SocketException e) { //return responseData = string.Format("SocketException: {0}", e); } return string.Empty; } } </code></pre> <p>This is method for load data:</p> <pre><code> private static void GetUpdatesFromPremiera() { Debug.WriteLine(DateTime.Now + ":GetUpdatesFromPremiera"); PremieraTcpClient client = new PremieraTcpClient(); client.QueryItems.Add("QueryCode", QueryCode.GetUpdates.ToString()); client.QueryItems.Add("ListType", "Movie;Hall;Session;Place;Delete"); client.QueryItems.Add("Updates", _lastUpdateId); _lastUpdateId = String.Empty; var response = client.SendQuery(); // here parse response //... } </code></pre> <p>This code works fine. But, now I have to load data from two remote app (tomorrow may be three).</p> <p>The simple solution is to iterate through all remote apps:</p> <pre><code>private static void GetUpdatesFromPremiera() { foreach(var remoteApp in listRemoteApp) { PremieraTcpClient client = new PremieraTcpClient(); // here assigned different properties var response = client.SendQuery(); } } </code></pre> <p>Is there is a better way of doing it? Also, each time a connection is established, I think it impacts performance greatly.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T10:26:57.940", "Id": "16914", "Score": "0", "body": "I'm not sure I understand what the problem is. If you have a collection of items, using `foreach` to do something for each item is exactly what you should be doing. I certainly don't think it's ugly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T11:04:53.667", "Id": "16915", "Score": "0", "body": "@svick:ok, What you think about `PremieraTcpClient`?" } ]
[ { "body": "<p>I have some suggestions about PremieraTcpClient. The way it is written may lead to unreleased resources. If you have an error then you will remain with a <strong><em>stream</em></strong> and <strong><em>client</em></strong> opened.\nThe correct way to do it is by using <strong><em>try...catch...finally</em></strong> or by using <strong><em>using</em></strong>.\nBelow you can find the code using try catch finally</p>\n\n<pre><code> private string Connect()\n {\n string responseData = string.Empty;\n TcpClient client = null;\n NetworkStream stream = null; \n try\n {\n client = new TcpClient(ServerIp, Port);\n client.ReceiveBufferSize = Int32.MaxValue;\n\n Byte[] data = Encoding.GetEncoding(1251).GetBytes(ReadyQuery);\n\n stream = client.GetStream();\n\n // send data\n stream.Write(data, 0, data.Length);\n\n var sizeBuffer = new byte[10];\n\n stream.Read(sizeBuffer, 0, 10);\n var sizeMessage = int.Parse(Encoding.GetEncoding(1251).GetString(sizeBuffer, 0, 10));\n\n data = new Byte[sizeMessage];\n\n var readSoFar = 0;\n //read data\n while (readSoFar &lt; sizeMessage)\n {\n readSoFar += stream.Read(data, readSoFar, data.Length - readSoFar);\n }\n\n responseData = Encoding.GetEncoding(1251).GetString(data, 0, data.Length);\n responseData = responseData.TrimStart('&amp;');\n //stream.Close();\n //client.Close();\n //return responseData;\n }\n catch (ArgumentNullException e)\n {\n //return responseData = string.Format(\"ArgumentNullException: {0}\", e);\n }\n catch (SocketException e)\n {\n //return responseData = string.Format(\"SocketException: {0}\", e);\n }\n finally\n {\n if(stream!=null) stream.Close();\n if(client!=null) client.Close();\n }\n\n return responseData;\n }\n</code></pre>\n\n<p>And another small suggestion: I think is misleading to have a method named <strong>Connect</strong> that in fact does more than connect. It will be better to break the Connect method into smaller methods, each one with specific actions (even if they are private).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T14:56:58.527", "Id": "10619", "ParentId": "10611", "Score": "4" } } ]
{ "AcceptedAnswerId": "10619", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T09:47:48.437", "Id": "10611", "Score": "4", "Tags": [ "c#", "asp.net-mvc-3", "tcp" ], "Title": "Loading data from a remote app" }
10611
<p>Some time ago I <a href="https://stackoverflow.com/a/9893623/917053">posted on Stack Overflow</a> an imperative C# implementation of Kadane's algorithm for finding a subarray with maximum sum. Then I considered implementing the same functionally in F# and came up with the following:</p> <pre><code>let kadanes (xs: int []) = xs |&gt; Array.mapi (fun i x -&gt; (x, i)) |&gt; Array.fold (fun (partSum, partIdx, maxSum, startIdx, endIdx) (x, i) -&gt; let newPartSum, newPartIdx = if partSum + x &gt; x then (partSum + x, partIdx) else (x, i) if newPartSum &gt; maxSum then (newPartSum, newPartIdx, newPartSum, newPartIdx, i) else (newPartSum, newPartIdx, maxSum, startIdx, endIdx)) (0,0,xs.[0],0,0) |&gt; fun (_, _, maxSum, startIdx, endIdx) -&gt; (maxSum, startIdx, endIdx) </code></pre> <p>While the implementation above is functional and correct I cannot consider it easily understandable; in particular, dragging tuple of 5 elements through the fold seems rather ugly.</p> <p>What can be done for improving this F# code?</p> <p>Thank you.</p>
[]
[ { "body": "<p>A recursive function often works well in place of fold.</p>\n\n<pre><code>let kadanes xs =\n let rec loop (partSum, partIdx, maxSum, startIdx, endIdx) i =\n if i &lt; Array.length xs then \n let x = xs.[i]\n let newPartSum, newPartIdx =\n if partSum + x &gt; x then (partSum + x, partIdx) else (x, i)\n let maxSum, startIdx, endIdx =\n if newPartSum &gt; maxSum then (newPartSum, newPartIdx, i)\n else (maxSum, startIdx, endIdx)\n loop (newPartSum, newPartIdx, maxSum, startIdx, endIdx) (i + 1)\n else (maxSum, startIdx, endIdx)\n loop (0,0,xs.[0],0,0) 0\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T22:59:13.603", "Id": "10631", "ParentId": "10616", "Score": "1" } }, { "body": "<p>Although <a href=\"https://codereview.stackexchange.com/a/10631/12197\">Daniel's suggestion</a> is sound and appreciated, the idiomatic improvement direction is more likely to be from a recursive function to a <code>fold</code>, not vice versa. Staying with <code>fold</code> I tried the following:</p>\n\n<ul>\n<li>make more apparent the <code>fold</code> arguments by moving the initial accumulator in front of input array and them arguments through <code>||&gt;</code></li>\n<li>make factors defining the outcome of folding step in the body of folder function more noticeable by first disassembling accumulator into logical groups, and then reassembling it back with the help of <code>in</code>.</li>\n</ul>\n\n<p>Here is the improved code:</p>\n\n<pre><code>let kadanes (xs: int[]) =\n ((0,0,xs.[0],0,0), (xs |&gt; Array.mapi (fun i x -&gt; (x, i))))\n ||&gt; Array.fold (fun (partSum, partIdx, maxSum, startIdx, endIdx) (x, i) -&gt;\n let (newPartSum, newPartIdx) = if partSum + x &gt; x then (partSum + x, partIdx) else (x, i) in\n let (newMaxSum, newStartIdx, newEndIdx) = if newPartSum &gt; maxSum then (newPartSum, newPartIdx, i) else (maxSum, startIdx, endIdx) in\n (newPartSum, newPartIdx, newMaxSum, newStartIdx, newEndIdx))\n |&gt; fun (_, _, maxSum, startIdx, endIdx) -&gt; (maxSum, startIdx, endIdx)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T02:37:20.767", "Id": "10716", "ParentId": "10616", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T13:45:14.210", "Id": "10616", "Score": "2", "Tags": [ "f#" ], "Title": "How can this functional implementation of Kadane's algorithm be improved?" }
10616
<p>Taking the following cases in consideration. Witch one would you prefer and why? Suggestions appreciated.</p> <ol> <li><p>Using Delegates</p> <pre><code>private void cmdDelete_enterClick(object sender, EventArgs e) { var accountManager = new BLAccountManager(); accountManager.OnAccountInUse = (msg) =&gt; MessageBox.Show(msg); accountManager.OnConfirmation = (msg) =&gt; { var dialogResult = MessageBox.Show(msg); return (dialogResult == DialogResult.OK); }; accountManager.DeleteAccount(selectedAccountId); } </code></pre> <hr> <pre><code> public class BLAccountManager { public Action&lt;string&gt; OnAccountInUse; public Func&lt;string, bool&gt; OnConfirmation; public void DeleteAccount(string accountId) { var bookingsUsingAccount = GetBookingsUsingAccount(accountId); if (bookingsUsingAccount.Count &gt; 0) { OnAccountInUse("msg"); return; } BankAccount account = GetAccount(accountId); if (OnConfirmation("confirm")) { account.Delete(false); } } } </code></pre></li> <li><p>Using Interfaces</p> <pre><code> public interface IUICallback { void SendMessage(string message,string caption); bool Confirmation(string message,string caption); } </code></pre> <hr> <pre><code>public class WinFormsUICallback : IUICallback { public void SendMessage(string message, string caption) { MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } public bool Confirmation(string message, string caption) { DialogResult result = MessageBox.Show(message); return result == DialogResult.OK; } } </code></pre> <hr> <pre><code> private void cmdDelete_Click(object sender, EventArgs e) { IUICallback uiCallback = new WinFormsUICallback(); var accountManager = new BLAccountManager(uiCallback); accountManager.Delete(selectedAccountId); } </code></pre> <hr> <pre><code> public void Delete(string accountId) { BookingList bookingsUsingAccount = bookingManager.GetBookingsUsingAccount(accountId); if (bookingsUsingAccount.Count &gt; 0) { _uiCallback.SendMessage(msg, caption); return; } if (_uiCallback.Confirmation(confirmationMessage, caption)) { account.Delete(false); } } </code></pre></li> </ol>
[]
[ { "body": "<p>A third option is to use continuations:</p>\n\n<pre><code>public void DeleteAccount(string accountId, Action&lt;string&gt; OnAccountInUse, Func&lt;string,bool&gt; OnConfirmation)\n{\n var bookingsUsingAccount = GetBookingsUsingAccount(accountId);\n if (bookingsUsingAccount.Count &gt; 0)\n { \n OnAccountInUse(\"msg\");\n return;\n }\n BankAccount account = GetAccount(accountId);\n if (OnConfirmation(\"confirm\"))\n {\n account.Delete(false);\n }\n}\n</code></pre>\n\n<p>edit: adding the usage, similar to the cases in the question</p>\n\n<pre><code>private void cmdDelete_enterClick(object sender, EventArgs e)\n{ \n var accountManager = new BLAccountManager();\n\n Func&lt;string,bool&gt; OnConfirmation = (msg) =&gt;\n {\n var dialogResult = MessageBox.Show(msg);\n return (dialogResult == DialogResult.OK);\n };\n\n accountManager.DeleteAccount(selectedAccountId,\n (msg) =&gt; MessageBox.Show(msg),\n OnConfirmation);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T06:28:47.443", "Id": "16972", "Score": "0", "body": "Interesting. Unfortunately I have a few other parameters that I need to pass to DeleteAccount and I think that adding the additional delegates to the parameters list would be to much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T08:46:04.380", "Id": "16975", "Score": "0", "body": "I do quite like this approach. The parameters could always be passed in via a DTO if there are extra ones than just the two...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T23:22:59.160", "Id": "22561", "Score": "0", "body": "tnx for this post" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T17:08:18.330", "Id": "10624", "ParentId": "10617", "Score": "2" } }, { "body": "<p>I think I like the combination of your third option with that supplied by Dan. I've made some other changes which may or may not be better. Not really sure. My aim was to have the Delete set status callbacks only i.e. success, failure while the UI event handler handled the confirmation requirements.</p>\n\n<p>If anything, I would always suggest using .Any() over .Count() > 0 operations as although a minor thing could have unexpected have performance benefits on large collections. And if anything I personally think it reads a bit nicer. </p>\n\n<pre><code> public class CallBackArgs\n {\n public string Message { get; private set; }\n public string Caption { get; private set; }\n\n public CallBackArgs(string msg, string caption)\n {\n Message = msg;\n Caption = caption;\n }\n }\n\n public interface ICrudCallback\n {\n void SendMessage(CallBackArgs args);\n void OnSuccess(CallBackArgs args);\n void OnFailure(CallBackArgs args);\n }\n\n private void cmdDelete_Click(object sender, EventArgs e)\n {\n WinFormsUICallback= new WinFormsUICallback();\n\n if (_uiCallback.Confirmation(\"Please confirm deletion is required\", \"Confirm\"))\n {\n var accountManager = new BLAccountManager(); \n accountManager.Delete(selectedAccountId, (ICrudCallback)uiCallback);\n }\n }\n\n public void Delete(string accountId, ICrudCallback uiCallback)\n {\n BookingList bookingsUsingAccount = bookingManager.GetBookingsUsingAccount(accountId, ICrudCallback uiCallback);\n\n // When doing .Count() &gt; 0 comparisons always try and use .Any() \n if (bookingsUsingAccount.Any())\n { \n uiCallback.OnFailure(new CallBackArgs(\"Account in use\", \"In use\"));\n } \n else\n {\n // Delete could throw an exception, return an error string, return a status\n // code, or in my case return bool. Either way we handle it\n if(account.Delete(false))\n {\n uiCallback.OnSuccess(new CallBackArgs(\"Delete succeeded\",\"Success\"));\n }\n else\n {\n // add error message appropriate from delete here?\n uiCallback.OnFailure(new CallBackArgs(\"Somethings gone wrong!\",\"Oops\"));\n }\n }\n }\n</code></pre>\n\n<p>Well that's my 2cents for what it's worth.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T20:53:54.883", "Id": "10628", "ParentId": "10617", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T14:46:52.997", "Id": "10617", "Score": "2", "Tags": [ "c#", ".net" ], "Title": "Business Layer - UI communication" }
10617
<p>I'm not very experienced in C++, but I am trying to circumvent a kind of 'constructor order' situation, where I have class A wants class B in its constructor, and vice versa. They don't really want <em>eachother</em>, but both implement an interface and need each other. I decided to give object A a future. Is this even remotely good practice in C++11?</p> <p>I'm thinking that the code below should be fine - the shared_ptr simply serves to make the future passable by value - multiple future objects can represent the same 'future'. Since I am not experienced in C++, I'm not sure of any potential trouble. I think that I don't need to declare any special copy constructor or such, since I don't do any allocation and std::shared_ptr should be copy-constructible automatically.</p> <p>What do you think?</p> <pre><code>#ifndef LIB_FUTURE #define LIB_FUTURE #include &lt;stdexcept&gt; #include &lt;memory&gt; namespace lib { template &lt;typename TValue&gt; class future { public: future() : value_ptr(std::make_shared&lt;TValue*&gt;()) { } void set(TValue &amp;value) { *value_ptr.get() = &amp;value; } TValue&amp; get() { assert_valid_access(); return **value_ptr; } TValue* operator-&gt;() { assert_valid_access(); return *value_ptr; } bool has_value() { return value_ptr.get() != nullptr; } private: std::shared_ptr&lt;TValue*&gt; value_ptr; void assert_valid_access() { if(!has_value()) throw std::runtime_error("Attempting to access a non-set value from a future"); } }; } #endif </code></pre> <p><strong>UPDATE</strong> The use case I have is a little more complicated than the above though. Here goes:</p> <pre><code>class view : public log_sink { view(tcp_client &amp;client); virtual sink members... }; class tcp_client { tcp_client(log) //a sink should be provided before this, since it will do some logging. }; class log { log(log_sink sink); //So this one needs view. }; int main() { log log(view); tcp_client client(log); view the_view(client); } </code></pre> <p>The above is not possible. View needs client, but client needs log, but log needs access to an interface on view.</p> <p>Instead, I opted to give log a <em>promise</em> of a sink in the future. Log implements a tiny buffering mechanism, on the off chance that it doesn't have a sink by the time someone wants logging done. When it finally gets a sink, everything works fine. :)</p> <p>Like this:</p> <pre><code>int main() { future&lt;log_sink&gt; promise; log log(promise); tcp_client client(log); view the_view(client); promise.set(view); } </code></pre>
[]
[ { "body": "<p>What's your inheritance relationship between A and B? If A is the parent of B, it's bad design if A needs to do ANYTHING with B in the constructor/destructor because B will not be valid until after A's construction.</p>\n\n<p>If you require RAII design, look at lazy resource acquisition to avoid re-acquisition going up the constructor chain (vector).</p>\n\n<p>Why do you want a smart pointer to a pointer. Smart pointers help you when there is no clear custodian of an instance (or shared primitive type), and you want to destroy an instance only when there are no more users of it. The way you are using the smart pointer means that only a memory location of a pointer is freed, not the memory of a type instance. Plus when you construct this class, the pointer held by the 'value_ptr' is random, which is bad. </p>\n\n<p>I'm not sure where you're going with this 'future' class and how it solves your inter-dependance between A and B.</p>\n\n<p>If A and B need a similar member, make them inherit from the same parent class. If you want to hide this 'shared' member or you want a pure-virtual interface, simply declare the interface as well as defining some sort of linking parent.</p>\n\n<p>If A and B need access to the same instance of something, use a singleton that is inherited from a shared parent.</p>\n\n<p>If you do need a shared instance, and you need to free any resources (IE files) held by the singleton, it's better to write an explicit free function. That way you will easily see where it's being cleaned up.</p>\n\n<p>If you mean you want to avoid initializing a resource that's defined in a parent class, until your child class A or B does, perhaps look at making an explicit, polymorph function.</p>\n\n<p>Hope that helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T08:29:32.847", "Id": "17043", "Score": "0", "body": "Thanks for your answer! I think I should have been a bit clearer. They don't have any inheritance relationship - only compositional dependence. Please see my edit - hopefully, the less abstract use case is better. I'll give you a chance to update any changes you might feel necessary (to your answer) before commenting further, since you explicitly stated you don't know where I was going with this! Hope it's not too much of a hassle. Just one thing: std::make_shared<ptr>() should call the default constructor, which initializes the ptr to zero! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T12:44:53.057", "Id": "17046", "Score": "0", "body": "It's no hassle, I do this to challenge myself. Some questions:\nWhy does log need view, aren't you passing it a log_sink? Why can't view be a polymorph (currently private inheritance) of log_sink which provides the interface you need? What things does log_sink depend on? When would log not have access to log_sink methods (\"on the off chance\")? Is there a load time issue here (IE is code being executed before main)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T13:00:42.133", "Id": "17047", "Score": "0", "body": "Oh dang, view *is* publicly inheriting log_sink - so I am using it polymorphically as a implementor of log_sink. log(...) needs view, polymorphically typed as log_sink. tcp_client is asynchronous, so it's possible that a log message is passed before it is 'given' a log_sink by the promise<log_sink>. In that case, the message is buffered. I'll update with the construction code in a minute." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T02:03:06.997", "Id": "10669", "ParentId": "10618", "Score": "2" } }, { "body": "<p>What you're calling a \"future\" doesn't model the same concept as <code>std::future</code>, so I think \"future\" is the wrong name for it. What you've got is more like a \"place to put the answer once we get around to computing it\", a.k.a. a \"variable that starts out uninitialized\". There's nothing too special about that, and you <em>could</em> implement it with much less boilerplate if you wanted to.</p>\n\n<p>Re your actual code: you wrote</p>\n\n<pre><code>class view : public log_sink {\n view(tcp_client&amp;);\n};\n\nclass tcp_client {\n tcp_client(log);\n};\n\nclass log {\n log(log_sink);\n};\n</code></pre>\n\n<p>Now, <code>log</code>'s constructor takes a <code>log_sink</code> parameter, but that's clearly incorrect, because <code>log_sink</code> is the base class of a polymorphic class hierarchy. You don't want to pass a polymorphic type by value (because of <a href=\"https://stackoverflow.com/questions/4403726/learning-c-polymorphism-and-slicing\">slicing</a>); you want to pass it by reference or by (smart) pointer.</p>\n\n<p>Then, <code>view</code>'s constructor takes a reference to a <code>tcp_client</code>; but does it really make sense to have a <code>view</code> without a <code>tcp_client</code>? Could we (without loss of generality) assert that <em>every <code>view</code> must have a <code>tcp_client</code></em>, in which case the <code>tcp_client</code> should actually be a fully owned <em>member</em> of <code>view</code>.</p>\n\n<pre><code>class view : public log_sink {\n tcp_client m_client;\n view(log) : m_client(std::move(log)) { ... }\n};\n\nclass tcp_client {\n tcp_client(log);\n};\n\nclass log {\n log(std::shared_ptr&lt;log_sink&gt;); // takes ownership\n};\n</code></pre>\n\n<p>And then finally we collapse the last level:</p>\n\n<pre><code>class log_sink : public std::enable_shared_from_this&lt;log_sink&gt; { };\n\nclass view : public log_sink {\n tcp_client m_client;\n view() : m_client(log(shared_from_this())) { ... }\n};\n\nclass tcp_client {\n tcp_client(log);\n};\n\nclass log {\n log(std::shared_ptr&lt;log_sink&gt;); // takes ownership\n};\n</code></pre>\n\n<p>Now we can construct a <code>view</code>, which contains a <code>tcp_client</code> which contains a <code>log</code> that knows (recursively) about <em>this <code>view</code></em>.</p>\n\n<p>The <code>shared_ptr</code> part is actually irrelevant at this point; you could just do</p>\n\n<pre><code>class log_sink { };\n\nclass view : public log_sink {\n tcp_client m_client;\n view() : m_client(log(*this)) { ... }\n};\n\nclass tcp_client {\n tcp_client(log);\n};\n\nclass log {\n log(log_sink&amp;);\n};\n</code></pre>\n\n<p>Does that answer your question, or are you asking about some other \"level\" of the problem? (For example, this doesn't deal with \"how do I prevent the <code>log</code> from logging anything to an only semi-constructed <code>view</code>?\", and it doesn't deal with the basic question \"how do I forward-declare <code>class tcp_client;</code>?\".)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-08T00:48:13.910", "Id": "90103", "ParentId": "10618", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T14:54:02.333", "Id": "10618", "Score": "5", "Tags": [ "c++", "c++11" ], "Title": "Is this a valid implementation of a 'future'?" }
10618
<p>I want to scale some sub images from an original image.<br> I need to use <code>TCanvas.CopyRect</code> function for about 5,000 times and it is very slow (from a simple BMP image). </p> <p>Do you know any other method that is faster that simple <code>TCanvas.CopyRect</code> method for the same job?</p> <p>Again the job is to stretch some rects (different rects, to the same size, exactly windowing) from an original image for about 5,000 times.</p> <p>Edit: I tested it with <strong>1,700</strong> images and that takes <strong>20</strong> seconds. </p> <p>Big edit, i don't use copyrect because i found it is useless:</p> <pre><code>Uses Classes,SysUtils,Windows,Graphics,HaarFeature_unit,Dialogs; Type TAlgorithm = class(TObject) protected bmBitmap:TBitmap; Haar:THaarFeature; vRects:array of TRect; vWebcamMatrix:TWebcamMatrix; iWebcamMatrixWidth,iWebcamMatrixHeight:integer; Procedure ClearList; Procedure DrawList; public Procedure Process(bmBitmap:TBitmap); private iMinWidth,iMinHeight,iMaxWidth,iMaxHeight,iDistX,iDistY:integer; procedure ProcessRect(iLeft,iTop,iRight,iBottom:integer); Procedure AddSolution(iLeft,iTop,iRight,iBottom:integer); Procedure ConstructorWebcamMatrix; published Constructor Create(iMinWidth,iMinHeight,iMaxWidth,iMaxHeight,iDistX,iDistY:integer; sHaarPath:string; iWhite,iBlack:integer); end; implementation //------------------------------------------------------------------------------ Procedure TAlgorithm.AddSolution(iLeft,iTop,iRight,iBottom:integer); begin SetLength(vRects,Length(vRects)+1); vRects[High(vRects)]:=Rect(iLeft,iTop,iRight,iBottom); end; //------------------------------------------------------------------------------ Procedure TALgorithm.ProcessRect(iLeft,iTop,iRight,iBottom:integer); begin end; //------------------------------------------------------------------------------ Procedure TAlgorithm.ConstructorWebcamMatrix; var i,j:integer; pvScanLine:PIntegerArray; begin for i := 0 to self.bmBitmap.Height-1 do begin pvScanLine:=bmBitmap.ScanLine[i]; for j := 0 to self.bmBitmap.Width-1 do vWebcamMatrix[i,j]:=GetRValue(pvScanLine[j]); end; self.iWebcamMatrixWidth:=self.bmBitmap.Width; self.iWebcamMatrixHeight:=self.bmBitmap.Height; end; //------------------------------------------------------------------------------ Procedure TAlgorithm.Process(bmBitmap:TBitmap); var iLeft,iTop,iRight,Bottom,iCount:integer; begin self.bmBitmap:=bmBitmap; self.bmBitmap.PixelFormat:=pf32Bit; if bmBitmap = NIL then exit; self.ConstructorWebcamMatrix; self.ClearList; iCount:=0; iLeft:=0; while iLeft &lt; iWebcamMatrixWidth-iMinWidth do begin iTop:=0; while iTop&lt;iWebcamMatrixHeight-iMinHeight do begin iRight:=iMinWidth; while (iRight &lt; iMaxWidth)and(iLeft+iRight&lt;iWebcamMatrixWidth) do begin iBottom:=iMinHeight; while (iBottom &lt; iMaxHeight)and(iTop+iBottom&lt;iWebcamMatrixHeight) do begin if self.Haar.Execute(iLeft,iTop,iLeft+iRight,iTop+iBottom) then AddSolution(iLeft,iTop,iLeft+iRight,iTop+iBottom); //iCount:=iCount+1; Inc(iBottom,iDistY); end; iCount:=iCount+1; inc(iRight,iDistX); end; iTop:=iTop+iDistY; end; iLeft:=iLeft+iDistX; end; self.DrawList; // //ShowMessage(IntToStr(iCount)); //Verify algorithm end; //------------------------------------------------------------------------------ Procedure TAlgorithm.ClearList; begin SetLength(self.vRects,0); end; //------------------------------------------------------------------------------ Procedure TAlgorithm.DrawList; var i:integer; begin self.bmBitmap.Canvas.Brush.Style:=bsClear; self.bmBitmap.Canvas.Pen.Color:=clRed; for i := 0 to High(self.vRects) do self.bmBitmap.Canvas.Rectangle(vRects[i].Left,vRects[i].Top,vRects[i].Right,vRects[i].Bottom); end; //------------------------------------------------------------------------------ Constructor TAlgorithm.Create(iMinWidth,iMinHeight,iMaxWidth,iMaxHeight,iDistX,iDistY:integer; sHaarPath:String; iWhite,iBlack:integer); begin inherited Create; // bmRect:=TBitmap.Create; // bmRect.PixelFormat:=pf32Bit; self.iMinWidth:=iMinWidth; self.iMinHeight:=iMinHeight; self.iMaxWidth:=iMaxWidth; self.iMaxHeight:=iMaxHeight; self.iDistX:=iDistX; self.iDistY:=iDistY; Haar:=THaarFeature.Create(sHaarPath,@self.vWebcamMatrix,iWhite,iBlack); end; //------------------------------------------------------------------------------ end. </code></pre> <p>and HaarClass</p> <pre><code>Uses Classes,SysUtils,Messages,Dialogs,Windows,Graphics; Type TWebcamMatrix = array [0..512,0..512] of integer; Type PWebcamMatrix = ^ TWebcamMatrix; Type THaarFeature = class(TObject) public vHaarMatrix:array of array of integer; pvMatrixArray:PWebcamMatrix; iRectWidth,iRectHeight:integer; Procedure Load(sPath:String); Function Execute(iLeft,iTop,iRight,iBottom:integer):Boolean; private iWhite,iBlack:integer; published Constructor Create(sPath:string; pvMatrixArray:PWebcamMatrix; iWhite,iBlack:integer); end; implementation //------------------------------------------------------------------------------ Function THaarFeature.Execute(iLeft,iTop,iRight,iBottom:integer):Boolean; var i,j,a,b,an,bn:integer; x,y,fi,fj:real; begin if self.pvMatrixArray = NIL then exit; a:=0; an:=0; b:=0; an:=0; iRectWidth:=iRight-iLeft; iRectHeight:=iBottom-iTop; y:=High(self.vHaarMatrix) / iRectHeight ; x:=High(self.vHaarMatrix[0]) / iRectWidth ; fi:=0; for i := iTop to iBottom do begin fj:=0; for j := iLeft to iRight do begin if (vHaarMatrix[Trunc(fi)][Trunc(fj)]=1) then begin a:=a+self.pvMatrixArray^[i,j]; an:=an+1; end else begin b:=b+self.pvMatrixArray^[i,j]; bn:=bn+1; end; fj:=fj+x; end; fi:=fi+y; end; if an=0 then a:=100 else a:=a div an; if bn=0 then b:=0 else b:=b div bn; if (a&gt;self.iWhite)and(b&lt;self.iBlack) then begin Result:=true; end else begin Result:=false; end; end; //------------------------------------------------------------------------------ Procedure THaarFeature.Load(sPath:String); var fIn:Text; i,j,n,m,nr:integer; begin if (FileExists(sPath) = false) then begin MessageDlg('File not exists',mtError,[mbOK],1); exit; end; try AssignFile(fIn,sPath); System.Reset(fIn); n:=0; while not eof(fIn) do begin m:=0; while not eoln(fIn) do begin read(fin,nr); inc(m); end; readln(fin); inc(n); end; CloseFile(fIn); SetLength(self.vHaarMatrix,n,m); AssignFile(fIn,sPath); System.Reset(fIn); for i := 0 to high(self.vHaarMatrix) do begin for j := 0 to high(self.vHaarMatrix[0]) do begin read(fin,vHaarMatrix[i][j]); end; readln(fin); end; CloseFile(fIn); except MessageDlg('Error assigning file to read haar matrix',mtError,[mbOK],1); end; end; //------------------------------------------------------------------------------ Constructor THaarFeature.Create(sPath:string; pvMatrixArray:PWebcamMatrix; iWhite,iBlack:integer); begin inherited Create; self.iWhite:=iWhite; self.pvMatrixArray:=pvMatrixArray; self.iBlack:=iBlack; self.Load(sPath); end; //------------------------------------------------------------------------------ end. </code></pre> <p>Parameters for objAlgorithm:=TAlgorithm.Create(30,30,60,60,9,9 _sPath, 200,50);</p> <p>For these parameters it works very well, but if i would like to improve and make smaller the iDistX, and iDistY to 8 or 7 it is very slow, and the bitmap must have a 128x128 pixels. Trully it is a polinomial complexity , it is about n^6. </p> <p>Description of the algorithm: It takes a lot of windows(now it doesn't scale anymore), and using a haar function it calculate a sum of pixels from a matrix). Like a face recognition(it is the same priciple, but currently i don't have the neural network, and just the haar function and not in the same porpose)</p> <p>I use that strange reading of haar matrix because in that file it doesn't include the length of haar function.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T20:41:07.527", "Id": "16935", "Score": "2", "body": "`CopyRect` calls `StretchBlt`. That's pretty well optimised. What makes you thing it is reasonable to expect better performance? How slow is slow?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T21:04:04.243", "Id": "16938", "Score": "1", "body": "If you stretch the same image over and over, you should really look at caching the image, instead of recalculating from scratch." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T21:38:51.537", "Id": "16942", "Score": "3", "body": "Maybe multithreading can help a little by distributing the image processing to every processor core." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T22:09:32.930", "Id": "16943", "Score": "1", "body": "@hubalu Not if the copying all modifies a single image, but of course we don't really know anything." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-27T07:31:10.720", "Id": "16944", "Score": "3", "body": "It's not slow at all. The only possible speed-up I could imagine for this case, is if you somehow managed to transfer the entire bitmap to the graphics card, and then have all the 17.000 stretches done directly from the graphics card memory, by the GPU. Then maybe you could see a speed increase. Otherwise not, I think." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-27T09:51:14.750", "Id": "16945", "Score": "0", "body": "I made a mistake, 1,700 copyrect it takes me about 20 seconds. Not 17,000" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-27T15:19:14.373", "Id": "16946", "Score": "3", "body": "@user558126: That makes it 11.8 milliseconds per image, or 85 images per second, which is still pretty quick. We can't tell you anything else without you giving us a lot more information about how much faster it needs to be, what exactly is happening, and exactly which piece of code needs optimizing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-27T23:23:15.670", "Id": "16949", "Score": "3", "body": "So where in the world is your bottle-neck? is it `Process`? and why are you using `pf32Bit` format for? I really think you need to delete this Q, and post the bottle-neck code only because it's a big salad right now..." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T20:37:25.317", "Id": "10620", "Score": "5", "Tags": [ "delphi" ], "Title": "Fastest function for TCanvas.CopyRect" }
10620
<p>I am completely new to Objective-C. I have written a simple SingleView Tic Tac Toe Application application for learning purposes. While writing the app, I've tried to be as much sound as I could. Since this is my first shot, I think it can be improved a lot.</p> <p>Please tell me what you think about it and what you see I made wrong so I can avoid those mistakes the next time.</p> <p>Is there code redundancy I don't see? Is everything declared and implemented at its right place?</p> <p>I will gladly provide more information about the app if needed. Just tell me!</p> <p>The board has this structure:</p> <pre><code>slot1 | slot2 | slot3 --------------------- slot4 | slot5 | slot6 --------------------- slot7 | slot8 | slot9 </code></pre> <p>This is the file <code>main.m</code>: (This was auto generated by Xcode.)</p> <pre><code>#import &lt;UIKit/UIKit.h&gt; #import "tttAppDelegate.h" int main(int argc, char *argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([tttAppDelegate class])); } } </code></pre> <p>This is the file <code>ViewController.h</code>:</p> <pre><code>#import &lt;UIKit/UIKit.h&gt; @interface tttViewController : UIViewController @property (nonatomic, retain) UIImage *circle; @property (nonatomic, retain) UIImage *cross; @property (nonatomic, retain) UIImage *imageToPlace; @property (weak, nonatomic) IBOutlet UIImageView *board; @property (weak, nonatomic) IBOutlet UIImageView *slot1; @property (weak, nonatomic) IBOutlet UIImageView *slot2; @property (weak, nonatomic) IBOutlet UIImageView *slot3; @property (weak, nonatomic) IBOutlet UIImageView *slot4; @property (weak, nonatomic) IBOutlet UIImageView *slot5; @property (weak, nonatomic) IBOutlet UIImageView *slot6; @property (weak, nonatomic) IBOutlet UIImageView *slot7; @property (weak, nonatomic) IBOutlet UIImageView *slot8; @property (weak, nonatomic) IBOutlet UIImageView *slot9; @property (weak, nonatomic) IBOutlet UILabel *msg; @property (nonatomic, retain) UIAlertView *myAlertView; @property (nonatomic, readwrite) NSInteger player; @property (nonatomic, readwrite) NSInteger round; /** * Resets the game by clearing the board and setting the variable `player` to 1. */ - (IBAction)resetButton:(id)sender; /** * Determines the status of the game. If all 9 fields were used or if there are * 3 circles or 3 crosses in a row it invokes an alertview which tells who won * thegame. */ - (void)gameStatus; /** * Changes players and updates the label which displays the player name. * Places the "cross" or the "circle on the board. */ - (void)switchPlayers; /** * Checks if somone has won and returns true. */ - (BOOL)somebodyWon; @end </code></pre> <p>And this is <code>ViewController.m</code>:</p> <pre><code>#import "tttViewController.h" @implementation tttViewController // @synthesize means "create getter and setter" methods. @synthesize slot1, slot2, slot3, slot4, slot5, slot6, slot7, slot8, slot9; @synthesize circle; @synthesize cross; @synthesize imageToPlace; @synthesize board; @synthesize msg; @synthesize myAlertView; @synthesize player; @synthesize round; - (void)viewDidLoad { circle = [UIImage imageNamed:@"circle.png"]; cross = [UIImage imageNamed:@"cross.png"]; player = 1; round = 0; msg.text = @"Player 1: Put a \"Cross\" on the field!"; [super viewDidLoad]; // Autogenerated. } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ if (player == 1) { imageToPlace = cross; } else if (player == 2) { imageToPlace = circle; } UITouch *touch = [[event allTouches] anyObject]; [self slot:slot1 wasTouched:touch]; [self slot:slot2 wasTouched:touch]; [self slot:slot3 wasTouched:touch]; [self slot:slot4 wasTouched:touch]; [self slot:slot5 wasTouched:touch]; [self slot:slot6 wasTouched:touch]; [self slot:slot7 wasTouched:touch]; [self slot:slot8 wasTouched:touch]; [self slot:slot9 wasTouched:touch]; } -(void)slot:(UIImageView *)slot wasTouched:(UITouch *)touch { if ((slot.image == NULL) &amp;&amp; CGRectContainsPoint([slot frame], [touch locationInView:self.view])) { slot.image = imageToPlace; round++; [self gameStatus]; } } -(void)gameStatus{ BOOL win = [self somebodyWon]; if (round == 9 || win) { myAlertView = nil; NSString *result = nil; if (round == 9 &amp;&amp; !win) { result = @"Draw!"; } else if (round &lt;= 9 &amp;&amp; win){ if(player == 1){ result = @"Player 1 won!"; } else if(player == 2){ result = @"Player 2 won!"; } } else { result = @"Sorry! Something went wrong when determining win/draw situation."; } myAlertView = [[UIAlertView alloc] initWithTitle:@"Result:" message:result delegate:self cancelButtonTitle:@"Ok!" otherButtonTitles:nil, nil]; [myAlertView show]; [self resetBoard]; } else { [self switchPlayers]; } } -(BOOL)somebodyWon{ /** * Check for win in the leftmost column and in the topmost row. */ if(slot1.image != NULL) { if (((slot1.image == slot2.image) &amp;&amp; (slot1.image == slot3.image)) || ((slot1.image == slot4.image) &amp;&amp; (slot1.image == slot7.image))) { return YES; } } /** * Check for wins that goe through the middle of the board. */ if(slot5.image != NULL) { if (((slot5.image == slot4.image) &amp;&amp; (slot5.image == slot6.image)) || ((slot5.image == slot2.image) &amp;&amp; (slot5.image == slot8.image)) || ((slot5.image == slot1.image) &amp;&amp; (slot5.image == slot9.image)) || ((slot5.image == slot3.image) &amp;&amp; (slot5.image == slot7.image))) { return YES; } } /** * Check for win in the rightmost column and in the lowest row. */ if(slot9.image != NULL) { if (((slot9.image == slot6.image) &amp;&amp; (slot9.image == slot3.image)) || ((slot9.image == slot8.image) &amp;&amp; (slot9.image == slot7.image))) { return YES; } } return NO; } - (IBAction)resetButton:(id)sender { [self resetBoard]; } //-(IBAction)buttonReset{ // [self resetBoard]; //} -(void)resetBoard{ slot1.image = NULL; slot2.image = NULL; slot3.image = NULL; slot4.image = NULL; slot5.image = NULL; slot6.image = NULL; slot7.image = NULL; slot8.image = NULL; slot9.image = NULL; player = 1; msg.text = @"Player 1: Put a \"Cross\" on the field"; round = 0; } -(void)switchPlayers{ if (player == 1){ player = 2; msg.text = @"Player 2: Put a \"Circle\" on the field"; } else { player = 1; msg.text = @"Player 1: Put a \"Cross\" on the field"; } } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } @end </code></pre>
[]
[ { "body": "<pre><code>#import \"tttViewController.h\"\n\n@implementation tttViewController\n\n// @synthesize means \"create getter and setter\" methods.\n</code></pre>\n\n<p>I'd avoid commenting to explain language features. Assume your reader knows the language.</p>\n\n<pre><code>@synthesize slot1, slot2, slot3, slot4, slot5, slot6, slot7, slot8, slot9;\n</code></pre>\n\n<p>Slot has a particular meaning in objective-c, so I'd pick another name to use here</p>\n\n<pre><code>@synthesize circle;\n@synthesize cross;\n@synthesize imageToPlace;\n@synthesize board;\n@synthesize msg;\n@synthesize myAlertView;\n@synthesize player;\n@synthesize round;\n\n- (void)viewDidLoad {\n circle = [UIImage imageNamed:@\"circle.png\"];\n cross = [UIImage imageNamed:@\"cross.png\"];\n</code></pre>\n\n<p>I'd put these in an array, then you can avoid using if to pick them</p>\n\n<pre><code> player = 1;\n round = 0;\n msg.text = @\"Player 1: Put a \\\"Cross\\\" on the field!\";\n\n [super viewDidLoad]; // Autogenerated.\n}\n\n- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{\n if (player == 1) {\n imageToPlace = cross;\n } else if (player == 2) {\n imageToPlace = circle;\n }\n</code></pre>\n\n<p>Don't use object variables to pass data. Pass it as function arguments</p>\n\n<pre><code> UITouch *touch = [[event allTouches] anyObject];\n [self slot:slot1 wasTouched:touch];\n [self slot:slot2 wasTouched:touch];\n [self slot:slot3 wasTouched:touch];\n [self slot:slot4 wasTouched:touch];\n [self slot:slot5 wasTouched:touch];\n [self slot:slot6 wasTouched:touch];\n [self slot:slot7 wasTouched:touch];\n [self slot:slot8 wasTouched:touch];\n [self slot:slot9 wasTouched:touch];\n</code></pre>\n\n<p>Instead of doing this, create a <code>slots</code> array and push all the slots in it. Then you can use a loop for things like this</p>\n\n<pre><code>}\n\n-(void)slot:(UIImageView *)slot wasTouched:(UITouch *)touch {\n</code></pre>\n\n<p>This name is somewhat confusing because it implies the slot was touched. However, since you call it for all the touches that may not be true</p>\n\n<pre><code> if ((slot.image == NULL) &amp;&amp;\n CGRectContainsPoint([slot frame], [touch locationInView:self.view])) {\n slot.image = imageToPlace;\n round++;\n [self gameStatus];\n } \n}\n\n-(void)gameStatus{\n</code></pre>\n\n<p>The name <code>gameStatus</code> implies that it returns the game status. But this is really more of a <code>updateGameStatus</code></p>\n\n<pre><code> BOOL win = [self somebodyWon];\n if (round == 9 || win) {\n myAlertView = nil;\n</code></pre>\n\n<p>Why isn't this a local variable?</p>\n\n<pre><code> NSString *result = nil;\n</code></pre>\n\n<p>Result isn't a very clear name, <code>text</code> would be better</p>\n\n<pre><code> if (round == 9 &amp;&amp; !win) {\n</code></pre>\n\n<p>All you really want to do is handle win or not win. Your logic here is way complicated. Just do <code>if(win)</code></p>\n\n<pre><code> result = @\"Draw!\";\n }\n else if (round &lt;= 9 &amp;&amp; win){\n if(player == 1){\n result = @\"Player 1 won!\";\n }\n else if(player == 2){\n result = @\"Player 2 won!\";\n }\n }\n else {\n result = @\"Sorry! Something went wrong when determining win/draw situation.\";\n }\n</code></pre>\n\n<p>Cleanup your logic so it's clear this'll never happen and then get rid of this silly case.</p>\n\n<pre><code> myAlertView = [[UIAlertView alloc] initWithTitle:@\"Result:\" message:result delegate:self cancelButtonTitle:@\"Ok!\" otherButtonTitles:nil, nil];\n</code></pre>\n\n<p>Do you really need the delegate here?</p>\n\n<pre><code> [myAlertView show];\n [self resetBoard];\n } else {\n [self switchPlayers];\n }\n}\n\n-(BOOL)somebodyWon{\n</code></pre>\n\n<p>The name is ambigious. It could check is somebody won or it could be called if somebody won</p>\n\n<pre><code> /**\n * Check for win in the leftmost column and in the topmost row.\n */\n if(slot1.image != NULL) {\n if (((slot1.image == slot2.image) &amp;&amp; (slot1.image == slot3.image)) ||\n ((slot1.image == slot4.image) &amp;&amp; (slot1.image == slot7.image))) {\n return YES;\n }\n }\n</code></pre>\n\n<p>Slightly confusing way to do this. If you put the slots in an array, you should be able to simplify this logic. Also, generally prefer to store game state in normal variables, not as whether images are set on ui controls.</p>\n\n<pre><code> /**\n * Check for wins that goe through the middle of the board.\n */\n if(slot5.image != NULL) {\n if (((slot5.image == slot4.image) &amp;&amp; (slot5.image == slot6.image)) ||\n ((slot5.image == slot2.image) &amp;&amp; (slot5.image == slot8.image)) ||\n ((slot5.image == slot1.image) &amp;&amp; (slot5.image == slot9.image)) ||\n ((slot5.image == slot3.image) &amp;&amp; (slot5.image == slot7.image))) {\n return YES;\n }\n } \n\n /**\n * Check for win in the rightmost column and in the lowest row.\n */\n if(slot9.image != NULL) {\n if (((slot9.image == slot6.image) &amp;&amp; (slot9.image == slot3.image)) ||\n ((slot9.image == slot8.image) &amp;&amp; (slot9.image == slot7.image))) {\n return YES;\n }\n }\n\n return NO;\n</code></pre>\n\n<p>Consider returning a number of options: Stalement, X-Wins, Y-Wins, GameContinues. I think that'll make the code clearer</p>\n\n<pre><code>}\n\n- (IBAction)resetButton:(id)sender {\n [self resetBoard];\n}\n\n//-(IBAction)buttonReset{\n// [self resetBoard];\n//}\n</code></pre>\n\n<p>Delete dead code, don't comment it out</p>\n\n<pre><code>-(void)resetBoard{\n slot1.image = NULL;\n slot2.image = NULL;\n slot3.image = NULL;\n slot4.image = NULL;\n slot5.image = NULL;\n slot6.image = NULL;\n slot7.image = NULL;\n slot8.image = NULL;\n slot9.image = NULL;\n\n player = 1;\n msg.text = @\"Player 1: Put a \\\"Cross\\\" on the field\";\n round = 0;\n</code></pre>\n\n<p>Message is duplicated, put it in a constant, or find a way to use switchPlayers</p>\n\n<pre><code>}\n\n-(void)switchPlayers{\n if (player == 1){\n player = 2;\n msg.text = @\"Player 2: Put a \\\"Circle\\\" on the field\";\n } else {\n player = 1;\n msg.text = @\"Player 1: Put a \\\"Cross\\\" on the field\";\n }\n}\n\n- (void)viewDidUnload\n{\n [super viewDidUnload];\n // Release any retained subviews of the main view.\n}\n\n- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation\n{\n return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);\n}\n\n@end\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T11:48:39.770", "Id": "16981", "Score": "2", "body": "Create Player class with name, picture and something else player specific! So you can avoid this ifs in your code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T08:14:47.700", "Id": "17041", "Score": "0", "body": "Winston, you're awesome. This is more then I hoped for. I will revamp the program and get back to you with the improved version as soon as I can. Thank very much so far!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T08:17:12.890", "Id": "17042", "Score": "0", "body": "@DenisMikhaylov, your comment was inspiring too, thanks! I will invent a `Player` and a `Game` class to my code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T09:15:27.277", "Id": "17399", "Score": "2", "body": "What is the special meaning of slot in Objective-c?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-27T18:58:39.683", "Id": "18089", "Score": "0", "body": "@JeremyP, Honestly, its fairly rarely used so it probably doesn't matter. The slot terminology was inherited from Smalltalk and is used more often there, and only occasionally in Objective-C." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T16:44:12.630", "Id": "18295", "Score": "0", "body": "@WinstonEwert \"The Objective-C Programming Language\" does not name a language feature named slot. Great answer, anyway." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T03:21:51.920", "Id": "10633", "ParentId": "10625", "Score": "5" } } ]
{ "AcceptedAnswerId": "10633", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T18:50:41.580", "Id": "10625", "Score": "7", "Tags": [ "beginner", "objective-c", "game" ], "Title": "Review of Tic Tac Toe game in Objective-C" }
10625
<p>I wrote a small JavaScript libary that aims to simplify JavaScript cookies. You can find the code on Github: <a href="https://github.com/js-coder/cookie.js" rel="nofollow">https://github.com/js-coder/cookie.js</a> I tested it in various browsers and it seems to work everywhere.</p> <p>It's not a lot of code so I'll insert it here as well: <em>I updated the code quite a bit so I posted the new version below.</em></p> <pre><code>(function (undefined) { var isArray = Array.isArray || function (value) { // check if value is an array created with [] or new Array return Object.prototype.toString.call(value) === '[object Array]'; }, isPlainObj = function (value) { // check if value is an object that was created with {} or new Object return Object.prototype.toString.call(value) === '[object Object]'; }, getKeys = Object.keys || function (obj) { // Object.keys polyfill var keys = [], key = ''; for (key in obj) { if (obj.hasOwnProperty(key)) keys.push(key); } return keys; }, retrieve = function (value, fallback) { // return fallback if the value is undefined, otherwise return value return value === undefined ? fallback : value; }, _cookie = { set: function (key, value, options) { if (isPlainObj(key)) { for (var k in key) { if (key.hasOwnProperty(k)) this.set(k, key[k]); } } else { options = options || {}; var expires = options.expires || '', expiresType = typeof(expires), path = options.path ? ';path=' + options.path : '', domain = options.domain ? ';domain=' + options.domain : '', secure = options.secure ? ';secure' : ''; if (expiresType === 'string' &amp;&amp; expires !== '') expires = ';expires=' + expires; else if (expiresType == 'number') { // this is needed because IE does not support max-age var d = new Date; d.setTime(d.getTime() + expires); expires = ';expires=' + d.toGMTString(); } else if (expires.hasOwnProperty('toGMTString')) expires = ';expires=' + expires.toGMTString(); document.cookie = key + '=' + escape(value) + expires + path + domain + secure; } return this; // return the _cookie object to allow chaining }, remove: function (keys) { keys = isArray(keys) ? keys : arguments; for (var i = 0, length = keys.length; i &lt; length; i++) { this.set(keys[i], '', { expires: -60 * 60 * 24 }); } return this; // return the _cookie object to allow chaining }, empty: function () { return this.remove(getKeys(this.all())); // return the _cookie object to allow chaining }, get: function (key, fallback) { fallback = fallback || undefined; if (isArray(key)) { var result = {}, cookies = this.all(); for (var i = 0, l = key.length; i &lt; l; i++) { var value = key[i]; result[value] = retrieve(cookies[value], fallback); } return result; } else { var cookies = this.all(); return retrieve(cookies[key], fallback); } }, all: function () { if (document.cookie == '') return {}; var match = document.cookie.split('; '), results = {}; for (var i = 0, l = match.length; i &lt; l; i++) { var tmp = match[i].split('='); results[tmp[0]] = unescape(tmp[1]); } return results; }, enabled: function () { var ret = cookie.set('a', 'b').get('a') === 'b'; cookie.remove('a'); return ret; } }, cookie = function (key, fallback) { return _cookie.get(key, fallback); }, methods = ['set', 'remove', 'empty', 'get', 'all', 'enabled']; for (var i = 0, l = methods.length; i &lt; l; i++) { // copy all _cookie methods to cookie var method = methods[i]; cookie[method] = _cookie[method]; } window.cookie = cookie; }()); </code></pre> <p>You can find the documentation here: <a href="https://github.com/js-coder/cookie.js/blob/master/readme.md" rel="nofollow">https://github.com/js-coder/cookie.js/blob/master/readme.md</a></p> <p>I would love to know how I can improve the code or the API.</p>
[]
[ { "body": "<p>I think you want to pass on the <code>options</code> argument and filter with <code>hasOwnProperty()</code> so inside of the <code>.set()</code> method this:</p>\n\n<pre><code> if (isPlainObj(key)) {\n for (var k in key) {\n this.set(k, key[k]);\n }\n }\n</code></pre>\n\n<p>becomes this:</p>\n\n<pre><code> if (isPlainObj(key)) {\n for (var k in key) {\n if (key.hasOwnProperty(k)) {\n this.set(k, key[k], options);\n }\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T18:16:09.703", "Id": "17070", "Score": "0", "body": "`Object.prototype.hasOwnProperty.call(key, k)`; otherwise you have unexpected behavior if your data contains a `hasOwnProperty` property." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T18:34:11.747", "Id": "17071", "Score": "0", "body": "@KevinReid - if an object has its own override property called `hasOwnProperty`, then it would seem that it intends to override it. If we always followed your suggestion, we'd never use a native method of an object, we'd always refer to everything from `Object.prototype`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T22:55:29.063", "Id": "17094", "Score": "0", "body": "I prefer to distinguish between objects-as-data-structures (which this is intending to be as it doesn't read inherited properties etc.) and objects-as-OO with methods and properties, where inheritance is not rejected." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T00:22:48.003", "Id": "17096", "Score": "0", "body": "@KevinReid - But, JS doesn't have data only objects. An object is an object and every object has methods which one should be free to use. I understand the point you're making, but I don't think that's the way JS was designed to be use. You are free to use it that way yourself, I guess." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T16:29:28.803", "Id": "17244", "Score": "0", "body": "@jfriend00 I agree with you. BTW I fixed this with the latest update on github. :) https://github.com/js-coder/cookie.js/blob/master/cookie.js" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T19:45:20.863", "Id": "10627", "ParentId": "10626", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T19:30:16.207", "Id": "10626", "Score": "2", "Tags": [ "javascript", "library" ], "Title": "Review my JavaScript cookie library" }
10626
<p>I'm in QA Automation, and C# isn't my first language. I've written a small class of methods for GETting and POSTing to web URLs. I use these when I want to test certain things that really fall outside the jurisdiction of Selenium, but are still roughly "black box" type testing. Link scanning, and culling data from POSTBIN, are a few examples. </p> <p>I was wondering if you C# gurus might like to look the code over, and let me know if there are better ways to do what I've done, or if there's any potential gotcha's I haven't thought of:</p> <pre><code>public class RawHttp { public static string Url = null; public RawHttp(string url) { Url = url; } public HttpStatusCode GetStatusCode(string url = null) { HttpStatusCode result = default(HttpStatusCode); string activeUrl = url ?? Url; var request = WebRequest.Create(activeUrl); request.Method = "HEAD"; using (var response = request.GetResponse() as HttpWebResponse) { if (response != null) { result = response.StatusCode; //var headers = response.Headers; response.Close(); } } return result; } public string GetBody(string url = null) { string activeUrl = url ?? Url; var request = (HttpWebRequest)WebRequest.Create(activeUrl); request.Method = "GET"; // Set some reasonable limits on resources used by this request request.MaximumAutomaticRedirections = 4; request.MaximumResponseHeadersLength = 4; // Set credentials to use for this request. request.Credentials = CredentialCache.DefaultCredentials; var response = (HttpWebResponse)request.GetResponse(); //Console.WriteLine("Content length is {0}", response.ContentLength); //Console.WriteLine("Content type is {0}", response.ContentType); // Get the stream associated with the response. Stream receiveStream = response.GetResponseStream(); // Pipes the stream to a higher level stream reader with the required encoding format. var readStream = new StreamReader(receiveStream, Encoding.UTF8); var body = readStream.ReadToEnd(); response.Close(); readStream.Close(); return body; } public string Post(string url = null, string parameters = "") { string activeUrl = url ?? Url; var req = WebRequest.Create(activeUrl); req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; byte[] bytes = Encoding.ASCII.GetBytes(parameters); req.ContentLength = bytes.Length; Stream os = req.GetRequestStream(); os.Write(bytes, 0, bytes.Length); //Push it out there os.Close(); var resp = req.GetResponse(); //if (resp == null) {return null;} var sr = new System.IO.StreamReader(resp.GetResponseStream()); return sr.ReadToEnd().Trim(); } } </code></pre> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T00:01:00.993", "Id": "16963", "Score": "1", "body": "Hello Greg. Is this strictly used as a utility? Do you test repeated things, like test a=status code success and then b = check something in the body? Also, you are switching between the static \"Url\" variable and the actual instance (the class is instance based and not static), what is the use case you are shooting for? Is there any other forms of functionality that you want to add onto this in the future? Is this code being included in something else (i.e. how does it interact with your test suite)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T21:53:18.233", "Id": "17232", "Score": "0", "body": "Thanks for the questions, Randy. I suppose I should have supplied some examples when I created this question. I've not had a lot of time to revisit this, though. I'm sorry for that. I'll respond in more detail later this week." } ]
[ { "body": "<p>It's probably fine for test code. There are a few things I noticed. None of these are necessarily a problem. They may never affect your tests. But they're not ideal either. </p>\n\n<ol>\n<li>You're not calling <code>Dispose()</code> on everything that you strictly should (eg, Streams).</li>\n<li>You're always encoding your post parameters in ASCII, but reading the responses in UTF8. If you're sticking to basic English characters that'll be fine, but if you try other languages/character sets it may be problematic. </li>\n<li>the GetStatusCode() function is using the HEAD method. Not all endpoints will respond properly to the HEAD method, or is the same way that they would to GET or POST. </li>\n</ol>\n\n<p>If you're going to be doing a lot of this then you may want to look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.100%29.aspx\" rel=\"nofollow\">WebClient</a> class. It's a little bit simpler to use, and may be sufficient for your needs. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T19:56:18.400", "Id": "16993", "Score": "0", "body": "Using `using` is even better than calling `.Dispose()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T20:07:12.253", "Id": "16995", "Score": "2", "body": "From a disposal standpoint they're equivalent, though `using` is frequently more convenient. At any rate, he's not doing either of them in several cases." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T21:54:50.913", "Id": "17233", "Score": "0", "body": "Thanks @breischl, these are really good tips. Sorry I haven't responded sooner. Things have been busy here." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T18:35:46.253", "Id": "10647", "ParentId": "10630", "Score": "1" } } ]
{ "AcceptedAnswerId": "10647", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T21:18:21.750", "Id": "10630", "Score": "4", "Tags": [ "c#", "classes" ], "Title": "C# Class of client methods for interacting with web servers" }
10630
<p>I coded a linear (without threads) app, which looks ok and has normal solving speed. Also, I coded a multithreaded app, and it is ok when I use 2 processors and 2 threads. It is also fine when I use 4 processors and 4 threads. But when I try to solve with 6 processors and 6 threads, I am not satisfied with the solving speed. How can I make it faster?</p> <p><strong>Main.java:</strong></p> <pre><code>import java.util.Scanner; public class Main { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub //Scanner scanner = new Scanner(System.in); //System.out.println("Iveskite N:"); //int n = Integer.parseInt(scanner.nextLine()); int n = Integer.parseInt(args[0]); int maxThreads = Integer.parseInt(args[1]); Karalienes.setMaxGSK(maxThreads); Karalienes queens = new Karalienes(n, 1, new int[n+1]); long startedTime = System.currentTimeMillis(); queens.start(); queens.join(); System.out.println("Solutions: "+Karalienes.getVariantuSkaiciu()); //queens.print(); System.out.println("Working time: "+(float)(System.currentTimeMillis()-startedTime)/1000 + " s."); } } </code></pre> <p><strong>Karalienes.java:</strong></p> <pre><code>import java.util.Stack; public class Karalienes extends Thread { private int n; private int places[]; private int column; private static Integer solutions = new Integer(0); private static Integer startedThreads = 0; private static int maxThreads; private Stack&lt;Karalienes&gt; stack; public Karalienes(int n,int column, int places[]) { this.n = n; this.column = column; this.places = places; stack = new Stack&lt;Karalienes&gt;(); } public static void setMaxGSK(int sk) { this.maxThreads = sk; } private boolean arOk(int row, int column) { boolean ok = true; int tmpColumn = column-1; for(; tmpColumn&gt;=1; tmpColumn--) { if ((places[tmpColumn]-row)==0) { ok = false; break; } int rowDiff = places[column] - places[tmpColumn]; if (rowDiff &lt; 0) rowDiff = 0 - rowDiff; if (rowDiff == column-tmpColumn) { ok = false; break; } } return ok; } public void deliojam() { for(int i=1; i&lt;=n ; i++ ) { //dirbam su row places[column] = i; if (arOk(i, column)) { if (column&lt;n) { int gSk; synchronized (startedThreads) { gSk = startedThreads; } if (gSk &lt; maxThreads) { Karalienes kar = new Karalienes(n, column+1, places.clone()); kar.start(); stack.add(kar); } else { column++; deliojam(); column--; } } if (column==n) { Karalienes.incVariantuSkaiciu(); } } } while (stack.size()!=0) { try { stack.pop().join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override public void run() { // TODO Auto-generated method stub Karalienes.incGijuSk(); deliojam(); Karalienes.decGijuSk(); } private static synchronized void incVariantuSkaiciu() { solutions++; } private static synchronized void incGijuSk() { startedThreads++; } private static synchronized void decGijuSk() { startedThreads--; } public static int getVariantuSkaiciu() { return solutions; } } </code></pre> <p><strong>List of times:</strong></p> <blockquote> <pre class="lang-none prettyprint-override"><code>Computer (code with threads) Proc Threads N Working time (in seconds) 2 2 9 0,022 2 2 10 0,052 2 2 11 0,106 2 2 12 0,299 2 2 13 1,342 2 2 14 7,303 2 2 15 47,486 2 2 16 345,369 2 2 17 2702,898 4 4 9 0,043 4 4 10 0,067 4 4 11 0,135 4 4 12 0,438 4 4 13 1,609 4 4 14 7,146 4 4 15 42,196 4 4 16 293,293 4 4 17 2038,762 6 6 9 0,053 6 6 10 0,09 6 6 11 0,194 6 6 12 0,483 6 6 13 1,99 6 6 14 10,347 6 6 15 62,086 6 6 16 420,496 6 6 17 2915,52 </code></pre> </blockquote>
[]
[ { "body": "<p>You're probably encountering locking between threads, where the <code>synchronized</code> between threads is costing you more than you gain. Here's what I'd do:</p>\n\n<ul>\n<li>Instead of using <code>synchronized</code> to protect your counters I'd use <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html\" rel=\"nofollow\"><code>AtomicInteger</code></a> to reduce the amount of locking between threads.</li>\n<li>Instead of creating and lots of short-lived threads yourself, I'd use a a thread pool (e.g. <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html\" rel=\"nofollow\"><code>ThreadPoolExecutor</code></a>. You can use <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html#setMaximumPoolSize%28int%29\" rel=\"nofollow\"><code>setMaximumPoolSize</code></a> to restrict the number of threads being used. The executor service will provide a queue of jobs.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T14:03:27.023", "Id": "10644", "ParentId": "10643", "Score": "4" } } ]
{ "AcceptedAnswerId": "10644", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T11:20:12.987", "Id": "10643", "Score": "5", "Tags": [ "java", "performance", "multithreading", "n-queens" ], "Title": "N-queens multithreaded working time" }
10643
<p>The problem is find the number of factors of (N!)^2.</p> <p>This is the code, I wrote:</p> <pre><code>int prime[]={//list of primes &lt;(10^6)}; int num_fac_of_factorial(int n, int x) { int p=x, z=0; while(n/p&gt;0) { z+=n/p; p*=x; } return z; } int count=78498; //Count of prime numbers &lt;10^6 int main() { int n, x, first=0, m=1000007; long long sol=1; scanf("%d", &amp;n); for(int i=0; prime[i]&lt;=n &amp;&amp; i&lt;count; i++) { x=num_fac_of_factorial(n, prime[i]); x=2*x+1; sol=(sol*x)%m; } sol%=m; printf("%d\n", sol); } </code></pre>
[]
[ { "body": "<p>There's no flaw in the logic, just a couple of implementation errors. And if e.g. <code>1/10 + 1/15 = 1/6</code> and <code>1/15 + 1/10 = 1/6</code> shall not be counted as different solutions but as one, then of course you need <code>(1 + number of divisors)/2</code>.</p>\n\n<p>Here</p>\n\n<pre><code>for(int i=0; prime[i]&lt;=n &amp;&amp; i&lt;count; i++)\n</code></pre>\n\n<p>you ought to check <code>i &lt; count</code> before accessing <code>prime[i]</code>. If <code>n &gt; 999983</code>, you will try to access <code>prime[78498]</code>, which is undefined behaviour.</p>\n\n<p>And - assuming that <code>int</code> is as usual 32 bits (or 36, wouldn't apply to 64-bit <code>int</code>s, however) - here</p>\n\n<pre><code>int num_fac_of_factorial(int n, int x)\n{\n int p=x, z=0;\n while(n/p&gt;0)\n {\n z+=n/p;\n p*=x;\n }\n return z;\n}\n</code></pre>\n\n<p>you have overflow for large enough primes <code>x</code> (typically <code>&gt; 46340</code>) when calculating <code>x*x</code>, which is also undefined behaviour. And with the not uncommon wrap-around for <code>int</code> overflow, that will cause wrong results for <code>n &gt;= 65537</code>. Replace the <code>while</code> loop with</p>\n\n<pre><code>do {\n n /= x;\n z += n;\nwhile(n &gt; 0);\n</code></pre>\n\n<p>to avoid the overflow.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T06:42:47.623", "Id": "17017", "Score": "0", "body": "For the first time, I am glad that someone pointed out so many implementation errors in my code. :P\nBtw, as per the question I need not do (1 + no_of_divisors)/2. That's fine.\nThe i<count should have been before prime[i]<=n. And your point about the int overflow is also right. Thanks for pointing all this out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T09:37:47.700", "Id": "17020", "Score": "0", "body": "Two glitches. You have an interesting definition of 'many' ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T11:18:38.527", "Id": "17022", "Score": "0", "body": "When you are quite experienced and suddenly make silly mistakes, 'two' indeed is 'many'. :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T18:41:06.903", "Id": "10648", "ParentId": "10645", "Score": "1" } } ]
{ "AcceptedAnswerId": "10648", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T16:18:32.330", "Id": "10645", "Score": "4", "Tags": [ "c++", "algorithm" ], "Title": "Is there any flaw in the logic of this problem?" }
10645
<p>I want to create a ExtensionMethod to ordenate my linq query, called <code>Ordenar</code>. I'll sort it depending what columns is in <code>sortColumns</code> ListDictionary.</p> <p>I tried some ways, but the best way I arquieve was this :</p> <pre><code>static class ClienteBusinessExtensions { public static IQueryable&lt;Model.View_Clientes&gt; Ordernar(this IQueryable&lt;Model.View_Clientes&gt; viewClientes, ListDictionary sortColumns) { foreach (System.Collections.DictionaryEntry item in sortColumns) { if (item.Value.ToString()=="ASC") { switch (item.Key.ToString()) { case "ClienteID": viewClientes = viewClientes.OrderBy(v =&gt; v.ClienteID); break; case "Nome": viewClientes = viewClientes.OrderBy(v =&gt; v.Nome); break; default: break; } } else //item.Value.ToString() will be DESC { switch (item.Key.ToString()) { case "ClienteID": viewClientes = viewClientes.OrderByDescending(v =&gt; v.ClienteID); break; case "Nome": viewClientes = viewClientes.OrderByDescending(v =&gt; v.Nome); break; case "CpfCnpj": viewClientes = viewClientes.OrderByDescending(v =&gt; v.CpfCnpj); break; default: break; } } } return viewClientes; } </code></pre> <p>It is used like this :</p> <pre><code>var clientesVip = (from vips in db.View_Clientes .Ordernar(sortColumns) select vips); </code></pre> <p>Are there a clever way to do it? I don't want to use switch statement. I want to sort any field of View_Clientes. It is used in a Asp.NET gridView, when user sort a column.</p> <p>And View_Clientes entity is :</p> <pre><code>public partial class View_Clientes { public System.Guid ClienteID { get; set; } public string Codcfo { get; set; } public string Nome { get; set; } public string CpfCnpj { get; set; } public string CLI_Origem { get; set; } } </code></pre>
[]
[ { "body": "<p>You definitely could use DynamicLinq to solve this problem. See Scott Guthries blog post about it at:\n<a href=\"http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx\" rel=\"nofollow\">http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T20:03:10.693", "Id": "10651", "ParentId": "10646", "Score": "1" } } ]
{ "AcceptedAnswerId": "10651", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T17:39:37.970", "Id": "10646", "Score": "2", "Tags": [ "c#", "optimization", "linq", "entity-framework", "extension-methods" ], "Title": "Clever way to build a extension method that ordenate my IQueryable<T>?" }
10646
<p>I have a function that takes a point, and given its velocity, and acceleration, calculates the time(s) for the point to collide with the line:</p> <pre><code>def ParabolaLineCollision(pos, vel, acc, line): """A pure function that returns all intersections.""" pass </code></pre> <p>I have another function that wants to calculate the smallest intersection time between two entities, where an entity has a velocity/acceleration, and a list of vertices.</p> <p>The algorithm of entity_intersection creates lines for each objects' list of vertices, and then calls ParabolaLineCollision on each point of each object, with each line of the other object. My current algorithm runs slowly, and thus I would like to be able to parallelize the algorithm.</p> <p>My problem is that <code>entity_intersections</code> is a bit hard to read, and I think that there may be some code duplication, which might possibly be eliminated. Here's the algorithm, and </p> <pre><code>class Entity # ... @property def lines(self): """ Get a list of lines that connect self.points. If self.enclosed, then the last point will connect the first point. """ # type(self.enclosed) == bool # # I included this, as this may be where there is logic duplication with entity_intersections. # # It's also not very readable. return [(self.points[i-1], self.points[i]) for i in range((1-int(self.enclosed)), len(self.points))] # ... def entity_intersections(entity, other): """ Find all intersection times between two entities. type(entity) == type(other) == Entity """ # Find relative velocity/acceleration a12 = entity.acceleration - other.acceleration a21 = other.acceleration - entity.acceleration v12 = entity.velocity - other.velocity v21 = other.velocity - entity.velocity entity_points, other_points = entity.points, other.points entity_lines, other_lines = entity.lines, other.lines results = [] # Get all intersections between each object's point and the other object's line for point in entity_points: for line in other_lines: results.append((point, v12, a12, line)) for point in other_points: for line in entity_lines: results.append((point, v21, a21, line)) # Return results of ParabolaLineCollision with each list of arguments in results # Pseudo-code to achieve this (I haven't done the parallizing yet): # return min(map(ParabolaLineCollision, results)) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T10:58:46.833", "Id": "17021", "Score": "0", "body": "How does your entity behave? Instead of calling \"ParabolaLineCollision on each point of each object\" which is very expensive, couldn't you just track the two mass center trajectory and check for an overlapping of the shapes of the two entities?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T16:56:18.827", "Id": "17031", "Score": "0", "body": "This is how I check the overlapping shapes, as this is the shapes of the two entities. I don't have a mass center trajectory. In addition, this is A Priori collision, and this is only done whenever an object's trajectory changes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T17:16:39.630", "Id": "17032", "Score": "0", "body": "There's a particular reason for not having one? It should really speed things up. I don't understand what it has to do if the computation is a priori or not, it's still a computation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T17:44:05.787", "Id": "17033", "Score": "0", "body": "I'm not sure what you're indicating as a way of doing collision. I don't have one because I don't need one. I say it's A priori to indicate that this doesn't happen every frame.\n\nI need to know when the shapes are going to hit each other, so that I can resolve the collision as it occurs (instead of after). I define my objects' shapes as a set of consecutive points. At the time that two consecutive points of an object become collinear with any other objects' point, there is a collision." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T18:39:47.733", "Id": "17035", "Score": "0", "body": "I'm indicating a way of just let those entity be, I'd build some kind of (repulsive) interaction between them to trigger when they'll get near enough. To keep the picture in sync with the physics underneath use different refresh rate. You wouldn't need to pre-compute anything and just let the physics flow. This way you should save you a \"very CPU-intensive function\" :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T20:31:20.530", "Id": "17037", "Score": "0", "body": "I plan on using space partitioning in the long run, and I am also considering using AABB collision detection as a way of knowing when two objects are likely to collide. My current solution allows frames to do nothing but compute position, until a collision occurs, which is a nice efficiency bonus in comparison to post-collision detection." } ]
[ { "body": "<p>Not a lot of changes, but maybe a bit more legible. </p>\n\n<pre><code>a12 = entity.acceleration - other.acceleration\na21 = -a12\nv12 = entity.velocity - other.velocity\nv21 = -v12\n\nresult = [ (p, v12, a12, l) for l in other.lines for p in entity.points ] +\n [ (p, v21, a21, l) for l in entity.lines for p in other.points ]\n</code></pre>\n\n<p>Obviously you could inline the v21 and a21 variables, but it's actually somewhat descriptive of what they represent to use those names.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T20:29:15.240", "Id": "10652", "ParentId": "10650", "Score": "3" } } ]
{ "AcceptedAnswerId": "10652", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T19:40:29.850", "Id": "10650", "Score": "2", "Tags": [ "python" ], "Title": "Logic/Code duplication, improve readability?" }
10650
<p>I've got this transform method with a triple-nested loop. The <code>Generate</code> methods do their own caching so they are fast. <code>K</code> will have a worst-case value of 150. <code>N</code> will have a worst-case value of about 20000. It's that 20000<sup>2</sup> that's killing me. It looks to me like the innermost loop could be moved out, but would you store every possible sum?</p> <pre><code> public static void Transform(IList&lt;float&gt; x, int offset, int sampleRate, int binsPerOctave, double minFrequency, double maxFrequency, out double[] magnitudes, out double maxMagnitude) { var Q = 1.0 / (Math.Pow(2.0, 1.0 / binsPerOctave) - 1.0); var K = (int)Math.Ceiling(Math.Log(maxFrequency / minFrequency, 2.0) * binsPerOctave); magnitudes = new double[K]; var maxN = (int)Math.Round(Q * sampleRate / minFrequency); var halfN = -maxN / 2; double[] wcs = GenerateWindowConstants(maxN); maxMagnitude = double.NegativeInfinity; for(int k = 0; k &lt; K; k++) { var N = (int)Math.Round(Q * sampleRate / (minFrequency * Math.Pow(2.0, (double)k / binsPerOctave))); Complex[] piqs = GeneratePiQConstants(N, Q); var maxMag = double.NegativeInfinity; for(int i = 0; i &lt; N; i++) { Complex sum = new Complex(); for(int n = 0; n &lt; maxN; n++) { var index = n + offset + halfN; index = Math.Min(x.Count - 1, index); index = Math.Max(0, index); sum += (wcs[n] * x[index]) * piqs[(n + i) % N]; } sum /= maxN; maxMag = Math.Max(maxMag, sum.Magnitude); } magnitudes[k] = maxMag; maxMagnitude = Math.Max(maxMagnitude, maxMag); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T19:41:06.977", "Id": "16997", "Score": "6", "body": "What is the aim of this code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T19:49:30.563", "Id": "16998", "Score": "1", "body": "This code is a modified ConstantQ transform -- modified in a way to try all possible phase shifts and use all the data available for higher frequencies." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T19:57:07.743", "Id": "16999", "Score": "0", "body": "How much speedup do you look for? What is the hot path? Have you tried libraries written in C++ that take advantage of platform?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T20:31:41.360", "Id": "17000", "Score": "0", "body": "I'm looking to speed this thing up from hours to minutes. The hotpath is the sum += ... I've thought about trying out the C++ compiler to see if it would give me any significant help. I've also thought about ditching the Complex struct and going with my own math as I know the CLR does a lot better optimization with simple types." } ]
[ { "body": "<p>Note the comment on FFT <a href=\"http://en.wikipedia.org/wiki/Constant_Q_transform#Fast_calculation_using_FFT\" rel=\"nofollow\">here</a>. </p>\n\n<p>(I assume your hot path is <code>sum += (wcs[n] * x[index]) * piqs[(n + i) % N];</code>).</p>\n\n<p>If <code>N</code> is a power of 2, you could use a shift instead of a divide. Have you tried padding up to a power of 2?</p>\n\n<p>Also, are you following the advice in <a href=\"http://www02.lps.ufrj.br/~sergioln/papers/IC26.pdf\" rel=\"nofollow\">this paper</a>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T20:29:29.317", "Id": "17001", "Score": "0", "body": "I definitely need to study that paper more. I'm aware that ConstantQ can be done with FFT. However, ConstantQ differs from my code in that it only has the one nested loop. (eg. replace the 'n' in my code with 'i'.) I haven't dug through the math to see how my current code could utilize the FFT (and I'm not sure my math skills are up to that task)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T19:52:41.290", "Id": "10654", "ParentId": "10653", "Score": "2" } }, { "body": "<p>It looks like based on the 2 inner loops where you are calculating maxMag you could refactor the code to utilize Parallel.ForEach() so you can start to use multiple cores for the math. Just put all of the individual maxMags into a concurrent dictionary. When your done, run your aggregation methods. You'll have to decide whether it is better as an array that gets copied, or whether to refactor them into a concurrent collection type. I hope this helps.</p>\n\n<p><strong>Edit/Update:</strong></p>\n\n<p>Per your comment relating to using all cores \"However, the best improvement this would bring on typical hardware would be 8x. 8x isn't quite going to be enough for my application.\" (found under cgilmeanu's answer)</p>\n\n<p>If utilizing all of the computer resources and taking an <strong>8-fold gain</strong> won't get anywhere close, then ...</p>\n\n<p><strong>Answer = you need to horizontally scale across multiple computers until you reach the point where you are satisfied with the \"timed\" outcome.</strong></p>\n\n<p>Going to c, c++, or .net-under-the-hood should help make gains for you. However, commonly, the programming involved results in something complicated, hard to understand, and more extensive documentation. This can make it tough to be nimble and make changes. Also, if you can assume that the computational load/iterations may increase in the future, your extensive efforts in extremely fine tuning this item may be all for nothing since it was internally just vertical scaling by optimization.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T22:19:53.470", "Id": "10655", "ParentId": "10653", "Score": "3" } }, { "body": "<p>I rewrote the inner most loop using parallel functions. I don't have all necessary classes for running tests on my own, so if you want to try it just let me know the results. Hope this helps.</p>\n\n<p>You could replace the following code</p>\n\n<pre><code>Complex sum = new Complex();\nfor(int n = 0; n &lt; maxN; n++)\n{\n var index = n + offset + halfN;\n index = Math.Min(x.Count - 1, index);\n index = Math.Max(0, index);\n sum += (wcs[n] * x[index]) * piqs[(n + i) % N];\n}\n</code></pre>\n\n<p>with this one</p>\n\n<pre><code>//ReaderWriterLockSlim rwlock = new ReaderWriterLockSlim();\nComplex sum = new Complex();\nobject lockObj = new object(); // this can be put outside the loop, in order not to create it every time the index advance\nParallelOptions options = new ParallelOptions { MaxDegreeOfParallelism = 4 }; // this can be put outside the loop, in order not to create it every time the index advance\nParallel.For(0,\n maxN,\n options,\n () =&gt; 0,\n (int n, ParallelLoopState loopState, Complex threadLocalSum) =&gt; { \n //rwlock.EnterReadLock();\n var index = n + offset + halfN;\n index = Math.Min(x.Count - 1, index);\n index = Math.Max(0, index);\n threadLocalSum += (wcs[n] * x[index]) * piqs[(n + i) % N]);\n //rwlock.ExitReadLock(); \n return threadLocalSum;\n },\n value =&gt; {\n lock (lockObj) { sum += value;}\n }\n );\n</code></pre>\n\n<p>I've also leave the code for ReadWriteLockSlim commented, just to try it if you wish but the performance will suffer if you use it.\nYou can change the MaxDegreeOfParallelism as you think is the best.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T03:44:23.917", "Id": "17038", "Score": "0", "body": "I appreciate the example in parallelism. However, the best improvement this would bring on typical hardware would be 8x. 8x isn't quite going to be enough for my application. I've had to resort to a rethinking on the algorithm." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T10:20:27.677", "Id": "10658", "ParentId": "10653", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T19:39:04.600", "Id": "10653", "Score": "4", "Tags": [ "c#", "performance" ], "Title": "ConstantQ transformation method" }
10653
<p>Our application uses some singletons for localized strings. These calls used to be long and dirty. Therefore some co-worker created extensions for the <code>int</code> and <code>string</code> type to ease the usage of translations.</p> <p>What does the code do: Find a translation string based on the key (the <code>int</code> value). If it cannot be found it falls back to the first provided string. The latter is a <code>params[]</code> string used in underlying <code>string.Format()</code> method as parameters.</p> <pre><code>const var warrantyDescription = "14"; var text = 4426.Translate("Garantietermijn {0} mnd", warrantyDescription); </code></pre> <p>However, I think this approach is bad because:</p> <ul> <li>Bad SoC. <code>Int</code> and <code>string</code> have nothing todo with translations</li> <li>This will result in unreadable and unmaintainable code from the perspective of other developers, encountering a extended int with specific functionality. Imagine a case where not only translations but xx other functionalities extend the int as it is a unique identifier.</li> </ul> <p>Trying to provide him with a better approach, all I could think of was a struct using implicit operators as below. However, I think this casting is bad practise as well..</p> <pre><code>const string warrantyDescription = "14"; var text = ((TranslateId) 4426).Translate( "Garantietermijn {0} mnd", warrantyDescription ); </code></pre> <p>To make this question complete, here is my code for the struct type.</p> <pre><code>public struct TranslateId { private readonly int m_Value; public TranslateId (int value) { m_Value = value; } public int Value { get { return m_Value; } } public string Translate(string defaultString, params object[] parameters) { // TODO: Use the actual singleton to retrieve translation string translationResult = defaultString; // Return the formatted retrieved value return string.Format(translationResult, parameters); } public static implicit operator TranslateId(int value) { return new TranslateId(value); } public static implicit operator int(TranslateId id) { return id.Value; } } </code></pre> <p>Any thoughts?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T12:48:40.317", "Id": "17027", "Score": "5", "body": "Why don't you use the built-in localization using resources? Something like `string.Format(Localization.WarrantyLength, warrantyDescription)` (where `Localization` is the resource class) seems much cleaner to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T13:02:34.037", "Id": "17151", "Score": "0", "body": "@svick you could have posted that as an answer. But my point is: maybe he has hundreds of resources to translate, like I do. :( `Localization.WarrantyLength` looks good in principle, but creating and maintaining resources with 500-700 translation strings in 6 langs (en fr es ru ar zh) sounds hellish. I can't really see a good workflow to get the translations to the translators, and then back into the code. Is it XML-based? Perhaps a converter script. Hopefully the process is simpler than I can think of." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T13:04:31.740", "Id": "17152", "Score": "0", "body": "@Aphelion What are the ints? Just random, irrelevant to the translation? Or do they add context? Are they language ids, object ids, anything?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T13:31:45.357", "Id": "17153", "Score": "0", "body": "@ANeves, yes, the resources are XML based, so it shouldn't be a problem to get them to translators, I think. I have never done it in practice, though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T07:03:02.030", "Id": "17190", "Score": "0", "body": "@ANeves they ints are Pkeys known in our Translation Management application (and the underlying datasources). We currently have about 9k of translations (over 3 languages). They already are undoubled and splitted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T07:04:11.357", "Id": "17191", "Score": "0", "body": "Also interesting is that the singleton that gives the translation depends on a lot of internal variables. We have about 4 cultures active, not juist a UI and code culture." } ]
[ { "body": "<p>This is a <strong>horrible</strong> misuse of extension methods. The only thing worse (and I'm sure you'll see it) is <code>(n+5).Translate(...)</code>. You're absolutely correct - the starting point for the mistake is in thinking of the integer as the base object for the translation. There are a number of well-understood patterns for handling localization, and this isn't any of them. Since we're talking C#, there's the obvious resource technique, but there are others as well. The GNU Project pioneered the <code>_(\"blah blah blah\")</code> mechanism, where the default string serves as a key in a locale-specific table of replacements (along with the Windows OS and MS Office, this is one of the most prevalent and successful translation systems). And then there's the tried-and-true dictionary-indexed-by-a-named-constant (often an <code>enum</code> member), often encapsulated behind a <code>Language</code> class with a <code>Translate(...)</code> method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T07:05:39.907", "Id": "17192", "Score": "0", "body": "This is indeed a good strategy in case the strings are unique. However, the kind of translations we use cause duplicates in the key language (english) as translations to for example dutch and french use other words or grammar. We cannot use the English text as a key to the translations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T14:56:22.680", "Id": "17209", "Score": "0", "body": "@Aphelion That's just one of the reasons why I prefer the named-constant approach. Another is a sneaking suspicion that, when the key is the default language, there are a lot of untranslated strings lurking in the product that will leak out to your users. When the key is Klingon or Esperanto, not so much :-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T01:28:32.593", "Id": "10695", "ParentId": "10659", "Score": "5" } }, { "body": "<p>One unobtrusive method might be to introduce a class called \"OutputString\" or \"TranslatedString\" and use it in presentation with explicit conversion from string. </p>\n\n<p>The service then can translate the string using language id and string itself as key.</p>\n\n<pre><code>public class OutputString {\n public static explicit operator OutputString(string b) \n {\n return new OutputString(b);\n }\n\n private readonly string innerString;\n public OutputString(string innerString) \n {\n this.innerString = innerString;\n }\n\n public override string ToString() \n {\n LongAndDirtyTranslationClass.EvenLongerAndDirtierMethod(this.innerString)\n }\n}\n</code></pre>\n\n<p>To use;</p>\n\n<pre><code>public class ShowProfileViewModel \n{\n public string Name { get; set; }\n public OutputString Ranking { get; set; }\n}\n\npublic class ProfileController \n{\n // ...\n public ActionResult Details(int id) \n {\n var profile = new ShowProfileViewModel {\n Name = this.someService.getName(id),\n Ranking = this.someOtherService.getRanking(id) //returns string\n };\n\n return View(profile);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:38:00.410", "Id": "17082", "Score": "0", "body": "This is a pretty common and decent answer to the problem. Personally, I much prefer having the key be a named constant or enum instrad of the untranslated string, because that makes it a first-class object that the IDE can help you with. But as long as *every* input string is passed through translation, rather than having it be the default output (_a.k.a._, the \"English is our default language\" scenario), it works well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T09:42:04.647", "Id": "10701", "ParentId": "10659", "Score": "4" } } ]
{ "AcceptedAnswerId": "10695", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T11:47:50.273", "Id": "10659", "Score": "4", "Tags": [ "c#", "localization" ], "Title": "Extension methods for translation engine" }
10659
<p>I'm just getting my feet wet with F#, by implementing some simple algorithms. First up: Djikstras shortest path.</p> <p>There is one piece I've written in this code which confuses me as to why it works: the <code>contains</code> function. As I understand it, <code>List.isEmpty</code> returns true when a list is empty; but in this case, I would want to see the opposite of that. However, <code>not(List.isEmpty)</code> appeared to give the opposite of what I was expecting: it still returned true on a list being empty. <strong>Why is this the case? Or am I just missing something obvious?</strong></p> <p>As for the full code listing: have I done anything massively wrong?</p> <pre><code>open System; open System.Collections; open System.Collections.Generic; open System.IO; type Node(id: int, neighbours:list&lt;(int*int)&gt;) = let mutable _ID = id let mutable _neighbours:list&lt;(int * int)&gt; = neighbours member this.ID with get() = _ID and set(value) = _ID &lt;- value member this.AddNeighbour(id:int, distance:int) = let t:(int*int) = (id, distance) _neighbours &lt;- _neighbours @ [t] member this.Neighbours with get() = _neighbours and set(value) = _neighbours &lt;- value; let nodes:list&lt;Node&gt; = [new Node(1, [(2, 3); (3, 3); (4, 1)]); new Node(2, [(3, 1)]); new Node(3, [(1, 3); (2, 1); (4, 10)]); new Node(4, [(1, 1); (3, 10)]) ]; let rec remove_first pred lst = match lst with | h::t when pred h -&gt; t | h::t -&gt; h::remove_first pred t | _ -&gt; []; let contains (item:'a) (lst:list&lt;'a&gt;) : bool = let filtered = List.filter (fun I -&gt; I = item) lst; List.isEmpty(filtered); let rec Traverse (data:list&lt;Node&gt;, start:int, visited:list&lt;int&gt;):list&lt;int&gt; = let startNode = List.find (fun (E:Node) -&gt; E.ID = start) data //Get the starting node let newData = remove_first (fun (E:Node) -&gt; E.ID = startNode.ID) data //Get the new data by removing the start node from the current data let newVisited = visited@[startNode.ID] let neighbourSet = List.filter (fun (i,_) -&gt; contains i newVisited) startNode.Neighbours //Use only the neighbours that aren't visisted if(List.isEmpty neighbourSet) then newVisited; else neighbourSet |&gt; List.minBy (fun (_,d:int) -&gt; d) //Get neighbour with smallest distance |&gt; fun (i, d) -&gt; Traverse(newData, i, newVisited); //Recurse in to the traverse function, starting at the smallest neighbour let result = Traverse (nodes, 1, []); let writeList (lst:list&lt;'a&gt;):string = let mutable output = ""; for I in lst do output &lt;- String.Concat(output, I); output; let path = "Output.txt"; File.WriteAllText(path , writeList(result)); </code></pre>
[]
[ { "body": "<p>Matthew Podwysocki wrote a nice <a href=\"http://codebetter.com/matthewpodwysocki/2009/04/21/functional-solution-for-the-shortest-path-problem/\">functional solution</a> for this on his blog a few years ago:</p>\n\n\n\n<pre><code>module Map =\n let transposeCombine m =\n (m, m) ||&gt; Map.fold (fun acc k1 m' -&gt;\n (acc, m') ||&gt; Map.fold (fun acc' k2 v -&gt;\n acc'\n |&gt; Map.add k2 (Map.add k1 v (defaultArg (acc' |&gt; Map.tryFind k2) Map.empty))\n ))\n\ntype City =\n | Boise | LosAngeles | NewYork | Seattle\n | StLouis | Phoenix | Boston | Chicago\n | Denver\n\nlet distanceBetweenCities =\n Map.ofList\n [\n (Boise, Map.ofList [(Seattle, 496);(Denver, 830);(Chicago, 1702)]);\n (Seattle, Map.ofList [(LosAngeles, 1141);(Denver, 1321)]);\n (LosAngeles, Map.ofList [(Denver, 1022);(Phoenix, 371)]);\n (Phoenix, Map.ofList [(Denver, 809);(StLouis, 1504)]);\n (Denver, Map.ofList [(StLouis, 588);(Chicago, 1009)]);\n (Chicago, Map.ofList [(NewYork, 811);(Boston, 986)]);\n (StLouis, Map.ofList [(Chicago, 300)]);\n (Boston, Map.ofList [(StLouis, 986)]);\n (NewYork, Map.ofList [(Boston, 211)])\n ]\n |&gt; Map.transposeCombine\n\nlet shortestPathBetween startCity endCity =\n let rec searchForShortestPath currentCity distanceSoFar citiesVisitedSoFar accMap =\n let visitDestinations m =\n (m, distanceBetweenCities.[currentCity])\n ||&gt; Map.fold\n (fun acc city distance -&gt;\n searchForShortestPath city (distance + distanceSoFar) (citiesVisitedSoFar @ [city]) acc)\n\n match Map.tryFind currentCity accMap with\n | None -&gt; accMap |&gt; Map.add currentCity (distanceSoFar, citiesVisitedSoFar) |&gt; visitDestinations\n | Some x -&gt;\n let (shortestKnownPath, _) = x\n if distanceSoFar &lt; shortestKnownPath then\n accMap |&gt; Map.add currentCity (distanceSoFar, citiesVisitedSoFar) |&gt; visitDestinations\n else accMap\n\n let shortestPaths = searchForShortestPath startCity 0 [] Map.empty\n shortestPaths.[endCity]\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>shortestPathBetween LosAngeles NewYork //(2721, [Denver; StLouis; Chicago; NewYork])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T14:39:44.697", "Id": "10725", "ParentId": "10663", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T18:37:39.233", "Id": "10663", "Score": "7", "Tags": [ "algorithm", "functional-programming", "f#", "beginner" ], "Title": "F# Djikstras shortest path implementation" }
10663
<p>I am contemplating working with a development firm, and had asked for this piece of sample code. Could you please take a look and let me know if this is a quality piece of work, or if it needs improvement?</p> <pre><code>// textures pvr -(void)startWaitAnimation { if(![self numberOfRunningActions] &amp;&amp; self.visible) { [super startWaitAnimation]; [[CCTextureCache sharedTextureCache] addImageAsync:@"lion_wait2.pvr.ccz" target:self selector:@selector(_startWaitAnimation)]; } } -(void)_startWaitAnimation { CCTexture2D *texture = [[CCTextureCache sharedTextureCache] textureForKey:@"lion_wait2.pvr.ccz"]; [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"lion_wait2.plist" texture:texture]; NSMutableArray *waitFrames = [NSMutableArray array]; for(int i = 1; i &lt;= 19; i++) { i = ( i%2 == 0 &amp;&amp; i!=19 ) ? i+1 : i; [waitFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"lev_wait2%04d.png", i]]]; } CCAnimation *waitAnimation = [CCAnimation animationWithFrames:waitFrames delay:kWaitAnimationTime*2]; CCAnimate *tempWaitAction = [CCAnimate actionWithAnimation:waitAnimation restoreOriginalFrame:YES] ; CCRepeat *re = [CCRepeat actionWithAction:tempWaitAction times:2]; CCSequence *seq = [CCSequence actions:re,[CCCallFunc actionWithTarget:self selector:@selector(releaseWaitFrames)], nil]; [self runAction:seq]; //CCRepeatForever *repeat = [CCRepeatForever actionWithAction: [CCAnimate actionWithAnimation:animation restoreOriginalFrame:NO]] } -(void)releaseWaitFrames { [[CCSpriteFrameCache sharedSpriteFrameCache] removeSpriteFramesFromFile:@"lion_wait2.plist"]; [[CCTextureCache sharedTextureCache] removeTextureForKey:@"lion_wait2.pvr.ccz"]; [self setDisplayFrame:animal]; } //particles -(void)firHeaded { CGSize s = [[CCDirector sharedDirector] winSize]; CCTexture2D *fir_texture = [[CCTextureCache sharedTextureCache] addImage:@"fir_glow.png"]; self.fir.texture = fir_texture; for (CCParticleSystem *p in effects) { [p removeFromParentAndCleanup:YES]; } [effects release]; effects = [[NSMutableArray alloc] init]; for (int y = 60; y &lt; 900; y+=20) { CGFloat x1 = [FirToyView fy1:s.height - y]; CGFloat x2 = [FirToyView fy2:s.height - y]; CCParticleSystem *particle = [self getStars:CGRectMake(x1, y, x2-x1 , 20 )]; [effects addObject:particle]; [self addChild:particle]; } if(!isTextEnabled) { textBtn.isEnabled = YES; isTextEnabled = YES; } [[AudioEngine sharedEngine] playEffect:kSoundCool]; //[[AudioEngine sharedEngine] playEffect:kSoundMenuClick]; } -(CCParticleSystem*)getStars:(CGRect)rect { float mul = (rect.size.width * rect.size.height) / 11815.0f; int maxcount = roundf( mul*10 ); CCParticleSystem *particle=[[[CCParticleSystemQuad alloc] initWithTotalParticles:96] autorelease]; CCTexture2D *texture=[[CCTextureCache sharedTextureCache] addImage:@"stars_t.png"]; particle.texture=texture; particle.emissionRate=19.20; particle.angle=210.0; particle.angleVar=30.0; ccBlendFunc blendFunc={GL_SRC_ALPHA,GL_ONE}; particle.blendFunc=blendFunc; particle.duration=-1.00; particle.emitterMode=kCCParticleModeGravity; ccColor4F startColor={1.00,0.75,0.23,1.00}; particle.startColor=startColor; ccColor4F startColorVar={0.15,0.00,0.00,0.44}; particle.startColorVar=startColorVar; ccColor4F endColor={0.98,1.00,0.82,1.00}; particle.endColor=endColor; ccColor4F endColorVar={0.11,0.12,0.12,0.18}; particle.endColorVar=endColorVar; particle.startSize=15.00; particle.startSizeVar=5.00; particle.endSize=20.00; particle.endSizeVar=5.00; particle.gravity=ccp(0.00,0.00); particle.radialAccel=0.00; particle.radialAccelVar=0.00; particle.speed= 0; particle.speedVar= 0; particle.tangentialAccel= 0; particle.tangentialAccelVar= 0; particle.totalParticles = maxcount; particle.life=0.50; particle.lifeVar=3.00; particle.startSpin=0.00; particle.startSpinVar=0.00; particle.endSpin=0.00; particle.endSpinVar=0.00; particle.position=ccp(rect.origin.x + rect.size.width/2, rect.origin.y + rect.size.height/2); particle.posVar=ccp(rect.size.width/2,rect.size.height/2); return particle; } //animations -(void)rectoreWorm:(CGPoint)location { touchOffset = 0.0; float distance = -rod.position.y; NSLog(@"Pos %f - %f",worm.position.y,worm.position.y + touchOffset); float mul = (distance &gt; 0)? 1 + (distance / 768) * 2 : 1 + (-distance / 768) *2; NSLog(@"mul = %f, distance %f ",mul, distance); CGPoint pos1 = CGPointMake(rodHomePosition.x, rodHomePosition.y + distance/3 ); CCSequence *action = [CCSequence actions:[CCMoveTo actionWithDuration:0.2*mul position:pos1],[CCMoveTo actionWithDuration:0.1*mul position:rodHomePosition], nil]; [rod runAction:action]; CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage:@"worm.png"]; CCSpriteFrame *frame = [CCSpriteFrame frameWithTexture:texture rect:worm.textureRect]; [worm setDisplayFrame:frame]; //ccDrawPoint(wormHomePosition); if(distanse &gt; 240 ) { [delegate changeLevel]; [[AudioEngine sharedEngine] playEffect:kUpSound]; } } //rotation with finger -(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event { CGPoint firstLocation = [touch previousLocationInView:[touch view]]; CGPoint location = [touch locationInView:[touch view]]; CGPoint touchingPoint = [[CCDirector sharedDirector] convertToGL:location]; CGPoint firstTouchingPoint = [[CCDirector sharedDirector] convertToGL:firstLocation]; CGPoint firstVector = ccpSub(firstTouchingPoint, wheel.position); CGFloat firstRotateAngle = -ccpToAngle(firstVector); CGFloat previousTouch = CC_RADIANS_TO_DEGREES(firstRotateAngle); CGPoint vector = ccpSub(touchingPoint, wheel.position); CGFloat rotateAngle = -ccpToAngle(vector); CGFloat currentTouch = CC_RADIANS_TO_DEGREES(rotateAngle); CGFloat diff = currentTouch - previousTouch; CGFloat rotation = wheel.rotation + currentTouch - previousTouch; if(rotation &gt; 180) { int normal = (int) ( rotation / 360 ); rotation -= normal*360; rotation -= 360; } else if( rotation &lt; -180 ) { int normal = (int) ( rotation / 360 ); rotation -= normal*360; rotation += 360; } wheel.rotation = rotation; NSLog(@"ANGLE %f - %d | diff %f",wheel.rotation,normal,diff); float delta = wheelStartAngle - wheel.rotation; delta = (delta &gt; 0) ? delta : -delta; if(delta &gt; 5 &amp;&amp; !isWheelSoundPalyed) { [[AudioEngine sharedEngine] playEffect:kWhellSound]; isWheelSoundPalyed = YES; } } //sqlite3 native -(DSSurvey*)getSyrvey:(NSInteger)survey_id { const char *sql = "SELECT id, title, date, template FROM surveys WHERE id=? LIMIT 1"; sqlite3_stmt *statement; DSSurvey *survey = [[DSSurvey alloc] init]; if (sqlite3_prepare_v2(database, sql, -1, &amp;statement, NULL) == SQLITE_OK) { int iId = sqlite3_bind_int(statement, 1, survey_id); while (sqlite3_step(statement) == SQLITE_ROW) { int primaryKey = sqlite3_column_int(statement,0); const unsigned char *title = sqlite3_column_text(statement, 1); const unsigned char *date = sqlite3_column_text(statement, 2); const unsigned char *templ = sqlite3_column_text(statement, 3); survey._id = primaryKey; survey.title = (title) ? [NSString stringWithUTF8String:title] : @""; survey.date = (date) ? [NSString stringWithUTF8String: date] : @""; survey._template = (templ) ? [NSString stringWithUTF8String: templ] : @""; } } sqlite3_finalize(statement); return (survey._id) ? [survey retain] : nil; } //sqlite3 fmdb -(void)setAnswer:(DMAnswer*)answer forTest:(DMTest*)test withQuestion:(DMQuestion*)question; { [db executeUpdate:@"INSERT OR REPLACE INTO tests_answers (id, course_id, theme_id, question_id, answer_id, is_right ,date) VALUES ( (SELECT id FROM tests_answers WHERE question_id = ?), ?, ?, ?, ?, ?, ?)" , [NSNumber numberWithInt:question.quetionId], [NSNumber numberWithInt: self.currentCourseId], [NSNumber numberWithInt:test.themeId] , [NSNumber numberWithInt:question.quetionId], [NSNumber numberWithInt:answer.answerId], [NSNumber numberWithBool:answer.isRight], [NSDate date]]; } //image processing - (UIImage *)getRoundedCornerImageWithGlareEffect:(NSInteger)cornerSize borderSize:(NSInteger)borderSize { // If the image does not have an alpha layer, add one UIImage *image = [self imageWithAlpha]; NSLog(@"%f,%f bits %lu",image.size.width,image.size.height,CGImageGetBitsPerComponent(image.CGImage)); // Build a context that's the same dimensions as the new size CGContextRef context = CGBitmapContextCreate(NULL, image.size.width, image.size.height, CGImageGetBitsPerComponent(image.CGImage), 0, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedFirst); // Create a clipping path with rounded corners CGContextBeginPath(context); [self addRoundedRectToPath:CGRectMake(borderSize, borderSize, image.size.width - borderSize * 2, image.size.height - borderSize * 2) context:context ovalWidth:cornerSize ovalHeight:cornerSize]; CGContextClosePath(context); CGContextClip(context); // Draw the image to the context; the clipping path will make anything outside the rounded rect transparent UIImage *glare = [UIImage imageNamed:@"glare.png"]; CGContextDrawImage(context, CGRectMake(0, 0, image.size.width, image.size.height), image.CGImage); CGContextDrawImage(context, CGRectMake(0, 0, glare.CGImage, glare.CGImage), glare.CGImage); // Create a CGImage from the context CGImageRef clippedImage = CGBitmapContextCreateImage(context); CGContextRelease(context); // Create a UIImage from the CGImage UIImage *roundedImage = [UIImage imageWithCGImage:clippedImage]; CGImageRelease(clippedImage); return roundedImage; } -(void)getCard:(SEL)callback { //flashView.alpha = 1.0f; [[SimpleAudioEngine sharedEngine] playEffect:kSoundCamera]; [[CCDirector sharedDirector].openGLView addSubview:flashView]; [self hideMenu]; [UIView animateWithDuration:0.03 delay: 0.0 options: UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionBeginFromCurrentState animations:^{ flashView.alpha = 1.0f; } completion:^(BOOL finished){ CGSize s = [[CCDirector sharedDirector] winSize]; UIImage *img2 =[self screenhot]; //UIImage *img3 =[UIImage imageNamed:@"frame.png"]; UIGraphicsBeginImageContext(s); [img2 drawInRect:CGRectMake(0,0,s.width,s.height)]; [transitView.layer renderInContext:UIGraphicsGetCurrentContext()]; //[img3 drawInRect:CGRectMake(0,0,s.width,s.height)]; self.snapshoot = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); [self showMenu]; [UIView animateWithDuration:0.5 delay: 0.0 options: UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionBeginFromCurrentState animations:^{ flashView.alpha = 0.0f; } completion:^(BOOL finished){ [flashView removeFromSuperview]; [self performSelector:callback]; }]; }]; } </code></pre>
[]
[ { "body": "<p>I observe that:</p>\n\n<ol>\n<li>Only one function has any comments</li>\n<li>There is a fair amount of commented out code</li>\n<li>The variable names aren't very helpful</li>\n<li>Somethings are just misspelled: <code>getSyrvey</code>, <code>rectoreWorm</code></li>\n<li>The code seems to mix various things together (drawing/particle system/database access)</li>\n</ol>\n\n<p>There is also this nugget:</p>\n\n<pre><code> for(int i = 1; i &lt;= 19; i++) {\n\n i = ( i%2 == 0 &amp;&amp; i!=19 ) ? i+1 : i;\n [waitFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@\"lev_wait2%04d.png\", i]]];\n\n }\n</code></pre>\n\n<p>Have fun figuring out the logic for <code>i</code> in that loop. </p>\n\n<p>Keep in mind its easy to go through code and find things to complain about. I'm probably guilty of much of the same stuff in my iOS code. (I blame objective-C, but that's another matter). But certainly, there are things that could use improvement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T01:03:13.920", "Id": "10668", "ParentId": "10665", "Score": "12" } }, { "body": "<pre><code>for(int i = 1; i &lt;= 19; i++) {\n\n i = ( i%2 == 0 &amp;&amp; i!=19 ) ? i+1 : i;\n [waitFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] \n spriteFrameByName:[NSString stringWithFormat:@\"lev_wait2%04d.png\", i]]];\n\n}\n</code></pre>\n\n<p>Holy Toledo.</p>\n\n<p>First of all, if you must update the iterator within a <code>for</code> loop, let's leave the update statement empty:</p>\n\n<pre><code>for (int i = 1; i &lt;= 19; /*updated within loop*/) {\n</code></pre>\n\n<p>As written, your loop misleadingly suggests we'll go from 1 to 19, run 19 times exactly, in order, and that's it. Then we sometimes increment in the loop...</p>\n\n<p>But even that's not necessary. Honestly, all your ternary operator seems to be doing is ensuring that <code>i</code> is an odd number. There's a much better way to do this:</p>\n\n<pre><code>for (int i = 1; i &lt;= 19; i += 2) {\n</code></pre>\n\n<p>Now we're incrementing by two on each loop. The end result is identical (<em>almost</em>). The readability is a million times better. The ternary is completely removed. </p>\n\n<p>(Technically, the end result is better because now we'll add 2 instead of adding 1 and then adding 1 again.)</p>\n\n<p>Now, there's something else important to note. In the body of that loop, all this nesting just hampers the readability. Unnesting these method calls doesn't negatively impact performance.</p>\n\n<p>So the final form of the loop should look something more like this:</p>\n\n<pre><code>for (int i = 1; i &lt;= 19; i += 2) {\n NSString *spriteName = [NSString stringWithFormat:@\"lev_wait2%04d.png\",i];\n CCSpriteFrameCache *cache = [CCSpriteFrameCache sharedSpriteFrameCache];\n\n [waitFrames addObject:cache spriteFrameByName:spriteName];\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-19T17:46:17.790", "Id": "57466", "ParentId": "10665", "Score": "15" } }, { "body": "<pre><code>[UIView animateWithDuration:0.03\n delay: 0.0\n options: UIViewAnimationOptionCurveEaseIn | \n UIViewAnimationOptionBeginFromCurrentState\n animations:^{\n flashView.alpha = 1.0f;\n } completion:^(BOOL finished){\n CGSize s = [[CCDirector sharedDirector] winSize];\n UIImage *img2 =[self screenhot];\n\n UIGraphicsBeginImageContext(s);\n [img2 drawInRect:CGRectMake(0,0,s.width,s.height)];\n [transitView.layer renderInContext:UIGraphicsGetCurrentContext()];\n\n self.snapshoot = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n [self showMenu];\n\n [UIView animateWithDuration:0.5\n delay: 0.0\n options: UIViewAnimationOptionCurveEaseIn | \n UIViewAnimationOptionBeginFromCurrentState\n animations:^{\n flashView.alpha = 0.0f;\n } completion:^(BOOL finished){\n [flashView removeFromSuperview];\n [self performSelector:callback];\n }]; \n }]; \n</code></pre>\n\n<p>This is an absolute mess, which I've already cleaned up slightly for the sake of the readability of my own answer...</p>\n\n<p>The core problem with this is the fact that within a method, we're calling a method which takes two blocks as arguments, and within one of those blocks, we're calling another method which takes two blocks as arguments. We want to indent to keep things readable, but by the time we indent enough for the deepest nested blocks, we type two letters and get word-wrapped or go off the edge! Now I realize that we'd be coding on an edit area much wider than what code review offers, so you'd have more space, but we should still avoid nesting so deeply.</p>\n\n<p>In this case, there's actually a pretty simple solutions. The inner <code>animateWithDuration</code> call has a single purpose, and that is to undo the animation that was done in the first block. Rather than nest this, we can just use the <code>delay</code> argument, unnest, and give the formerly inner block a delay that is equivalent to the other animation's <code>duration</code>.</p>\n\n<p>But we can still keep these nested without being so ugly if we want. We just need to know a little bit more about Objective-C code blocks.</p>\n\n<p>There are two types of code blocks in this snippet.</p>\n\n<p>The first kind is the <code>animate</code> block, which takes no arguments and returns no values.</p>\n\n<p>The second kind is the <code>completion</code> block, which takes a <code>BOOL</code> value (indicating whether or not the animation actually animated) and returns no value.</p>\n\n<p>We can create variables to hold references to block (just as the method this code resides in takes a <code>SEL</code> argument (a reference to a selector).</p>\n\n<p>First, let's create the animation blocks, as they're simple. It looks something like this:</p>\n\n<pre><code>void (^showFlashView)(void) = ^{\n flashView.alpha = 1.0f;\n}\n\nvoid (^hideFlashView)(void) = ^{\n flashView.alpha = 0.0f;\n}\n</code></pre>\n\n<p>Simple, right?</p>\n\n<p>The <code>completion</code> blocks which take a <code>BOOL</code> argument are only slightly more complex:</p>\n\n<pre><code>void (^lastCompletionBlock)(BOOL) = ^(BOOL finished) {\n [flashView removeFromSuperview];\n [self performSelector:callback];\n}\n</code></pre>\n\n<p>We have to create the last one first, because the first one needs the last one:</p>\n\n<pre><code>void (^firstCompletionBlock)(BOOL) = ^(BOOL finished) {\n CGSize s = [[CCDirector sharedDirector] winSize];\n UIImage *img2 = [self screenhot];\n\n UIGraphicsBeginImageContext(s);\n [img2 drawInRect:CGRectMake(0,0,s.width,s.height)];\n [transitView.layer renderInContext:UIGraphicsGetCurrentContext()];\n\n self.snapshoot = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n [self showMenu];\n\n [UIView animateWithDuration:0.5\n delay:0.0\n options:UIViewAnimationOptionCurveEaseIn |\n UIViewAnimationOptionBeginFromCurrentState\n animations:hideFlashView\n completion:lastCompletionBlock];\n}\n</code></pre>\n\n<p>And now that we've defined our blocks, our actual code looks like this:</p>\n\n<pre><code>[UIView animateWithDuration:0.03\n delay:0.0\n options:UIViewAnimationOptionCurveEaseIn | \n UIViewAnimationOptionBeginFromCurrentState\n animations:showFlashView\n completion:firstCompletionBlock];\n</code></pre>\n\n<p>The total number of lines of code is very slightly increased, however the readability is drastically improved.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-19T20:13:39.760", "Id": "57475", "ParentId": "10665", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T21:52:57.930", "Id": "10665", "Score": "15", "Tags": [ "objective-c", "interview-questions", "ios", "animation", "sqlite" ], "Title": "Sample game code for applying to a development firm" }
10665
<p>I'm new to coffeescripts. Can the <code>getSum</code> method be simplified more? Thanks</p> <pre><code>MyObject = checkCondition: (num) -&gt; return true if num is 5 getSum: (num) -&gt; total = 0 total += i for i in [1..num] when @checkCondition i total </code></pre> <p>I tried removing the last total but coffeescripts compiler goes nut :-/</p> <p>Any help greatly appreciate.</p>
[]
[ { "body": "<p>It's not clear what you're trying to achieve here. </p>\n\n<p>The <code>getSum</code> method looks fine. The <code>checkCondition</code> is overcomplicated: it better be <code>checkCondition: (num) -&gt; num is 5</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T20:04:59.893", "Id": "17039", "Score": "0", "body": "actually the checkCondition code was a long one but it is not important here.. I just want to know if it is possible to further simplify `getSum` to one line?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T19:37:21.170", "Id": "10678", "ParentId": "10677", "Score": "0" } }, { "body": "<p>First, <code>return true if num is 5</code> is the same as just <code>num is 5</code>.<br>\nThen, you can convert the explicit loop into a <code>reduce</code> (you can read about it in <a href=\"http://en.wikipedia.org/wiki/Fold_%28higher-order_function%29\">Wikipedia</a> or <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Reduce\">MDN</a>): </p>\n\n<pre><code>MyObject =\n checkCondition: (num) -&gt; num is 5\n\n getSum: (num) -&gt;\n [0..num].reduce (x,y) =&gt;\n if @checkCondition y then x + y else x\n</code></pre>\n\n<p>Note <code>=&gt;</code> instead of plain <code>-&gt;</code> after <code>(x,y)</code>. This is <a href=\"http://coffeescript.org/#fat_arrow\">fat arrow</a>, it prevents the capture of <code>@</code> the inside function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T16:06:31.803", "Id": "17049", "Score": "2", "body": "Using `reduce` is definitely the most elegant approach, but note that it's not supported in older browsers. You can either add it to the `Array` prototype yourself, or use the excellent [Underscore.js](http://documentcloud.github.com/underscore/) library." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T19:44:44.483", "Id": "10679", "ParentId": "10677", "Score": "11" } }, { "body": "<p>As written getSum will only ever return 0 or 5, but I assume this checkCondition is merely an example, so here is my answer:</p>\n\n<pre><code>MyObject =\n checkCondition: (num) -&gt; num is 5\n\n getSum: (num) -&gt;\n total = (i for i in [1..num] when @checkCondition i).reduce ((x, y) -&gt; x + y), 0\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T08:05:34.780", "Id": "17040", "Score": "0", "body": "That is one liner even I don't understand how reduce works" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T07:21:49.003", "Id": "18725", "Score": "0", "body": "nice implementation" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T00:46:33.467", "Id": "10680", "ParentId": "10677", "Score": "1" } } ]
{ "AcceptedAnswerId": "10679", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T19:11:27.627", "Id": "10677", "Score": "3", "Tags": [ "coffeescript" ], "Title": "Can this coffeescripts method be simplified?" }
10677
<p>I have a java function that reads a csv and returns its content as a <code>Vector&lt;Vector&lt;String&gt;&gt;</code>.</p> <p>The function seems to work as I need it, but my gut feeling says it could be better (never mind the fact that it is declared <code>throws Exception</code>).</p> <p>So here it is:</p> <pre><code>private static Vector&lt;Vector&lt;String&gt;&gt; readTXTFile(String csvFileName) throws Exception { BufferedReader stream = new BufferedReader( new InputStreamReader( new FileInputStream(csvFileName))); Vector&lt;Vector&lt;String&gt;&gt; csvData = new Vector&lt;Vector&lt;String&gt;&gt;(); String line; while ((line = stream.readLine()) != null) { csvData.add(new Vector&lt;String&gt;() ); String[] values = line.split(","); for (int v=0; v&lt;values.length; v++) { csvData.get(csvData.size()-1).add(values[v]); } } return csvData; } </code></pre> <h2>Background</h2> <p>Ultimately, the CSV Data will be used to fill a <a href="http://docs.oracle.com/javase/6/docs/api/javax/swing/JTable.html">JTable</a>. I could have used an <code>String[][]</code> for the data too, but it seemed that constructing a dynamic <code>String[][]</code> from a csv file would have been even more combersome (although I stand ready to be corrected on this, too).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T01:58:40.320", "Id": "58731", "Score": "0", "body": "Something like Óscar López said, don't use concrete class for method return.And Vector will cause performance hit." } ]
[ { "body": "<p>There's a constructor for <code>Vector</code> that takes any <code>Collection</code> as its argument. So you could write</p>\n\n<pre><code>String[] values = line.split(\",\"); \ncsvData.add( new Vector&lt;String&gt;( Arrays.asList( values ))); \n</code></pre>\n\n<p>instead of writing your own loop to iterate <code>values</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T15:00:08.360", "Id": "17048", "Score": "0", "body": "That's short and nice, but `Arrays.asList` will create an intermediate list which gets discarded immediately. Not very efficient regarding memory use" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-07T11:28:00.817", "Id": "19832", "Score": "0", "body": "@ÓscarLópez `Arrays.asList` returns a wrapper around the original array with O(1) space." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T08:18:17.790", "Id": "10682", "ParentId": "10681", "Score": "5" } }, { "body": "<ul>\n<li><p>Don't just throw an <code>Exception</code> either</p>\n\n<ul>\n<li>handle the errors</li>\n<li>throw specific exceptions so that they can be handled in the right way later</li>\n<li>throw a <code>RuntimeException</code> that will not be catches (<code>throw new RuntimeException(catchedException);</code>)</li>\n</ul></li>\n<li><p>close all the streams you use</p></li>\n<li><p>you don't need to <code>get</code> the Vector you just added: just keep a reference</p></li>\n<li><p>you can directly iterate over the splitted line</p></li>\n</ul>\n\n<p>Here an example without error handling:</p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.Vector;\n\npublic class Test {\n\n @SuppressWarnings(\"unused\")\n private static Vector&lt;Vector&lt;String&gt;&gt; readTXTFile(String csvFileName) {\n\n FileInputStream fileInputStream = null;\n InputStreamReader inputStreamReader = null;\n BufferedReader stream = null;\n\n Vector&lt;Vector&lt;String&gt;&gt; csvData = null;\n\n try {\n\n try {\n\n fileInputStream = new FileInputStream(csvFileName);\n inputStreamReader = new InputStreamReader(fileInputStream);\n stream = new BufferedReader(inputStreamReader);\n\n csvData = new Vector&lt;Vector&lt;String&gt;&gt;();\n\n String line;\n while ((line = stream.readLine()) != null) {\n\n Vector&lt;String&gt; vector = new Vector&lt;String&gt;();\n\n csvData.add(vector );\n\n for (String value : line.split(\", \")) {\n vector.add(value);\n }\n\n }\n\n } finally {\n if (stream != null) {\n stream.close();\n }\n if (inputStreamReader != null) {\n inputStreamReader.close();\n }\n if (fileInputStream != null) {\n fileInputStream.close();\n } \n\n }\n\n } catch (IOException ioException) {\n throw new RuntimeException(ioException);\n }\n\n return csvData;\n\n}\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T09:53:42.863", "Id": "10683", "ParentId": "10681", "Score": "2" } }, { "body": "<p>There are frameworks that allow you to read from a CSV file and configure the record structure into one XML configuration file and will parse files for you.\nYou can use:</p>\n\n<ul>\n<li>FFP - Flat file parsing library <a href=\"http://jffp.sourceforge.net/\">http://jffp.sourceforge.net/</a></li>\n<li>BeanIO: <a href=\"http://www.beanio.org/\">http://www.beanio.org/</a></li>\n<li><a href=\"http://fixedformat4j.ancientprogramming.com/\">Fixedformat4j</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T10:13:15.067", "Id": "17266", "Score": "1", "body": "You are aware that we're on ***Code Review*** and not Stack Overflow, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T11:28:25.393", "Id": "17270", "Score": "2", "body": "I just thought that it could be useful to the person who asked to know that maybe his code could be greatly simplified by using a framework. Maybe it is not strictly code review, but it could help anyway." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T12:32:34.180", "Id": "10684", "ParentId": "10681", "Score": "6" } }, { "body": "<p>The code can be simplified and improved in several ways, and the inner loop can be made tighter. Let me show you how:</p>\n\n<pre><code>private static List&lt;List&lt;String&gt;&gt; readTXTFile(String csvFileName) throws IOException {\n\n String line = null;\n BufferedReader stream = null;\n List&lt;List&lt;String&gt;&gt; csvData = new ArrayList&lt;List&lt;String&gt;&gt;();\n\n try {\n stream = new BufferedReader(new FileReader(csvFileName));\n while ((line = stream.readLine()) != null) {\n String[] splitted = line.split(\",\");\n List&lt;String&gt; dataLine = new ArrayList&lt;String&gt;(splitted.length);\n for (String data : splitted)\n dataLine.add(data);\n csvData.add(dataLine);\n }\n } finally {\n if (stream != null)\n stream.close();\n }\n\n return csvData;\n\n}\n</code></pre>\n\n<ul>\n<li>A method should throw an exception as specific as possible, here it's better to use <code>IOException</code> instead of simply <code>Exception</code></li>\n<li>Whenever possible, return interface types instead of concrete classes. Using <code>List</code> is preferred to using <code>Vector</code>, this allows you the flexibility to change the implementation of the collection later</li>\n<li>Talking about collections: <code>Vector</code> is thread-safe and <code>synchronized</code> in many of its public methods, that can cause a performance hit. If you don't need that, it's better to use <code>ArrayList</code>, it's a drop-in replacement and won't incur in the performance penalty of synchronization. </li>\n<li>There's a simpler way to instantiate a <code>BufferedReader</code>, using a <code>FileReader</code> instead of using an <code>InputStreamReader</code> plus a <code>FileInputStream</code>. Besides, <code>FileReader</code> will take care of pesky details regarding character encoding</li>\n<li>There's a simpler way to add elements to the last <code>List</code> added to <code>csvData</code>, as shown in the code</li>\n<li>There's a simpler way to iterate through the <code>String[]</code> returned by <code>split()</code>, using an enhanced loop</li>\n<li>Don't forget to close your streams! preferably inside a <code>finally</code> block</li>\n</ul>\n\n<p>If you don't need to add more elements to the returned <code>List&lt;List&lt;String&gt;&gt;</code>, you can use the following alternate version. It's faster because it avoids copying the <code>String[]</code> of split elements, but it won't allow adding new elements, as per the contract of <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList%28T...%29\" rel=\"nofollow\"><code>asList()</code></a>:</p>\n\n<pre><code>private static List&lt;List&lt;String&gt;&gt; readTXTFile(String csvFileName) throws IOException {\n\n String line = null;\n BufferedReader stream = null;\n List&lt;List&lt;String&gt;&gt; csvData = new ArrayList&lt;List&lt;String&gt;&gt;();\n\n try {\n stream = new BufferedReader(new FileReader(csvFileName));\n while ((line = stream.readLine()) != null)\n csvData.add(Arrays.asList(line.split(\",\")));\n } finally {\n if (stream != null)\n stream.close();\n }\n\n return csvData;\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T14:43:51.300", "Id": "10685", "ParentId": "10681", "Score": "13" } }, { "body": "<p>Depends on what you name \"CSV\" if you work with really simple files, <code>split(\",\")</code> may work. </p>\n\n<p>If you should handle arbitrary CSV files, you better read <a href=\"http://ostermiller.org/utils/CSV.html\" rel=\"nofollow\">http://ostermiller.org/utils/CSV.html</a> and <a href=\"http://www.csvreader.com/java_csv.php\" rel=\"nofollow\">http://www.csvreader.com/java_csv.php</a> (which I personnaly like less) to understand the size of CSV reading problem.</p>\n\n<p>As a little help (if you need it):</p>\n\n<pre><code>Pattern splitter = Pattern.compile(\",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*(?![^\\\"]*\\\"))\");\n</code></pre>\n\n<p>will handle most of string including strings like <code>\"something\"\",\"\"\",\"\"\",\"\"another\"</code>, which covers about 2/3 of CSVs.</p>\n\n<p>Result of split: <code>\"something\"\",\"\"\"</code> and <code>\"\"\",\"\"another\"</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T21:24:59.113", "Id": "10687", "ParentId": "10681", "Score": "4" } }, { "body": "<p>Óscar López's comment regarding FileReader is blatantly incorrect. FileReader will <em>not</em> take care of any \"pesky character encoding\" issues. It will simply use the system default encoding just like InputStreamReader does.</p>\n\n<p>Using system default encoding will <em>always</em> cause problems in some point and it's use should never be encouraged. Heck, having an accented Ó on the text file will suffice.</p>\n\n<p>Whenever you are writing code that deals with text files, you always must provide a way to let the user tell the character encoding of the file. If you do not, you are writing code that can not be used correctly even if the user was capable of doing it. Instead you are forcing people into doing the wrong thing.</p>\n\n<p>I simply can not stress this enough. I have earned living writing Java applications for over 10 years and this single issue comes up practically every time I review someone else's code. It is the most common bug I have to fix over and over again (lack of understanding how time zones work are the close second :) ).</p>\n\n<p>Instead of using FileReader, use a FileInputStream chained to an InputStreamReader.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-04T18:31:12.770", "Id": "29062", "Score": "0", "body": "execelt point about encoding. Do you have any links or suggestions relating to this discussion? Perhapse suggested approaches to mitigate this problem?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-24T07:21:23.643", "Id": "11133", "ParentId": "10681", "Score": "0" } }, { "body": "<p>The biggest problem is the use of line.split(\",\") to initially break the line. If any of the values have a comma in them, then this will not work. In that case, the value must be quoted, and the comma will be within the quote, but the \"split\" function will not distinguish that.</p>\n\n<p>Also, I agree with the last comment about using the default character encoding. You should either work only in characters, our you should specify the encoding of bytes to characters.</p>\n\n<p>Let me offer you a single class implementation of reading and writing CSV files. The Only Class You Need for CSV Files:</p>\n\n<p><a href=\"http://agiletribe.wordpress.com/2012/11/23/the-only-class-you-need-for-csv-files/\" rel=\"nofollow\">http://agiletribe.wordpress.com/2012/11/23/the-only-class-you-need-for-csv-files/</a></p>\n\n<p>In about 70 lines, it does what you need most of the time without the complication of the big library approaches.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-23T19:58:39.380", "Id": "18951", "ParentId": "10681", "Score": "2" } }, { "body": "<p>Couple of thoughts : </p>\n\n<ul>\n<li>Consider using a standard library for CSV parsing. I have recently\nworked with <a href=\"http://commons.apache.org/proper/commons-csv/\" rel=\"nofollow\">Apache Commons</a> which provides simpler interface for\nCSV parsing. It internally uses ExtendedBufferedReader against\nBufferedReader which provides some extended support.</li>\n<li>As mentioned previously , try to code against the interfaces.\nReturning a List will be preferable over Vector if you are not\ngetting into threading issues.</li>\n<li>If not a standard library, you might want to provide a custom\nformat(CSV or TSV) for parser to consume, in which case your code can\nbe reused for other files also. Currently, the only argument your\nclass is taking is a filename to parse. Wouldn't it be great, if\nthere is a way to set the parser expectations and define the parse\nfunctions.</li>\n<li>How will your code behave in different encoding scenarios?</li>\n<li>Last, but not the least, how are you planning to take care of you\nrecords with values which contain comma itself ? Create a custom\nmapping against the header for a particular row will be great.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-25T19:28:09.553", "Id": "38086", "ParentId": "10681", "Score": "1" } } ]
{ "AcceptedAnswerId": "10685", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T08:02:37.013", "Id": "10681", "Score": "19", "Tags": [ "java", "array", "csv", "vectors" ], "Title": "Java function to read a CSV file" }
10681
<p>I'm mostly looking to get feedback on how well I've implemented the C++ language. But I would also like feedback on my algorithm. Did I make it more complex than it needs to be? Is there anything I could have done better?</p> <p>Things my algorithm prevents:</p> <ul> <li>IIII &lt;- "too many multiples," better represented as IV</li> <li>IIIV &lt;- "cannot add the same digit to a subtraction," better represented as VI</li> <li>IVI &lt;- "addition cannot follow subtraction," better represented as V</li> <li>IXX &lt;- "cannot subtract from a multiple," better represented as XIX</li> </ul> <p>Things it does not prevent (that I'm aware of):</p> <ul> <li>XICV &lt;- "bad format," better represented as CXIV</li> <li>IXIX &lt;- "repeated subtraction," better represented as XVIII</li> <li>VV &lt;- "multiple is value of existing digit," better represented as X</li> </ul> <p><em>Note: This uses the rules of roman numerals I was taught, and I realize that there isn't really a an accepted standard of rules for representing numbers using roman numerals.</em></p> <pre><code>#include &lt;string&gt; #include &lt;stack&gt; #include &lt;iostream&gt; #include &lt;ctype.h&gt; // required for tolower() using namespace std; int get_roman_value( char ); int roman_to_decimal( string&amp; ); int main( int argc, char* argv[] ) { if( argc &gt; 1 ) { string roman(argv[1]); try { cout &lt;&lt; roman_to_decimal(roman) &lt;&lt; endl; } catch( const char* e ) { cerr &lt;&lt; e &lt;&lt; endl; } } return 0; } int get_roman_value( char digit ) { switch( tolower(digit) ) { case 'i': return 1; break; case 'v': return 5; break; case 'x': return 10; break; case 'l': return 50; break; case 'c': return 100; break; case 'd': return 500; break; case 'm': return 1000; break; default: throw "bad digit"; } return 0; } int roman_to_decimal( string&amp; roman ) { int decimal = 0; // the final result int multiple = 0; // keeps track of multiples, eg. In XXV, X would be a multiple int current = 0; // the digit currently being processed int last_add = 0; // the last digit that wasn't a multiple, or subtraction operation int last_sub = 0; stack&lt;int&gt; digits; // queue of the digits string::iterator i; // iterator to loop through the roman string for( i = roman.begin(); i &lt; roman.end(); i++ ) digits.push( get_roman_value(*i) ); do { // get the current digit current=digits.top(), digits.pop(); // if there are too many multiples, then throw up if( multiple &gt; 2 ) throw "too many multiples"; // check for a substraction operation if( !digits.empty() &amp;&amp; current &gt; digits.top() ) { if( multiple &gt; 0 ) throw "cannot subtract from a multiple"; if( last_add == digits.top() ) throw "addition cannot follow subtraction"; decimal+=(current-digits.top()), last_sub=digits.top(), digits.pop(); } // check for multiples else if( !digits.empty() &amp;&amp; current == digits.top() ) decimal += current, multiple++; // regular addition operation else if( last_sub == current ) throw "cannot add the same digit to a subtraction"; else decimal+=current, multiple=0, last_add=current; } while( !digits.empty() ); return decimal; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T05:56:49.957", "Id": "17104", "Score": "0", "body": "There is actually an accepted standard for using Roman numerals, however, you can parse them for complete fails that don't do it properly like IIIIV pretty easily still." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T22:04:12.033", "Id": "17125", "Score": "0", "body": "@OrgnlDave, perhaps we have a different definition of \"standard.\" Can you please post a link or reference to the standard you're speaking of?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T18:22:34.600", "Id": "17164", "Score": "1", "body": "XICV <- \"bad format,\" better represented as CXIV\" . No, it isn't. The first is invalid, the second is 114. It's not 'better represented.' It's like saying '213' is better represented as '321'. Your algorithm has to have a way to reject malformed numbers, which that is. It's malformed because it's ambiguous. There are more than one way to represent a number, sure, but ambiguous becomes malformed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T19:56:58.043", "Id": "57538", "Score": "0", "body": "@OrgnlDave: What numbers are legitimately representable in more than one form? There is no \"general subtraction rule\", rather the specific substrings IV, IX, XL, XC, CD, CM, etc. [using characters not representable here] have special meaning. Ensure there are no runs of 4 or more of any character, then expand the above into IIII, VIIII, XXXX, LXXXX, etc. Then validate the expression against (for up to 999) [D][C[C[C[C]]]][L][X[X[X[X]]]][V][I[I[I[I]]]]. Any non-empty string which matches the above expression after the run-of-four check and substitutions will be a valid Roman numeral." } ]
[ { "body": "<p>Well, first of all you should probably declare variables closer to usage. Not only this will compress your code a bit, it will also save you the trouble of assigning random things to them. For example <code>int current = 0</code> declaration can be omitted.</p>\n\n<p>You normally want to use <code>!=</code> operator when dealing with iterators, so that you can switch containers, implementations, etc; and you'd generally want to increase the iterator without making an extra copy of same. So for example the following</p>\n\n<pre><code>for( i = roman.begin(); i &lt; roman.end(); i++ )\n digits.push( get_roman_value(*i) );\n</code></pre>\n\n<p>is better written as</p>\n\n<pre><code>for( i = begin(roman); i != end(roman); ++i )\n digits.push( get_roman_value(*i) );\n</code></pre>\n\n<p>also, there are some obscure reasons to write <code>begin(container)</code> and <code>end(container)</code> instead of invoking member functions, but most would say it's a matter of taste.</p>\n\n<p>Depending on how serious your are, you shouldn't throw strings, instead throw something that derives from <code>exception</code>, which is a part of STL which lives in \"<code>&lt;exception&gt;</code>\" header.</p>\n\n<p>Then there's some redundancy in your <code>switch</code>, for example</p>\n\n<pre><code>case 'i': return 1; break;\n</code></pre>\n\n<p>the break statement is not necessary, and most programmers are very familiar with <code>case</code> -> <code>return</code> pattern. Ultimately it's a matter of taste, I guess.</p>\n\n<p><strong>EDIT</strong> Answer to comment</p>\n\n<p>I would prefer to remove the declaration of <code>int current = 0</code>, and instead use:</p>\n\n<pre><code>// get the current digit\nint current = digits.top();\ndigits.pop();\n</code></pre>\n\n<p>Although I personally like your use of comma operator, most people emphatically do not; and encourage to separate statements on separate lines.</p>\n\n<p>I also noticed you are a bit inconsistent with spaces, it's advisable to always have same rules everywhere. For example there are places where you surround the assignment operator with spaces, and then there are cases when you don't.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T22:23:11.263", "Id": "17058", "Score": "1", "body": "I like your suggestion about using `!=` operator instead of the `<` operator, but I honestly cannot see how you say `current` can be omitted? I need to compare two items from the `digits` **stack** at the same time? How could I compare the top 2 items without storing one in a temporary variable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T22:36:39.267", "Id": "17060", "Score": "1", "body": "I'm sorry if I was unclear, I didn't want to get rid of it, I wanted to move it closer to where it's needed. This practice aids refactoring, and in most cases makes the code more readable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T22:41:47.793", "Id": "17061", "Score": "0", "body": "oh you mean move it inside the `do... while...` loop?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T22:43:46.277", "Id": "17062", "Score": "0", "body": "@druciferre that's right" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T22:46:26.947", "Id": "17063", "Score": "0", "body": "I can see how that makes sense. I think I only put it at the beginning of the function to make my documentation (as light-weight as it is) easier." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T22:15:13.677", "Id": "10693", "ParentId": "10686", "Score": "7" } }, { "body": "<p>Your code doesn't handle an empty input (<code>./rom2dec \"\"</code>) well, it tries to call <code>top</code> and <code>pop</code> on an empty <code>stack</code>. I'd simply move the <code>while</code> to the beginning of the loop, since I consider the empty roman numeral to have a value of zero, but you might want to throw an error instead.</p>\n\n<p><code>roman_to_decimal</code> does not modify its argument and is probably not intended to ever do so, so it should take a const reference.</p>\n\n<p>As Gleno said, throwing strings is not really a great habit. If you exit the program after an error, it's best to return an error code, so your caller can react to the error situation. I.e., don't <code>return 0</code> if an error happened. <code>return 1</code> is the most common choice for generic errors; if you want to distinguish between different types of errors, returning different non-zero numbers is the common way.</p>\n\n<p>Another thing Gleno already pointed out, I just thought I'd point out a different example: Since you're not using <code>i</code> after the loop through the string, it's probably a good idea to scope it accordingly:</p>\n\n<pre><code>for (string::const_iterator i = begin(roman); i != end(roman); ++i) {\n digits.push(get_roman_value(*i));\n}\n</code></pre>\n\n<p>Note that there is no reason to document what <code>i</code> is: The code already says it all. (Too bad there is no <code>push_iterator</code> for stacks.) In C++11, write <code>auto</code> in lieu of <code>string::const_iterator</code>.</p>\n\n<p>(Note the <code>++i</code>: Whenever you're not using the return value of an increment, it's a good habit to use pre-increment. Makes no real difference 99% of the time, but sometimes, it does.)</p>\n\n<p>I have over time moved towards always using braces for <code>for</code>, <code>if</code>, <code>else</code> etc. It makes working on the code much safer and is something I now also find easier to read. Like many things with code styles, that is mostly personal preference, of course. Just like I dislike the space distribution you are using – <code>for</code>, <code>if</code>, and <code>switch</code> are not function calls and in my opinion should not look like one; instead, I always put one space between the keyword and its <code>(</code>. For cohesion, I never put spaces after an opening parenthesis or before a closing one, with the obvious exception of indenting. As Gleno said, pick any style and then stay consistent.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T18:26:49.510", "Id": "10755", "ParentId": "10686", "Score": "6" } }, { "body": "<p>A few things:</p>\n\n<ol>\n<li><p>I would have probably used the <code>std::string</code> containing the Roman numeral rather than converting it to a stack.</p></li>\n<li><p>I avoid the <code>using std</code> in CPPs preferring to prefix Standard Lib methods with <code>std::</code>.</p></li>\n<li><p>The initial test for <code>argc &gt; 1</code> could be made more flexible by looping over all the inputs rather than the first one, e.g.</p>\n\n<pre><code>while (*++argv != NULL) std::cout &lt;&lt; *argv &lt;&lt; std::endl;\n</code></pre></li>\n<li><p>By re-ordering the methods to be:</p>\n\n<pre><code>roman_to_decimal\nget_roman_value\nmain\n</code></pre>\n\n<p>the forward declarations of the functions at the top are not needed. Currently the declaration for <code>roman_to_decimal()</code> is superfluous as the definition is before <code>get_roman_value()</code> which uses it.</p></li>\n<li><p>The function parameters could be <code>const</code>.</p></li>\n<li><p>The comment regarding using <code>begin()</code> and <code>end()</code> is better than it seems. Rather than using these for obscure reasons the C++11 standard encourages this use.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T07:26:16.677", "Id": "15561", "ParentId": "10686", "Score": "5" } } ]
{ "AcceptedAnswerId": "10693", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T16:38:40.260", "Id": "10686", "Score": "9", "Tags": [ "c++", "algorithm", "converting", "roman-numerals" ], "Title": "Roman Numeral to Decimal Conversion" }
10686
<p>I was preparing myself for an interview at a well known .com firm. One of the question that they often ask is an algorithm to solve sudokus (that have one solution). Here is what came to my mind. Any hints criticisms or suggestions to tune it up? </p> <pre><code>import itertools sudoku_str="""003020600 900305001 001806400 008102900 700000008 006708200 002609500 800203009 005010300""" sudoku=[[int(i) for i in j] for j in sudoku_str.splitlines()] while not any([0 in line for line in sudoku]): for x,y in itertools.ifilter(lambda x: sudoku[x[1]][x[0]]==False, itertools.product(*[range(9)]*2)): #Find the elements in the line line=set([i for i in sudoku[y] if i]) #Find the elements in the column column=set([xline[x] for xline in sudoku if xline[x]]) #Create some shifts to get the start (x,y) position for the area computation e.g. for 1,1 =&gt; 0,0 and for 3,8=&gt;1,3 shifts=dict(zip(range(9),[0]*3+[3]*3+[6]*3)) #Find the elements in the area area=filter(None,reduce(lambda x,y: x.add(y), sudoku[shifts[y]:shifts[y]+3], set())) #What could be in that position? outcomes=set(range(1,10))-line-column-area if len(outcomes)==1: #One outcome? replace the zero sudoku[y][x]=outcomes.pop() print "\n".join([" | ".join(str(k) for k in i) for i in sudoku]) </code></pre>
[]
[ { "body": "<p>The biggest problem with the algorithm that I can see, is that it doesn't solve all possible solvable sudoku puzzles, instead (possibly) solving only those that can be filled without guesses, i.e. without backtracking. You can consult <a href=\"http://en.wikipedia.org/wiki/Sudoku_algorithms#Standard_Sudoku_solver_and_enumerator\" rel=\"nofollow\">wikipedia article</a> on sudoku algorithms for more information. </p>\n\n<p>The biggest problem your .com employer will see with your approach, is the point-free compact style of writing your program. When you show off your ability, don't pretend that knowing compact python syntax is better than being able to clearly express your ideas and consequently be a better team player. Strive for abstracts like self-documenting code, descriptive variable names and simplicity.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T21:49:45.987", "Id": "17051", "Score": "0", "body": "Yes my mission for today was to solve only the 1-solutions sudoku. Ok I see your point; clean is better than complex. Even though I didn't want to show off but to speed up and use less memory with itertools that create generators. Am I wrong?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T22:20:06.370", "Id": "17057", "Score": "0", "body": "if by 1-solutions sudoku you mean sodoku with unique solution, then you often still need to backtrack to find that solution. If you mean something else, then that meaning was not clear. As for the memory argument, I'm not sure. However, there are very few corner cases where you'd want to optimize your code in a python interview. It would probably make much more sense to write this code in C, if memory was a concern." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T22:31:56.980", "Id": "17059", "Score": "0", "body": "Ok, therefore I'm finding out that the algo is wrong basically. I'll have to find out a schema requiring backtracking to exercise. Thanks a lot for pointing that out!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T21:43:54.963", "Id": "10689", "ParentId": "10688", "Score": "4" } }, { "body": "<p>This is far too complicated:</p>\n\n<pre><code>for x,y in itertools.ifilter(lambda x: sudoku[x[1]][x[0]]==False, itertools.product(*[range(9)]*2)):\n</code></pre>\n\n<p>It is equivalent to this:</p>\n\n<pre><code>[(x, y) for x in range(9) for y in range(9) if not sudoku[y][x]]\n</code></pre>\n\n<p>More generally, this code feels like it is trying too hard to be clever at the expense of both clarity and potentially accuracy.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>To answer the question of speed posed by the op:</p>\n\n<pre><code>$ python -m timeit 'sudoku_str=\"\"\"003020600900305001001806400008102900700000008006708200002609500800203009005010300\"\"\";sudoku = [[int(i) for i in sudoku_str[j:j+9]] for j in range(0, 81, 9)];b = [(x, y) for x in range(9) for y in range(9) if not sudoku[y][x]];'\n10000 loops, best of 3: 68.1 usec per loop\n\n$ python -m timeit 'import itertools; sudoku_str=\"\"\"003020600900305001001806400008102900700000008006708200002609500800203009005010300\"\"\";sudoku = [[int(i) for i in sudoku_str[j:j+9]] for j in range(0, 81, 9)];a =[(x, y) for x, y in itertools.ifilter(lambda x: sudoku[x[1]][x[0]]==False, itertools.product(*[range(9)]*2))];'\n10000 loops, best of 3: 91.9 usec per loop\n</code></pre>\n\n<p>A simple list comprehension is both clearer and faster.</p>\n\n<p>Here's another example of unnecessary cleverness:</p>\n\n<pre><code>&gt;&gt;&gt; shifts=dict(zip(range(9),[0]*3+[3]*3+[6]*3))\n&gt;&gt;&gt; shifts\n{0: 0, 1: 0, 2: 0, 3: 3, 4: 3, 5: 3, 6: 6, 7: 6, 8: 6}\n&gt;&gt;&gt; clear_shifts = {x:(x/3)*3 for x in range(9)}\n&gt;&gt;&gt; clear_shifts\n{0: 0, 1: 0, 2: 0, 3: 3, 4: 3, 5: 3, 6: 6, 7: 6, 8: 6}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T21:47:12.247", "Id": "17050", "Score": "0", "body": "Definitely cleaner. Would abandoning itertools comport any noticeable decrease in the speed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T22:02:58.130", "Id": "17052", "Score": "0", "body": "@luke14free abandoning itertools would significantly increase the speed: see my edit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T22:09:31.577", "Id": "17055", "Score": "0", "body": "Yes, this should be because of the lambda function. If you use ifilterfalse and put \"None\" instead of the lambda block itertools are about 10usec faster than simple lists.\n\npython -m timeit 'import itertools; sudoku_str=\"\"\"003020600900305001001806400008102900700000008006708200002609500800203009005010300\"\"\";sudoku = [[int(i) for i in sudoku_str[j:j+9]] for j in range(0, 81, 9)];a =[(x, y) for x, y in itertools.ifilterfalse(None, itertools.product(*[range(9)]*2))];'" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T22:17:14.157", "Id": "17056", "Score": "0", "body": "Great answer anyhow. I love criticisms. Anyhow set([i for i in sudoku[y] if i]) is used because:\n\na) I need a set for the \"set subtraction\".\n\nb) I cannot accept zeros. -\n\nI don't see the reason of your struggling on it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T21:44:01.353", "Id": "10690", "ParentId": "10688", "Score": "5" } }, { "body": "<p>I have to say I am really impressed (not being a Python programmer) by what can be written in Python. However, it doesn't solve all sudokus, even worse, it cycles infinitely on the \"wrong\" ones. These may even be solvable w/o guessing, there exist other rules that you can follow when solving sudoku (for one thing, if you have eg. in a line a triple of places, which only have (together) three candidate numbers to them, these numbers cannot occur in other than these three).</p>\n\n<p>BTW why don't you use something like <code>int((x-1)/3)*3</code> instead of your shifts array?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T22:04:30.523", "Id": "17053", "Score": "0", "body": "yes, in fact I explicitly said \"sudokus (that have one solution)\". Good point for the shift, a part from the fact that they are re-generated at every loop (they should be outside the main loop). Anyhow you don't even need to call int as the default division is the integer one (weird behavior changed from python 3k)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T21:53:54.040", "Id": "10691", "ParentId": "10688", "Score": "0" } }, { "body": "<p>you can try the tree and recursive based approach! In that you use the typical recursive down algorithm and cut off if not possible (pruning). For yours, you could throw in some heuristics also, i suggest google with that regard.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T22:11:15.950", "Id": "10692", "ParentId": "10688", "Score": "0" } } ]
{ "AcceptedAnswerId": "10690", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T21:39:37.747", "Id": "10688", "Score": "4", "Tags": [ "python", "algorithm", "sudoku" ], "Title": "Sudoku solving algorithm - Revision needed" }
10688
<p>I've been cooking with gas since I got Daniel C Sobral's help on my last question. I am now re-reading Odersky's "Programming in Scala, 2nd Edition" (finished my first reading about this time last year).</p> <p>I am eager to understand how to alter my mental modeling of problems to more fully embrace the functional programming style. However, I have spent hours looking at the code below attempting to figure out how to eliminate the var references. I am sure my imperative past is overshadowing and blinding me to functional possibilities.</p> <p>I think I have retained overall "referential transparency" at each method; i.e. none of the var-ness escapes the local scope of the method (or function) within which it is defined. However, I would like to understand how I might achieve a higher level of functional programming purity, even if it is slightly unreasonable, within each method. I am more looking for ways I need to change my problem solving approaches to be more myopically functional in nature.</p> <p>Specifically, how might I approach eliminate each instance of var.</p> <p>Thank you for any guidance.</p> <pre><code>case class Bitmap2d(name: String, rowsByColumns: List[List[Boolean]], faceUp: Boolean) { //require(rowsByColumns != null) //Assumed that if null was allowed as parameter, an Option would be used require(validateRectangular, "all rows must have same length") def validateRectangular: Boolean = { rowsByColumns.forall(_.size / rowsByColumns.head.size == 1) } } class Piece(name: String, charRep: Char, rowsByColumnsAndUp: List[List[Boolean]]) { val translations = createTranslations() def printTranslations() = { println("Name: " + name + " Char: " + charRep) for (bitmap2d &lt;- translations) { println(" Orientation: " + bitmap2d.name) for (row &lt;- bitmap2d.rowsByColumns) { for (pixel &lt;- row) { val value = if (pixel) "1" else "0" print(value); } println() } } } private def createTranslations() = { //generate all 7 translations val bitmap2dRaws = for (i &lt;- 0 to 7) yield translateBasedOnBitsForXYR(rowsByColumnsAndUp, i) var bitmaps = Set[List[List[Boolean]]]() var result = List[Bitmap2d]() for ( bitmap2dRaw &lt;- bitmap2dRaws if (!bitmaps.contains(bitmap2dRaw._2)) ) { bitmaps += bitmap2dRaw._2; result = Bitmap2d(bitmap2dRaw._1, bitmap2dRaw._2, bitmap2dRaw._3) :: result } result.reverse } private def translationSideUp(bits: Int) = { val flipX = ((bits &amp; 1) == 1) val flipY = ((bits &amp; 2) == 2) ((flipX || flipY) &amp;&amp; (!(flipX &amp;&amp; flipY))) } private def translationDescription(bits: Int) = { var result = List[String]() if ((bits &amp; 1) == 1) { result = "FlipX" :: result } if ((bits &amp; 2) == 2) { result = "FlipY" :: result } if ((bits &amp; 4) == 4) { result = "Rotate" :: result } result.reverse } private def translateBasedOnBitsForXYR(rowsByColumns: List[List[Boolean]], bits: Int) = { require (((bits &gt;= 0) &amp;&amp; (bits &lt; 8)), "bits must contain a value between 0 (inclusive) and 8 (exclusive)") var result = rowsByColumns; if ((bits &amp; 1) == 1) { result = translateAroundXAxis(result) } if ((bits &amp; 2) == 2) { result = translateAroundYAxis(result) } if ((bits &amp; 4) == 4) { result = translateRotate90DegreesRight(result) } (translationDescription(bits).mkString("+") , result, translationSideUp(bits)) } private def translateAroundXAxis(rowsByColumns: List[List[Boolean]]) = { if (rowsByColumns.size &gt; 1) { rowsByColumns.reverse } else { rowsByColumns } } private def translateAroundYAxis(rowsByColumns: List[List[Boolean]]) = { if (rowsByColumns.head.size &gt; 1) { for (row &lt;- rowsByColumns) yield row.reverse } else { rowsByColumns } } private def translateRotate90DegreesRight(rowsByColumns: List[List[Boolean]]) = { val width = rowsByColumns.head.size val height = rowsByColumns.size val linearized = //need non-recursive random access ( for { row &lt;- rowsByColumns pixel &lt;- row } yield pixel ).toArray var result = List[List[Boolean]]() for (i &lt;- 0 to (width - 1)) { var tempRow = List[Boolean]() for (j &lt;- 0 to (height - 1)) { tempRow = linearized((width * (j + 1)) - 1 - i) :: tempRow } result = tempRow :: result } result } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T15:07:29.763", "Id": "17114", "Score": "0", "body": "This article comes out right after I spent the weekend learning exactly this. I am feeling quite appreciative: http://nurkiewicz.blogspot.com/2012/04/secret-powers-of-foldleft-in-scala.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T17:44:50.947", "Id": "17160", "Score": "1", "body": "Why do you define `value`, only used once? Wouldn't `print(if (pixel) \"1\" else \"0\")` be at least just as readable? (Also, I'd suggest adding some line breaks for the extra-wide lines.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T02:32:13.867", "Id": "17181", "Score": "0", "body": "@Christopher Good point. And the braces were incorrect, too. My Java code format bleeding through. I've corrected both. Tyvm for your feedback." } ]
[ { "body": "<p>One good technique at eliminating vars is recursion -- it can certainly be used in this example. Alternatively, you can identify a common pattern, such as fold, traversal, etc. For example:</p>\n\n<pre><code>var bitmaps = Set[List[List[Boolean]]]()\nvar result = List[Bitmap2d]()\nfor (\n bitmap2dRaw &lt;- bitmap2dRaws\n if (!bitmaps.contains(bitmap2dRaw._2))\n)\n{\n bitmaps += bitmap2dRaw._2;\n result = Bitmap2d(bitmap2dRaw._1, bitmap2dRaw._2, bitmap2dRaw._3) :: result\n}\nresult.reverse\n</code></pre>\n\n<p>Recursion:</p>\n\n<pre><code>def getResult(bitmap2dRaws: ???, bitmap: Set[List[List[Boolean]]], result: List[Bitmap2d]): List[Bitmap2d] = bitmap2dRaws match {\n case Seq(bitmap2dRaw, rest: _*) if (!bitmaps.contains(bitmap2dRaw._2) =&gt;\n getResult(rest, bitmaps + bitmap2dRaw._2, Bitmap2d(bitmap2dRaw._1, bitmap2dRaw._2, bitmap2dRaw._3) :: result)\n case Seq(bitmap2dRaw, rest: _*) =&gt;\n getResult(rest, bitmaps, result)\n case _ =&gt; result.reverse\n}\ngetResult(bitmap2dRaws, Set[List[List[Boolean]], Nil)\n</code></pre>\n\n<p>Fold:</p>\n\n<pre><code>bitmap2dRaws.foldLeft((Set[List[List[Boolean]]], List[Bitmap2d])) {\n case ((bitmaps, result), bitmap2dRaw) if (!bitmaps.contains(bitmap2dRaw._2) =&gt;\n (bitmaps + bitmap2dRaw._2, Bitmap2d(bitmap2dRaw._1, bitmap2dRaw._2, bitmap2dRaw._3) :: result)\n case ((bitmaps, result), _) =&gt; (bitmaps, result)\n}._2.reverse\n</code></pre>\n\n<p>You can use the same techniques for the <code>var</code> inside <code>translateRotate90DegreesRight</code> as well.</p>\n\n<p>In other places you might use <code>Option</code>:</p>\n\n<pre><code>private def translationDescription(bits: Int) = {\n var result = List[String]()\n if ((bits &amp; 1) == 1) {\n result = \"FlipX\" :: result\n }\n if ((bits &amp; 2) == 2) {\n result = \"FlipY\" :: result\n }\n if ((bits &amp; 4) == 4) {\n result = \"Rotate\" :: result\n }\n result.reverse\n}\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>private def translationDescription(bits: Int) = {\n val flipX = if ((bits &amp; 1) == 1) Some(\"FlipX\") else None\n val flipY = if ((bits &amp; 2) == 2) Some(\"FlipY\") else None\n val rotate = if ((bits &amp; 4) == 4) Some(\"Rotate\") else None\n List(flipX, flipY, rotate).flatten // if this doesn't work, try flatMap(x =&gt; x)\n}\n</code></pre>\n\n<p>Finally (unless I missed something), the <code>var</code> inside <code>translateBasedOnBitsForXYR</code> can be avoided simply by using multiple <code>val</code>, and <code>if</code> statements like this:</p>\n\n<pre><code>val xTranslation = if ((bits &amp; 1) == 1) translateAroundXAxis(rowsByColumns) else rowsByColumns\n</code></pre>\n\n<p>and so on.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:06:22.867", "Id": "17077", "Score": "0", "body": "Awesome! And somewhat daunting. :) I read and reread your first answser, both the recursion and foldLeft solutions, and think I finally understood how they work. And then without copying your code, I decided to try and implement the recursive version using only your code as a reference. I wanted to be sure I pushed through all the new thinking I need to do. I will update my post with the updated code (separate from the original problem code). I have only done your first answer thus far. I will continue working through the rest of the class using your guidance and re-post in the update." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T22:54:06.727", "Id": "17093", "Score": "0", "body": "Okay. I have worked through all of your guidance. Thank you for doing both recursive and foldLeft examples. Between my way over imperative original version (which I deeply understand) and your examples, I was able to think through to both the recursion and foldLeft. I chose recursion this time. However, I will come back to using List and foldLeft to get used to using its recursive nature. Please let me know if you see anything else that can be improved on the new updated Piece object and class." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T05:38:49.553", "Id": "10699", "ParentId": "10696", "Score": "2" } }, { "body": "<p>Just a few remarks:</p>\n\n<p>This won't work - we have integer division like in Java, e.g. 7 / 5 == 1:</p>\n\n<pre><code>rowsByColumns.forall(_.size / rowsByColumns.head.size == 1)\n</code></pre>\n\n<p>Suggestion:</p>\n\n<pre><code>def validateRectangular = rowsByColumns.forall(_.size == rowsByColumns.head.size)\n</code></pre>\n\n<p>Here you're looking for an exclusive or (a.k.a. \"xor\"):</p>\n\n<pre><code>private def translationSideUp(bits: Int) = {\n val flipX = ((bits &amp; 1) == 1)\n val flipY = ((bits &amp; 2) == 2)\n ((flipX || flipY) &amp;&amp; (!(flipX &amp;&amp; flipY)))\n}\n</code></pre>\n\n<p>...which would look like</p>\n\n<pre><code>private def translationSideUp(bits: Int) = ((bits &amp; 1) == 1) ^ ((bits &amp; 2) == 2)\n</code></pre>\n\n<p>Here I would use a Map instead:</p>\n\n<pre><code>private def translationDescription(bits: Int) = {\n var result = List[String]()\n if ((bits &amp; 1) == 1) {\n result = \"FlipX\" :: result\n }\n if ((bits &amp; 2) == 2) {\n result = \"FlipY\" :: result\n }\n if ((bits &amp; 4) == 4) {\n result = \"Rotate\" :: result\n }\n result.reverse\n}\n</code></pre>\n\n<p>For instance:</p>\n\n<pre><code>private def translationDescription(bits: Int) = \n TreeMap(1-&gt;\"FlipX\", 2-&gt;\"FlipY\", 4-&gt;\"Rotate\").\n filterKeys(x =&gt; (bits &amp; x) == x).values.toList \n</code></pre>\n\n<p>Finally you can get a rotation by using List.transpose and a vertical or horizontal flip. E.g.</p>\n\n<pre><code>List(List(1,2,3),List(4,5,6)).transpose\n// List[List[Int]] = List(List(1, 4), List(2, 5), List(3, 6))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:18:54.067", "Id": "17078", "Score": "0", "body": "Oops. Good catch on Bitmap2d.validateRectangular(). It was still incorrect in Eclipse even though I had updated it when Daniel pointed it out on a previous thread. I have updated in the \"original\" code copy as it was not intended to be reworked in this thread." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:27:57.690", "Id": "17079", "Score": "0", "body": "XOR was exactly what I was looking for. And I even saw the reference in Odersky's book. I just didn't connect the dots. Thank you for the specific example. Next time I do a code update in the original post, I will add that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:32:15.143", "Id": "17080", "Score": "0", "body": "Regarding your specific example of using a Map, ordering of the elements is important. I noticed that you used a TreeMap directly defined in the method. Does that preserve the ordering I had in my original method? I wonder how I could look that up myself (i.e. the ScalaDoc for immutable.TreeMap)? And then you create the TreeMap in the instance method. In Java I would have created a private static final Map TRANSLATION_DESCRIPTIONS and then referred to it from this method to avoid instantiating it every time the method is called. Does the Scala compiler automatically figure this out?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:36:33.093", "Id": "17081", "Score": "0", "body": "I went here http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.TreeMap to try and figure out what TreeMap does. There is little resemblance to JavaDoc (like normal expansive English explanations with some prototypical examples), so I am still not able to tell if TreeMap preserves ordering some way (although the RedBlackTree it extends seems to imply it...but jumping there in the ScalaDoc didn't help me)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:49:17.243", "Id": "17085", "Score": "0", "body": "Took me a second to understand your transpose example as it doesn't do a 90 degree rotation right. However, I stepped through it and realized that it does the rotation and then I just need to do a Y axis flip for the result and I get the same result with quite a bit less work. Code change will be in the next update." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T22:51:43.407", "Id": "17092", "Score": "0", "body": "I have modified Piece to have a companion object where I define the TreeMap containing the descriptions. Does this work correctly and optimally? I cannot tell if I am still thinking too Java-like imperative." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T23:23:26.417", "Id": "17095", "Score": "1", "body": "@chaotic3quilibrium `TreeMap` is ordered by key. One might use `ListMap` or `LinkedHashMap` instead, which will preserve insertion order -- that might be more adequate to your needs. Just make sure it is working as you expect: some of these more unusual collections are not well tested, and have bugs you'd never expect to see." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T09:01:18.830", "Id": "17109", "Score": "0", "body": "Regarding TreeMap: The key order would work here, as 1,2,4 is in order. But you're right, in the general case you need something preserving insertion order." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T19:20:23.293", "Id": "10705", "ParentId": "10696", "Score": "2" } } ]
{ "AcceptedAnswerId": "10699", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T02:28:37.390", "Id": "10696", "Score": "3", "Tags": [ "functional-programming", "scala", "matrix" ], "Title": "Attempting to eliminate var (and imperative style) from my Piece class" }
10696
<p>I'm looking for a code review on the following C++/STL graph implementation:</p> <pre><code>#include &lt;list&gt; #include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;utility&gt; #include &lt;iostream&gt; #include &lt;stdexcept&gt; #include &lt;assert.h&gt; namespace Graph { template &lt;class T&gt; class graph { public : explicit graph(const std::vector&lt;std::pair&lt;T, T&gt; &gt; &amp;vertices); ~graph() {} void insert_vertex_pair_by_keys(T key1, T key2); // Private contained classes private: // Forward Definition of vertex class vertex; struct edge { edge(vertex *edge, T weight) : m_Edge(edge), m_Weight(weight) {} vertex *m_Edge; T m_Weight; }; // END EDGE class vertex { public: vertex(T key) : m_Key(key) {} void connect_edge(vertex *adjacent); const T key() const {return m_Key;} const std::list&lt;edge&gt; &amp;edges() const {return m_Edges;} private: std::list&lt;edge&gt; m_Edges; T m_Key; bool contains_edge_to_vertex_with_key(const T key); }; // END VERTEX // Private methods and member variables private: std::list&lt;vertex&gt; m_Vertices; vertex *contains_vertex(const T key); }; } /*! * Constructor of graph: Take a pair of vertices as connection, attempt * to insert if not already in graph. Then connect them in edge list */ template &lt;class T&gt; Graph::graph&lt;T&gt;::graph(const std::vector&lt;std::pair&lt;T, T&gt; &gt; &amp;vertices_relation) { #ifndef NDEBUG std::cout &lt;&lt; "Inserting pairs: " &lt;&lt; std::endl; #endif typename std::vector&lt;std::pair&lt;T, T&gt; &gt;::const_iterator insert_it = vertices_relation.begin(); for(; insert_it != vertices_relation.end(); ++insert_it) { #ifndef NDEBUG std::cout &lt;&lt; insert_it-&gt;first &lt;&lt; " -- &gt; " &lt;&lt; insert_it-&gt;second &lt;&lt; std::endl; #endif insert_vertex_pair_by_keys(insert_it-&gt;first, insert_it-&gt;second); } #ifndef NDEBUG std::cout &lt;&lt; "Printing results: " &lt;&lt; std::endl; typename std::list&lt;vertex&gt;::iterator print_it = m_Vertices.begin(); for(; print_it != m_Vertices.end(); ++print_it) { std::cout &lt;&lt; print_it-&gt;key(); typename std::list&lt;edge&gt;::const_iterator edge_it = print_it-&gt;edges().begin(); for(; edge_it != print_it-&gt;edges().end(); ++edge_it) { std::cout &lt;&lt; "--&gt;" &lt;&lt; edge_it-&gt;m_Edge-&gt;key(); } std::cout &lt;&lt; std::endl; } #endif } /*! * Takes in a value of type T as a key and * inserts it into graph data structure if * key not already present */ template &lt;typename T&gt; void Graph::graph&lt;T&gt;::insert_vertex_pair_by_keys(T key1, T key2) { /*! * Check if vertices already in graph */ Graph::graph&lt;T&gt;::vertex *insert1 = contains_vertex(key1); Graph::graph&lt;T&gt;::vertex *insert2 = contains_vertex(key2); /*! * If not in graph then insert it and get a pointer to it * to pass into edge. See () for information on how * to build graph */ if (insert1 == NULL) { m_Vertices.push_back(vertex(key1)); insert1 = contains_vertex(key1); } if (insert2 == NULL) { m_Vertices.push_back(vertex(key2)); insert2 = contains_vertex(key2); } #ifndef NDEBUG assert(insert1 != NULL &amp;&amp; "Failed to insert first vertex"); assert(insert2 != NULL &amp;&amp; "Failed to insert second vertex"); #endif /*! * At this point we should have a vertex to insert an edge on * if not throw an error. */ if (insert1 != NULL &amp;&amp; insert2 != NULL) { insert1-&gt;connect_edge(insert2); insert2-&gt;connect_edge(insert1); } else { throw std::runtime_error("Unknown"); } } /*! * Search the std::list of vertices for key * if present return the vertex to indicate * already in graph else return NULL to indicate * new node */ template &lt;typename T&gt; typename Graph::graph&lt;T&gt;::vertex *Graph::graph&lt;T&gt;::contains_vertex(T key) { typename std::list&lt;vertex &gt;::iterator find_it = m_Vertices.begin(); for(; find_it != m_Vertices.end(); ++find_it) { if (find_it-&gt;key() == key) { return &amp;(*find_it); } } return NULL; } /*! * Take the oposing vertex from input and insert it * into adjacent list, you can have multiple edges * between vertices */ template &lt;class T&gt; void Graph::graph&lt;T&gt;::vertex::connect_edge(Graph::graph&lt;T&gt;::vertex *adjacent) { if (adjacent == NULL) return; if (!contains_edge_to_vertex_with_key(adjacent-&gt;key())) { Graph::graph&lt;T&gt;::edge e(adjacent, 1); m_Edges.push_back(e); } } /*! * Private member function that check if there is already * an edge between the two vertices */ template &lt;class T&gt; bool Graph::graph&lt;T&gt;::vertex::contains_edge_to_vertex_with_key(const T key) { typename std::list&lt;edge&gt;::iterator find_it = m_Edges.begin(); for(; find_it != m_Edges.end(); ++find_it) { if (find_it-&gt;m_Edge-&gt;key() == key) { return true; } } return false; } </code></pre> <p></p> <pre><code>// main.cpp #include "graph.h" #include &lt;cstdlib&gt; int main(int argc, char *argv[]) { std::vector&lt;std::pair&lt;int, int&gt; &gt; graph_vect; for (int i = 0; i &lt; 100; i++) { graph_vect.push_back(std::pair&lt;int, int&gt;(rand()%20, rand()%20)); } Graph::graph&lt;int&gt; my_graph(graph_vect); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T17:38:28.307", "Id": "17159", "Score": "0", "body": "Why do your edges only have a single `vertex *`, and why is that pointer named `m_Edge` and `edge`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T19:32:00.533", "Id": "17166", "Score": "0", "body": "An edge can only lead to a single vertex for one. This facilitates algorithms by allowing you to traverse the edge list, then get a pointer to the vertex associated with that edge so you don't have to do a lookup on the vertex to scan its edges. m_Edge and edge where chosen because the \"edge\" leads to the adjacent vertex." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T20:04:52.463", "Id": "17168", "Score": "0", "body": "Sorry, I hadn't realized you're storing the outgoing edges in the vertices. Still not happy with the names, though – `vertex *to` and `vertex *m_endPoint`, perhaps? Nah …" } ]
[ { "body": "<ul>\n<li><p>This is a <strong>directed</strong> <strong>weighted</strong> graph. You may want to indicate this by name. If you wish to be more general you can have two type parameters, one for vertex data and one for edge data. Also think about undirected graphs.</p></li>\n<li><p>I guess namespace Graph and class name graph is redundant</p></li>\n<li><p>Depending on expected usage pattern of verticies, you may want to use vector instead of list</p></li>\n<li><p>Another way to represent edges is by a matrix where M[i,j] represents the edge between i and j.</p></li>\n</ul>\n\n<p>Worth reading is this:</p>\n\n<p><a href=\"http://community.topcoder.com/tc?module=Static&amp;d1=tutorials&amp;d2=graphsDataStrucs1\" rel=\"nofollow\">http://community.topcoder.com/tc?module=Static&amp;d1=tutorials&amp;d2=graphsDataStrucs1</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T19:48:56.020", "Id": "10707", "ParentId": "10697", "Score": "4" } }, { "body": "<p>As long as you use special function for checking, consider to use special function for adding. Something like </p>\n\n<pre><code>Graph::graph&lt;T&gt;::vertex *insert1 = contains_vertex(key1);\n\n ...\n\n if (insert1 == NULL) {\n add_vertex_in_container(vertex(key1));\n insert1 = contains_vertex(key1);\n }\n\n/*....*/\n\nadd_vertex_in_container(vertex(key1))\n{\n m_Vertices.push_back(vertex(key1));\n}\n</code></pre>\n\n<p>I'm 99% sure the compiler will make this function inline, so there won't be an calling overhead.</p>\n\n<p>pros: it's easier to change the adding logic in the future. For example to increment an counter and send an even after the adding has happened.</p>\n\n<p>cons: the code could become less readble in the case all you need is <code>m_Vertices.push_back()</code></p>\n\n<hr>\n\n<p>you could rewrite <code>contains_edge_to_vertex_with_key</code> method in such way</p>\n\n<pre><code>{\n return find(m_Edges.begin(), m_Edges.end(), key) != m_Edges.end() ? true : false ;\n}\n</code></pre>\n\n<hr>\n\n<p>upd:\nconsider to use <code>std::make_pair</code> instead of <code>std::pair</code>. In the first case you free to not specialize template parameters explicitly</p>\n\n<pre><code>vector&lt;pair&lt;int, int&gt; &gt; v;\nv.push_back(make_pair(1,2)) \n\ninstead of \nv.push_back(pair&lt;int, int&gt;(1,2))\n</code></pre>\n\n<hr>\n\n<p>+1 for possibility of changing vector to list and vise versa. Speaking more detaily your graph object shouldn't be hardly related with data structure keeping the graph structure. Consider to implement it as an template parameter.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T10:04:15.893", "Id": "10723", "ParentId": "10697", "Score": "1" } } ]
{ "AcceptedAnswerId": "10723", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T03:19:30.690", "Id": "10697", "Score": "4", "Tags": [ "c++", "graph", "stl" ], "Title": "STL graph implementation" }
10697
<p>This is a simple filter that I have been using for a project reading data over a serial connection, and thought it would be good to use it as my first attempt to write docstrings. Does anyone have any suggestions? I have been reading PEP 257. As it is a class, should the keyword arguments come after the <code>__init__</code> ?</p> <p>If there is a better way to write any part of it (not only the docstrings), I would appreciate it if people could point me in the right direction. </p> <pre><code>class Filter(object) : """Return x if x is greater than min and less than max - else return None. Keyword arguments: min -- the minimum (default 0) max -- the maximum (default 0) Notes: Accepts integers and integer strings """ def __init__(self, min=0, max=0) : self.min = min self.max = max def __call__(self, input) : try : if int(input) &lt;= self.max and int(input) &gt;= self.min : return int(input) except : pass </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T22:36:01.197", "Id": "17090", "Score": "0", "body": "For better commentary, how about including a sample of usage?" } ]
[ { "body": "<p>I'd suggest noting that the filter will always return an <code>int</code>, regardless of what you pass in.</p>\n\n<p>I'd also avoid using a bare <code>except:</code> - masking ALL exceptions is generally a bad idea. Instead, catch the exceptions that you <em>want</em> to ignore (e.g. <code>ValueError</code> and <code>TypeError</code> for integer conversion errors) and do something to handle them (either throwing your own exception or returning a default value).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:36:15.903", "Id": "10710", "ParentId": "10709", "Score": "1" } }, { "body": "<pre><code>class Filter(object) :\n \"\"\"Return x if x is greater than min and less than max - else return None. \n</code></pre>\n\n<p>How about \"if x is between min and mix\"?</p>\n\n<pre><code> Keyword arguments:\n min -- the minimum (default 0)\n max -- the maximum (default 0)\n\n Notes:\n Accepts integers and integer strings\n \"\"\"\n def __init__(self, min=0, max=0) :\n</code></pre>\n\n<p>min and max are builtin python functions. I suggest not using the same names if you can help it.</p>\n\n<pre><code> self.min = min\n self.max = max\n def __call__(self, input) :\n try :\n if int(input) &lt;= self.max and int(input) &gt;= self.min : \n</code></pre>\n\n<p>In python you can do: <code>if self.min &lt; int(input) &lt;= self.max</code></p>\n\n<pre><code> return int(input)\n\n except : pass\n</code></pre>\n\n<p>Don't ever do this. DON'T EVER DO THIS! ARE YOU LISTENING TO ME? DON'T EVER DO THIS.</p>\n\n<p>You catch and ignore any possible exception. But in python everything raises exceptions, and you'll not be notified if something goes wrong. Instead, catch only the specific exceptions you are interested in, in this, case <code>ValueError</code>.</p>\n\n<p>Futhermore, having a filter that tries to accept string or integers like this just a bad idea. Convert your input to integers before you use this function, not afterwards.</p>\n\n<p>The interface you provide doesn't seem all that helpful. The calling code is going to have to deal with <code>None</code> which will be a pain. Usually in python we'd do something operating on a list or as a generator.</p>\n\n<p>Perhaps you want something like this:</p>\n\n<pre><code>return [int(text) for text in input if min &lt; int(text) &lt; max]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:44:02.460", "Id": "17083", "Score": "0", "body": "I know I was being super lazy with the except:pass, it got the job done... but you words have not fallen on deaf ears :) Ideally I didn't want it to return anything if it was not within the range. Again the conversion of str -> int was out of lazyness, I had another function for that. So I should keep things clean, and shouldn't mix things that shouldn't be mixed..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:49:14.407", "Id": "17084", "Score": "0", "body": "One question... what exactly is the 'interface'. I didn't think Python did interfaces." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:56:39.763", "Id": "17086", "Score": "0", "body": "@user969617, interface refers to how you use the function. Stuff like names, return values, parameters, that sorta thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T22:01:27.540", "Id": "17087", "Score": "0", "body": "@Winston... gotcha" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:38:11.050", "Id": "10711", "ParentId": "10709", "Score": "4" } } ]
{ "AcceptedAnswerId": "10711", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:22:04.923", "Id": "10709", "Score": "4", "Tags": [ "python" ], "Title": "Filter for reading data over a serial connection" }
10709
<p>I was trying to solve the following <a href="http://programmingpraxis.com/2012/03/02/balanced-delimiters/" rel="nofollow">Programming Praxis</a> problem:</p> <blockquote> <p>Write a function that takes a string and determines if the delimiters in the string are balanced. The pairs of delimiters are (), [], {}, and &lt;>, and delimiters may be nested. In addition, determine that string delimiters ‘ and ” are properly matched; other delimiters lose their magical delimiter-ness property within quoted strings. Any delimiter is escaped if it follows a backslash.</p> </blockquote> <p>Here's my attempt to solve the problem:</p> <pre><code>import java.util.*; public class BalancedDelimiters{ private Map&lt;Character,Integer&gt; delimitMap; private Map&lt;Character,Character&gt; charMap; public BalancedDelimiters(){ delimitMap = new LinkedHashMap&lt;Character,Integer&gt;(); charMap = new LinkedHashMap&lt;Character,Character&gt;(); initDelimitDics(delimitMap); initCharMap(charMap); } private void initCharMap(Map&lt;Character,Character&gt; charMap){ charMap.put('(',')'); charMap.put(')','('); charMap.put('[',']'); charMap.put(']','['); charMap.put('{','}'); charMap.put('}','{'); charMap.put('&lt;','&gt;'); charMap.put('&gt;','&lt;'); } private void initDelimitDics(Map&lt;Character,Integer&gt; delimitMap){ delimitMap.put('(',0); delimitMap.put(')',0); delimitMap.put('[',0); delimitMap.put('{',0); delimitMap.put('&lt;',0); delimitMap.put('&gt;',0); delimitMap.put(']',0); delimitMap.put('}',0); } public boolean checkForBalance(String extractedString){ int balancedIndicator = 0; char[] charArr = extractedString.toCharArray(); for(char c:charArr){ if(delimitMap.containsKey(c)){ delimitMap.put(c,delimitMap.get(c)+1); } } for(Map.Entry&lt;Character,Integer&gt; entry:delimitMap.entrySet()){ System.out.println("Entry Key:"+entry.getKey()+"Entry value:"+entry.getValue()); System.out.println("Complementary delimiter:"+charMap.get(entry.getKey())); if(delimitMap.get(charMap.get(entry.getKey())) != entry.getValue()) return false; } return true; } } </code></pre> <p>Can somebody review my code and let me know how I would be able to improve this snippet?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T22:34:25.183", "Id": "17089", "Score": "1", "body": "One issue with your code is that `a)test(` returns as a balanced expression, although the bracket is closed before being opened." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T22:36:15.353", "Id": "17091", "Score": "0", "body": "And another one (but you probably already know that) is that you don't cover the second part of the requirement on the effect of `\"`, `'` and ``\\``." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T01:41:29.513", "Id": "17097", "Score": "0", "body": "@assylias - Thanks for pointing out the issue with the logic. I guess I need to maintain two different Maps, one for opening delimiter and one for closing delimiter. The appropriate entry in the right collection will be incremented based on whether it is an opening or a closing delimiter. After all the characters have been processed, the entries of these two maps will be examined for whether they have the same number of opening or closing delimiters. This is too much bookkeeping though. There should be a simpler/more elegant way to solve this problem in a streaming fashion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T06:46:07.713", "Id": "17105", "Score": "0", "body": "Perhaps consider `java.util.Stack` or anything that is equivalent to it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T07:43:26.587", "Id": "17107", "Score": "1", "body": "@sc_ray This is one way to do it: http://stackoverflow.com/a/3918697/829571" } ]
[ { "body": "<p>In order to solve this problem you should either use a stack or recursion to keep track of the current nesting levels. The proposed solutions (including the linked one from assylias) will not do when you have multiple different delimiters and also string delimiters.</p>\n\n<p>Here is a solution that seems to work based on recursion. It can probably be made a little shorter but i tried to keep it readable:</p>\n\n<pre><code>public class BalancedDelimiters {\n\n private static class NotBalancedException extends RuntimeException {\n private static final long serialVersionUID = 1L;\n }\n\n private static final Map&lt;Character, Character&gt; blockDelimiters = new HashMap&lt;Character, Character&gt;();\n static {\n blockDelimiters.put('(', ')');\n blockDelimiters.put('[', ']');\n blockDelimiters.put('{', '}');\n blockDelimiters.put('&lt;', '&gt;');\n }\n\n private static final Set&lt;Character&gt; stringDelimiters = new HashSet&lt;Character&gt;();\n static {\n stringDelimiters.add('\\\"');\n stringDelimiters.add('\\'');\n }\n\n\n public boolean checkForBalance(String extractedString) {\n try {\n consume(extractedString, null);\n return true;\n } catch (NotBalancedException e) {\n return false;\n }\n }\n\n private String consume(String remainingString, Character currentDelimiter) {\n while (true) {\n int nextInterestingCharacter = getNextInterestingCharacter(remainingString);\n if (nextInterestingCharacter == -1) {\n if (currentDelimiter == null) {\n return \"\";\n } else {\n throw new NotBalancedException();\n }\n }\n\n char delimiter = remainingString.charAt(nextInterestingCharacter);\n remainingString = remainingString.substring(nextInterestingCharacter + 1);\n if (closes(delimiter, currentDelimiter)) {\n return remainingString;\n } else if (isBlockStartDelimiter(delimiter)) {\n remainingString = consume(remainingString, delimiter);\n } else if (isStringDelimiter(delimiter)) {\n remainingString = consumeToNextStringDelimiter(remainingString, delimiter);\n } else {\n throw new NotBalancedException(); // we found a delimiter that we could not use!\n }\n }\n }\n\n private int getNextInterestingCharacter(String remainingString) {\n for (int i = 0; i &lt; remainingString.length(); i++) {\n if (remainingString.charAt(i) == '\\\\') {\n i++; // also skip next character\n } else if (isAnyKindOfDelimiter(remainingString.charAt(i))) {\n return i;\n }\n }\n return -1;\n }\n\n private String consumeToNextStringDelimiter(String remainingString, char delimiter) {\n for (int i = 0; i &lt; remainingString.length(); i++) {\n if (remainingString.charAt(i) == '\\\\') {\n i++; // also skip next character\n } else if (remainingString.charAt(i) == delimiter) {\n return remainingString.substring(i + 1);\n }\n }\n throw new NotBalancedException();\n }\n\n private boolean closes(char delimiter, Character currentDelimiter) {\n if (currentDelimiter == null) {\n return false;\n }\n return blockDelimiters.get(currentDelimiter).equals(delimiter);\n }\n\n private boolean isAnyKindOfDelimiter(char c) {\n return isBlockDelimiter(c) || isStringDelimiter(c);\n }\n\n private boolean isBlockDelimiter(char c) {\n return isBlockStartDelimiter(c) || isBlockEndDelimiter(c);\n }\n\n private boolean isBlockStartDelimiter(char c) {\n return blockDelimiters.containsKey(c);\n }\n\n private boolean isBlockEndDelimiter(char c) {\n return blockDelimiters.containsValue(c);\n }\n\n private boolean isStringDelimiter(char c) {\n return stringDelimiters.contains(c);\n }\n}\n</code></pre>\n\n<p>Note that I handle normal delimiters (i call them block delimiters) differently from string delimiters as they behave quite differently. I'm using an exception to control flow when the string is not balanced. Maybe some will find that a bit ugly but it saves a few lines of code (i think).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T10:17:59.193", "Id": "10852", "ParentId": "10712", "Score": "3" } } ]
{ "AcceptedAnswerId": "10852", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:41:33.227", "Id": "10712", "Score": "3", "Tags": [ "java", "algorithm", "strings", "balanced-delimiters" ], "Title": "Balanced delimiter method" }
10712
<p>I originally posted this in stackoverflow.com but the question may be too broad. I'm trying to figure out the best way to download and use an SQL database from my server. I have included the code i whipped up but I'm not sure if it's a viable way to accomplish this so peer review would be extremely helpful :)</p> <p>As it stands now, the database will be downloaded in a separate thread but when UI components are initialized they fail (obviously, as the database doesnt exist while its still being downloaded).</p> <pre><code>package com.sandbox.databaseone; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.util.Log; public class DatabaseManager { private SQLiteDatabase database; private int currentVersion = 0; private int nextVersion = 0; private static String databasePath = "/data/data/com.sandbox.databaseone/databases/"; private static String databaseFile = "dbone.sqlite"; private static String databaseBaseURL = "http://www.redstalker.com/dbone/"; private static String databaseVersionURL = "version.txt"; public DatabaseManager() { database = null; } public void initialize() { DatabaseVersionCheck check = new DatabaseVersionCheck(); String url = databaseBaseURL + databaseVersionURL; check.execute(url); } private void init_database(String path) { database = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY); if(database != null) { currentVersion = nextVersion; } else { nextVersion = 0; } } private class DatabaseVersionCheck extends AsyncTask&lt;String, Void, String&gt; { @Override protected String doInBackground(String... params) { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(params[0]); try { HttpResponse response = client.execute(get); int statusCode = response.getStatusLine().getStatusCode(); if(statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while((line = reader.readLine()) != null) { builder.append(line); } in.close(); reader.close(); entity.consumeContent(); } } catch(Exception e) { e.printStackTrace(); } return builder.toString(); } @Override protected void onPostExecute(String result) { if(result != null) { int version = Integer.parseInt(result); if(version &gt; currentVersion) { nextVersion = version; DownloadDatabase d = new DownloadDatabase(); d.execute(); } } } } private class DownloadDatabase extends AsyncTask&lt;Void, Void, Boolean&gt; { @Override protected Boolean doInBackground(Void... params) { boolean result = false; String url = databaseBaseURL + databaseFile; String path = databasePath + databaseFile; HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); try { HttpResponse response = client.execute(get); int statusCode = response.getStatusLine().getStatusCode(); if(statusCode == 200) { FileOutputStream fos = new FileOutputStream(path); HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); byte [] buffer = new byte[1024]; int count = 0; while((count = in.read(buffer)) != -1) { fos.write(buffer, 0, count); } fos.close(); in.close(); entity.consumeContent(); result = true; } } catch(Exception e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(Boolean result) { String path = databasePath + databaseFile; if(result) { init_database(path); } } } } </code></pre>
[]
[ { "body": "<p>Some generic Java notes, since I'm not too familiar with Android.</p>\n\n<ol>\n<li><p><code>databasePath</code>, <code>databaseFile</code>, <code>databaseBaseURL</code>, <code>databaseVersionURL</code> should be constants (all uppercase with words separated by underscores):</p>\n\n<pre><code>private static final String DATABASE_PATH = \n \"/data/data/com.sandbox.databaseone/databases/\";\nprivate static final String DATABASE_FILE = \"dbone.sqlite\";\nprivate static final String DATABASE_BASE_URL = \n \"http://www.redstalker.com/dbone/\";\nprivate static final String DATABASE_VERSION_URL =\n \"version.txt\";\n</code></pre>\n\n<p>Reference: <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\" rel=\"nofollow noreferrer\">Code Conventions for the Java Programming Language, 9 - Naming Conventions</a></p></li>\n<li><p>According to the previous Code Conventions, <code>init_database</code> should be <code>initDatabase</code>.</p></li>\n<li><p>If <code>databaseBaseURL</code> and <code>databaseVersionURL</code> hadn't be constant I'd named them as <code>databaseBaseUrl</code> and <code>databaseBaseVersionUrl</code>. From <em>Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions</em>: </p>\n\n<blockquote>\n <p>While uppercase may be more common, \n a strong argument can made in favor of capitalizing only the first \n letter: even if multiple acronyms occur back-to-back, you can still \n tell where one word starts and the next word ends. \n Which class name would you rather see, <code>HTTPURL</code> or <code>HttpUrl</code>?</p>\n</blockquote></li>\n<li>\n\n<pre><code>public DatabaseManager()\n{\n database = null;\n}\n</code></pre>\n\n<p>Initializing fields with <code>null</code> is unnecessary since <code>null</code> is the default value of references.</p></li>\n<li><p>I'd call the <code>StringBuilder</code> in the <code>doInBackground</code> method as <code>result</code>.</p>\n\n<pre><code>StringBuilder builder = new StringBuilder();\n</code></pre>\n\n<p>It would say what's the purpose of the object. For the same reason I'd rename the </p>\n\n<ul>\n<li><code>boolean result</code> to <code>boolean success</code>,</li>\n<li><code>in</code> to <code>responseStream</code>, and</li>\n<li><code>d</code> to <code>downloadDatabase</code>.</li>\n</ul></li>\n<li><p>Close your streams in a <code>finally</code> block. In case of a previous errors they won't be closed.</p></li>\n<li><p>The code does <code>databasePath + databaseFile</code> more than once. Create a method for that.</p></li>\n<li><p>I don't know if it is applicable to Android or not, but in Java it's a good practice to pass the character set to the constructor of <code>InputStreamReader</code>. Without this <code>InputStreamReader</code> uses the default charset which could vary from system to system.</p>\n\n<pre><code>BufferedReader reader = \n new BufferedReader(new InputStreamReader(in, \"UTF-8\"));\n</code></pre></li>\n<li><p>I'd use <a href=\"http://commons.apache.org/io/\" rel=\"nofollow noreferrer\">Commons IO</a>'s <a href=\"http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html\" rel=\"nofollow noreferrer\">IOUtils</a> for the copying. It has a <code>copy(InputStream input, OutputStream output)</code> which you could use in the <code>DownloadDatabase</code> task and you could use <code>copy(InputStream input, Writer output)</code> in the <code>DatabaseVersionCheck</code> task if you replace the <code>StringBuilder</code> to a <code>StringWriter</code>.</p></li>\n<li><p>In the <code>DatabaseVersionCheck.onPostExecute</code> I'd use guard clauses:</p>\n\n<pre><code>@Override\nprotected void onPostExecute(String result) {\n if(result == null) {\n return;\n }\n\n int version = Integer.parseInt(result);\n if(version &lt;= currentVersion) {\n return;\n }\n\n nextVersion = version;\n\n DownloadDatabase d = new DownloadDatabase();\n d.execute();\n}\n</code></pre>\n\n<p>It makes the code flatten and more readable. References: <em>Replace Nested Conditional with Guard Clauses</em> in <em>Refactoring: Improving the Design of Existing Code</em>; <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">Flattening Arrow Code</a></p></li>\n<li><p><code>e.printStackTrace()</code> is not the best practice. Maybe you should inform the user about the error and/or log it. </p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/7469316/why-is-exception-printstacktrace-considered-bad-practice\">Why is exception.printStackTrace() considered bad practice?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/3855187/is-it-a-bad-idea-to-use-printstacktrace-in-android-exceptions\">Is it a bad idea to use printStackTrace() in Android Exceptions?</a></li>\n</ul></li>\n<li><p><code>Integer.parseInt</code> could throw <code>NumberFormatException</code>. Maybe the code should handle it.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T04:41:43.010", "Id": "18796", "Score": "1", "body": "Wow... you really just schooled me in Java. I will definitely take this to heart and study up to improve, I appreciate it. Hopefully my next version will be cleaner." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T20:46:16.427", "Id": "11668", "ParentId": "10715", "Score": "4" } } ]
{ "AcceptedAnswerId": "11668", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T01:22:27.853", "Id": "10715", "Score": "3", "Tags": [ "java", "android" ], "Title": "AsyncTask, Android, and SQL" }
10715
<p>I don't know if this is exactly refactoring but I recently completed a <a href="http://www.cstutoringcenter.com/problems/problems.php?id=20" rel="nofollow" title="Programming Challenge">programming challenge</a> to learn more about Ruby's iterators. However, I feel that the code is extremely "un-Ruby like". Would anyone have any suggestions as to how I could improve it?</p> <pre><code>numbers = [] binary = [] binary_count = 0 File.open('decimals.txt').each_line do |line| numbers.push line.chomp end numbers.each do |number| binary.push number.to_i.to_s(2) end binary.each do |binary_num| binary_count += binary_num.count("1") end puts binary_count </code></pre> <p>Yes, I know it's a basic problem. It took me roughly five minutes to complete but it was more about just getting the syntax of the iterators down.</p>
[]
[ { "body": "<p>I would not open a stream instead use IO.readlines and enum methods:</p>\n\n<pre><code>puts File.readlines(\"decimals.txt\").reduce(0) { |total, line| total += line.chomp.to_i.to_s(2).count(\"1\") }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T07:16:38.133", "Id": "17106", "Score": "0", "body": "no need to `chomp` before `to_i`. `\"123\\n\".to_i => 123`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T14:19:42.233", "Id": "17111", "Score": "0", "body": "Why would you recommend IO.readlines and enum methods as opposed to a stream?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T14:38:41.203", "Id": "17112", "Score": "0", "body": "IO.readlines returns array of lines as your first block does. it also ensures the stream is closed and its native implementation is more optimized than the Ruby code. It is very easy to read in the code and explains the intention better. Enumerable methods are the coolest part of Ruby. Beside coolness, there is no point to keep 2 arrays + 1 stream in the memory for no reason. You have 3 star actors in the cast who never show up in the movie. It is much easier to understand shorter, but not too short, code. Only thing that I do not like is `to_i.to_s(2)` which would be better: `to_binary`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T14:43:29.250", "Id": "17113", "Score": "0", "body": "By the way, you should watch [The Enumerable Module or How I fell in Love with Ruby](http://confreaks.com/videos/607-cascadiaruby2011-the-enumerable-module-or-how-i-fell-in-love-with-ruby) if you have not yet" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T01:12:31.187", "Id": "17178", "Score": "0", "body": "Ok thanks! That helps a lot. Any other recommendations for screencasts on Ruby/RoR to watch?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T06:17:42.133", "Id": "10721", "ParentId": "10717", "Score": "1" } } ]
{ "AcceptedAnswerId": "10721", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T05:03:06.157", "Id": "10717", "Score": "4", "Tags": [ "ruby", "programming-challenge" ], "Title": "Binary numbers challenge" }
10717
<p>Here are two methods of code that only vary in one place. Specifically, the first method calls GetReleaseYear(), and the second calls GetReleaseDate().</p> <p>This is one example of a one-line difference in multiple methods, and each time the difference might be on a different line or couple of lines. One possible design I've considered is passing in a list of strings to a function, but this is cumbersome because the lists would still need to be prepared, and the generated HTML still has to be somewhat content-aware.</p> <pre><code>private string A() { string title = GetTitle(); string mediaType = GetMediaType(); string description = GetDescription(); string releaseYear = GetReleaseYear(); string contributors = GetContributors(); string image = GetImage(); string genres = GetGenres(); string ratings = GetRatings(); string top = string.Format("{0}This is a {1}{2}.&lt;br&gt;&lt;br&gt;", title, mediaType, string.IsNullOrEmpty(releaseYear) ? string.Empty : " released in " + releaseYear); StringBuilder metadata = new StringBuilder(); metadata.AppendLine(contributors + "&lt;br&gt;"); metadata.AppendLine(genres + "&lt;br&gt;&lt;br&gt;"); metadata.AppendLine(ratings + "&lt;br&gt;&lt;br&gt;"); metadata.AppendLine(description); return string.Format("{0}&lt;table&gt;&lt;tr&gt;&lt;td style=\"width:400px; vertical-align:top\"&gt;{1}&lt;/td&gt;&lt;td style=\"width:400px; vertical-align:top\"&gt;{2}&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;", top, metadata.ToString(), image); } private string B() { string title = GetTitle(); string mediaType = GetMediaType(); string description = GetDescription(); string releaseDate = GetReleaseDate(); string contributors = GetContributors(); string image = GetImage(); string genres = GetGenres(); string ratings = GetRatings(); string top = string.Format("{0}This is a {1}{2}.&lt;br&gt;&lt;br&gt;", title, mediaType, string.IsNullOrEmpty(releaseDate) ? string.Empty : " released in " + releaseDate); StringBuilder metadata = new StringBuilder(); metadata.AppendLine(contributors + "&lt;br&gt;"); metadata.AppendLine(genres + "&lt;br&gt;&lt;br&gt;"); metadata.AppendLine(ratings + "&lt;br&gt;&lt;br&gt;"); metadata.AppendLine(description); return string.Format("{0}&lt;table&gt;&lt;tr&gt;&lt;td style=\"width:400px; vertical-align:top\"&gt;{1}&lt;/td&gt;&lt;td style=\"width:400px; vertical-align:top\"&gt;{2}&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;", top, metadata.ToString(), image); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T01:16:02.243", "Id": "17098", "Score": "2", "body": "get rid of those styles and move them to CSS at the least :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T01:21:50.540", "Id": "17099", "Score": "0", "body": "@merlin2011 have you considered using a delegate?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T01:22:45.593", "Id": "17100", "Score": "0", "body": "Can the people who are voting to close this question explain why they believe it is off topic?\nI am asking this question seriously." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T01:23:55.797", "Id": "17101", "Score": "0", "body": "@dbaseman, I am aware of delegates and used them in the past, but unclear about how they might apply here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T01:35:58.083", "Id": "17102", "Score": "0", "body": "@M.Babcock The question is not really about improving existing code, because the code hasn't been written yet (outside of one instance of the existing method). It's more about designing code correctly so that when it IS written, it doesn't look like repeated garbage. \nIs it still off-topic in that case?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T01:51:11.170", "Id": "17103", "Score": "0", "body": "@merlin2011 - That is a gray line in my understanding, so I [asked a question on meta](http://meta.stackexchange.com/questions/128594/where-is-the-line-between-code-review-and-so-part-2-or-maybe-part-n) for clarification of the rules. It's Saturday night my time so I'm guessing it might be a bit til we get a response. Feel free to add your opinion on the topic." } ]
[ { "body": "<p>There's no one answer for all situations, and your code didn't indicate what the class structures involved might be. </p>\n\n<p>Here are some options:</p>\n\n<ul>\n<li>implement a GetReleaseValue(boolean fullDate) function, and have it\ncall either GetReleaseDate() or GetReleaseYear() depending on the\nvariable passed in. Then merge A() and B() into AB(boolean\nfullDate), and have it call GetReleaseValue(fullDate). </li>\n<li>if GetReleaseDate() and GetReleaseYear() are from a class, you could\ncreate a subclass and either override GetReleaseDate() to just return\na year (depending on the datatypes) or else make a new method\nGetReleaseValue() which delegates to the correct function depending\non which class you're in. Then you just have to instantiate the\nright class before calling AB().</li>\n<li>delegates can be used: this allows you to pass a function in to another function, so you'd make your new method AB(delegate releaseValue), and instead of calling GetReleaseYear/Date() you'd call the delegate method releaseValue().</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T01:34:44.700", "Id": "10719", "ParentId": "10718", "Score": "2" } }, { "body": "<p>A good practice is <code>Observe which part of the code does not change</code> Extract that keep it in a separate method. Pass the variable <code>Which changes</code> as an input to that method.</p>\n\n<pre><code> public string CommonMethod(string formattedString)\n {\n string title = GetTitle();\n string mediaType = GetMediaType();\n string description = GetDescription();\n /***string releaseYear = GetReleaseYear();***/ this is not required.\n string contributors = GetContributors();\n string image = GetImage();\n string genres = GetGenres();\n string ratings = GetRatings();\n\n string top = **formattedString**;\n\n StringBuilder metadata = new StringBuilder();\n metadata.AppendLine(contributors + \"&lt;br&gt;\");\n metadata.AppendLine(genres + \"&lt;br&gt;&lt;br&gt;\");\n metadata.AppendLine(ratings + \"&lt;br&gt;&lt;br&gt;\");\n metadata.AppendLine(description);\n\n return string.Format(\"{0}&lt;table&gt;&lt;tr&gt;&lt;td style=\\\"width:400px; vertical-align:top\\\"&gt;{1}&lt;/td&gt;&lt;td style=\\\"width:400px; vertical-align:top\\\"&gt;{2}&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;\", top, metadata.ToString(), image);\n }\n</code></pre>\n\n<p><em><strong>each time the difference might be on a different line or couple of lines.</em></strong></p>\n\n<p>This part is difficult to answer. Even in that scenario, omit the one or two lines which may change, pass the things which may change as input.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T01:58:56.363", "Id": "10720", "ParentId": "10718", "Score": "4" } } ]
{ "AcceptedAnswerId": "10720", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T01:14:02.917", "Id": "10718", "Score": "2", "Tags": [ "c#", "design-patterns" ], "Title": "What is a good way to structure mark-up generating code and avoid the example mess?" }
10718
<p>I found myself struggling when it came to refactor the following (<em>working</em>) code. Since can't be found a lot of documentation about Rails '<strong>accepts_nested_attributes_for</strong>' applied to a <strong>many-to-many</strong> relationship (furthermore, with ancillary data), I figured out it would be interesting to challenge this brave community about it! :-)</p> <p>The app logic is quite simple, we have a <strong>recipe</strong> model:</p> <pre><code>class Recipe &lt; ActiveRecord::Base has_many :quantities, dependent: :destroy has_many :ingredients, through: :quantities accepts_nested_attributes_for :quantities, :reject_if =&gt; lambda { |dq| dq[:ingredient_id].blank? || dq[:qty].blank? }, :allow_destroy =&gt; true attr_accessible :name, :description, :kind end </code></pre> <p>Which, of course, has many <strong>ingredients</strong>: </p> <pre><code>class Ingredient &lt; ActiveRecord::Base has_many :quantities, dependent: :destroy has_many :recipes, through: :quantities attr_accessible :name, :availability, :unit end </code></pre> <p>Through <strong>quantities</strong>:</p> <pre><code>class Quantity &lt; ActiveRecord::Base belongs_to :recipe belongs_to :ingredient attr_accessible :recipe_id, :ingredient_id, :qty # There can be only one of each ingredient per recipe validates_uniqueness_of :ingredient_id, scope: :recipe_id validates_numericality_of :qty, greater_than: 0 end </code></pre> <p><em>Please note</em>: every ingredient has an 'in stock' availability (and a unit of measurement for it), while every <strong>recipe</strong> needs a given '<em>quantity.qty</em>*' of some ingredients in order to be prepared.</p> <pre><code>* Quantity.where(ingredient_id: ingredient.id, recipe_id: recipe.id).qty </code></pre> <p>By the way, do you know a more concise way to get some ingredient quantity.qty for some recipe?</p> <p>Back to the main context, it is mainly about the following views. The difficult part regards the fact that the fields are dynamically displayed or removed through jQuery, as in this Railscast: <a href="http://railscasts.com/episodes/197-nested-model-form-part-2">http://railscasts.com/episodes/197-nested-model-form-part-2</a>.</p> <p>So the next one displays the form to create and edit a recipe:</p> <pre><code>&lt;%= simple_form_for(@recipe) do |f| %&gt; &lt;%= render 'shared/error_messages', object: @recipe %&gt; &lt;fieldset&gt; &lt;legend&gt;Ricetta&lt;/legend&gt; &lt;%= f.input :name %&gt; &lt;%= f.input :description %&gt; &lt;%= f.input :kind, collection: Recipe::KINDS, prompt: "Scegli..." %&gt; &lt;%= f.input :cooked %&gt; &lt;%= render 'quantities_fields' %&gt; &lt;div class="form-actions"&gt; &lt;%= f.button :submit, "Confirm" %&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;% end %&gt; </code></pre> <p>Where the quantities_fields partial is the following (now it comes the mayhem):</p> <pre><code>&lt;fieldset class="nested"&gt; &lt;legend&gt;Ingredienti&lt;/legend&gt; &lt;ol id='ingredients'&gt; &lt;%= render :partial =&gt; 'dummy_hidden_fields' %&gt; &lt;% for dq in @recipe.quantities %&gt; &lt;li class="fields"&gt; &lt;%= select_tag 'recipe[quantities_attributes][][ingredient_id]', options_from_collection_for_select(ingredients_for_select, 'id', 'name_unit', dq.ingredient_id) -%&gt; &lt;%= text_field_tag 'recipe[quantities_attributes][][qty]', ingredient_qty_for_select(dq), size: 3, placeholder: "Q.tà" %&gt; &lt;!-- the id must be POST in order to trigger update instead of create when appropriate! --&gt; &lt;%= hidden_field_tag 'recipe[quantities_attributes][][id]', dq.id %&gt; &lt;!-- the following must be changed to '1' via js in order to destroy this quantity --&gt; &lt;%= hidden_field_tag 'recipe[quantities_attributes][][_destroy]', 0 %&gt; &lt;%= link_to_function "elimina", "remove_ingredient(this)", :class =&gt; 'btn btn-mini' %&gt; &lt;/li&gt; &lt;% end %&gt; &lt;/ol&gt; &lt;%= link_to_function "Add ingredient", "add_ingredient()" %&gt; &lt;/fieldset&gt; </code></pre> <p>Yes, I wasn't able to use '<strong>fields_for</strong>' because I couldn't figure out a proper way.</p> <p>The 'dummy_hidden_field" partial is used to create some initially hidden fields to be displayed through jQuery if a new ingredient is needed:</p> <pre><code>&lt;li class="fields hidden"&gt; &lt;%= select_tag 'recipe[quantities_attributes][][ingredient_id]', options_from_collection_for_select(ingredients_for_select, 'id', 'name_unit') -%&gt; &lt;%= text_field_tag 'recipe[quantities_attributes][][qty]', nil, size: 3, placeholder: "Q.tà" %&gt; &lt;%= hidden_field_tag 'recipe[quantities_attributes][][_destroy]', 0 %&gt; &lt;%= link_to_function "elimina", "remove_ingredient(this)", :class =&gt; 'btn btn-mini' %&gt; &lt;/li&gt; </code></pre> <p>And for last the above-mentioned jQuery functions:</p> <pre><code>function remove_ingredient(link) { $(link).prev("input[type=hidden]").val("1"); $(link).closest(".fields").hide(); } function add_ingredient() { var ol = $('ol#ingredients'); ol.find('li:first').clone(true).appendTo(ol).removeClass('hidden'); } </code></pre> <p>For any further information please don't hesitate to ask!</p>
[]
[ { "body": "<p>You can try this, taken from <a href=\"http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for\" rel=\"nofollow\">Ruby on Rails API</a>:</p>\n\n<p><code>quantities_fields.html.erb</code>:</p>\n\n<pre><code>&lt;fieldset class=\"nested\"&gt;\n &lt;legend&gt;Ingredienti&lt;/legend&gt;\n &lt;ol id='ingredients'&gt; \n &lt;%= render :partial =&gt; 'dummy_hidden_fields' %&gt;\n\n &lt;%= fields_for :quantities do |recipe_quantities| %&gt;\n &lt;li class=\"fields\"&gt;\n &lt;%= recipe_quantities.select :ingredient_id, options_from_collection_for_select(ingredients_for_select, :id, :name_unit, recipe_quantities.object.ingredient_id) %&gt;\n\n ...\n\n &lt;%# fields_for will automatically generate a hidden field to store the ID of the record, so the following line is not necessary %&gt;\n &lt;%#= recipe_quantities.hidden_field_tag 'recipe[quantities_attributes][][id]', dq.id %&gt; \n\n &lt;%# when you use a form element with the _destroy parameter, with a value that evaluates to true, you will destroy the associated model (eg. 1, ‘1’, true, or ‘true’) %&gt;\n &lt;%= recipe_quantities.hidden_field :_destroy, value: 0 %&gt;\n &lt;%= link_to_function \"elimina\", \"remove_ingredient(this)\", :class =&gt; 'btn btn-mini' %&gt; \n &lt;/li&gt; \n &lt;% end %&gt; \n&lt;/ol&gt; \n&lt;%= link_to_function \"Add ingredient\", \"add_ingredient()\" %&gt;\n</code></pre>\n\n<p> </p>\n\n<p>Instead of using a hidden <code>li</code> to add new ingredients, to use a template, like in <a href=\"http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for#1435-Using-fields-for-with-collection-no-association-\" rel=\"nofollow\">this example</a> (written in <code>haml</code>):</p>\n\n<pre><code>%h1 Edit Task Collection\n= form_tag task_collection_update_path, :method =&gt; :put do\n %table#tasks\n %tr\n %th Name\n %th Priority\n - @tasks.each do |task|\n = fields_for 'tasks[]', task, :hidden_field_id =&gt; true do |task_form|\n = render :partial =&gt; 'task_form', :locals =&gt; {:task_form =&gt; task_form}\n\n = button_tag 'Save'\n\n= button_tag \"Add task\", :type =&gt; :button, :id =&gt; :add_task\n\n%script{:type =&gt; 'html/template', :id =&gt; 'task_form_template'}\n = fields_for 'tasks[]', Task.new, :index =&gt; 'NEW_RECORD', :hidden_field_id =&gt; true do |task_form| render(:partial =&gt; 'task_form', :locals =&gt; {:task_form =&gt; task_form}); end\n\n:javascript\n $(function(){\n task_form = function(){ return $('#task_form_template').text().replace(/NEW_RECORD/g, new Date().getTime())}\n var add_task = function(){ $('#tasks').append(task_form()) }\n $('#add_task').on('click', add_task)\n })\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T00:02:51.660", "Id": "73812", "Score": "1", "body": "+1 for putting the effort in - and not running away with all those downvotes! Keep answering, CR needs you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T21:41:57.427", "Id": "42813", "ParentId": "10724", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T12:34:55.240", "Id": "10724", "Score": "8", "Tags": [ "jquery", "ruby", "ruby-on-rails" ], "Title": "Refactoring contest: Rails accepts_nested_attributes_for a many-to-many associated model" }
10724
<p>I saw <a href="http://odetocode.com/Blogs/scott/archive/2012/04/09/a-refactoring-experiment.aspx" rel="nofollow">this article that proposes a refactoring exercise</a> and thought I'd give it a try.</p> <p><strong>Spoiler alert:</strong> I'm going to show my solution to the Kata below. You might want to attempt the Kata yourself before you look at this code, so this will not influence you in any way.</p> <p>I ended up with the following three classes:</p> <p><strong>Person.cs</strong></p> <pre><code>public class Person { public string Name { get; set; } public DateTime BirthDate { get; set; } public bool IsOlderThan(Person person2) { return BirthDate &gt; person2.BirthDate; } } </code></pre> <p><strong>Pair.cs</strong></p> <pre><code>public class Pair { public Person Person1 { get; set; } public Person Person2 { get; set; } public TimeSpan AgeDifference { get { return Person2.BirthDate - Person1.BirthDate; } } public Pair(Person person1, Person person2) { if (person1.IsOlderThan(person2)) { Person1 = person2; Person2 = person1; } else { Person1 = person1; Person2 = person2; } } public Pair() { Person1 = Person2 = null; } } </code></pre> <p><strong>Finder.cs</strong></p> <pre><code>public class Finder { private readonly List&lt;Person&gt; _person; public Finder(List&lt;Person&gt; person) { _person = person; } public Pair FindClosestAgeInterval() { return Find(pairs =&gt; pairs.OrderBy(p =&gt; p.AgeDifference).FirstOrDefault()); } public Pair FindFurthestAgeInterval() { return Find(pairs =&gt; pairs.OrderByDescending(p =&gt; p.AgeDifference).FirstOrDefault()); } public Pair Find(Func&lt;IEnumerable&lt;Pair&gt;, Pair&gt; pairSelectionLambda) { var availableDistinctPairs = GetDistinctPairs(); return pairSelectionLambda(availableDistinctPairs) ?? new Pair(); } private IEnumerable&lt;Pair&gt; GetDistinctPairs() { for (var i = 0; i &lt; _person.Count - 1; i++) for (var j = i + 1; j &lt; _person.Count; j++) yield return new Pair(_person[i], _person[j]); } } </code></pre> <p>The test class basically remained the same (except that I have updated it with the new class/method names).</p> <p>Overall I think this code is OK (it passes the tests and I could easily understand it 6 months from now).</p> <p>However, I'm interested to hear your critic opinions, to find out how it can get better.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T15:37:43.220", "Id": "17116", "Score": "1", "body": "I would rename the fields in `Pair` to reflect their respective ages. Maybe something like `Senior` and `Junior` or `Elder` and `Younger`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T19:35:54.517", "Id": "17122", "Score": "0", "body": "@CarlManaster you are right; the names you propose are very suggestive. I really shouldn't have left those property names as I did." } ]
[ { "body": "<p>My $0.02. Your solution is quite good as it stands. Just putting my thing down too.</p>\n\n<p>I'm a fan of interface-based development with factory methods, so I extracted out an interface for the <code>Person</code> class called <code>IPerson</code>:</p>\n\n<pre><code>public interface IPerson\n{\n string Name { get; }\n\n DateTime BirthDate { get; }\n}\n</code></pre>\n\n<p>and then implemented <code>Person</code> as a <code>sealed</code> immutable class (using <code>readonly</code> and a parametrized <code>private</code> constructor) which has a factory method:</p>\n\n<pre><code>public sealed class Person : IPerson\n{\n private readonly string name;\n\n private readonly DateTime birthDate;\n\n private Person(string name, DateTime birthDate)\n {\n this.name = name;\n this.birthDate = birthDate;\n }\n\n public string Name { get { return this.name; } }\n\n public DateTime BirthDate { get { return this.birthDate; } }\n\n public static IPerson Create(string name, DateTime birthDate)\n {\n return new Person(name, birthDate);\n }\n}\n</code></pre>\n\n<p>I did similarly with the class you called <code>Pair</code>, but I called it <code>PersonBirthdayDifference</code> (I'll freely admit I can't think up a useful name at all). Also note the static <code>Empty</code> property which I put to use in the <code>Finder</code> algorithm rather than just <code>new</code>ing up one with no properties set.</p>\n\n<pre><code>public interface IPersonBirthdayDifference\n{\n IPerson YoungerPerson { get; }\n\n IPerson ElderPerson { get; }\n\n TimeSpan AgeDifference { get; }\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>public sealed class PersonBirthdayDifference : IPersonBirthdayDifference\n{\n private static readonly IPersonBirthdayDifference empty = Create(null, null);\n\n private readonly IPerson youngerPerson;\n\n private readonly IPerson elderPerson;\n\n private readonly TimeSpan ageDifference;\n\n private PersonBirthdayDifference(IPerson youngerPerson, IPerson elderPerson)\n {\n this.youngerPerson = youngerPerson;\n this.elderPerson = elderPerson;\n this.ageDifference = (youngerPerson == null) || (elderPerson == null)\n ? default(TimeSpan)\n : elderPerson.BirthDate - youngerPerson.BirthDate;\n }\n\n public static IPersonBirthdayDifference Empty { get { return empty; } }\n\n public IPerson YoungerPerson { get { return this.youngerPerson; } }\n\n public IPerson ElderPerson { get { return this.elderPerson; } }\n\n public TimeSpan AgeDifference { get { return this.ageDifference; } }\n\n public static IPersonBirthdayDifference Create(IPerson p1, IPerson p2)\n {\n return new PersonBirthdayDifference(p1, p2);\n }\n}\n</code></pre>\n\n<p>Finally, I update the <code>Finder</code> class by some of the same methods as above, plus introduce a couple more helper classes called <code>GreaterThanComparer</code> and <code>LessThanComparer</code> (not posting that code, it's rather trivial) to keep the <code>switch</code> from executing every iteration of the loop. There's also a healthy dose of LINQ to help declare intent where I can:</p>\n\n<pre><code>public sealed class Finder : IFinder\n{\n private readonly IList&lt;IPerson&gt; people;\n\n private Finder(IEnumerable&lt;IPerson&gt; people)\n {\n this.people = people.ToList();\n }\n\n public static IFinder Create(IEnumerable&lt;IPerson&gt; people)\n {\n return new Finder(people);\n }\n\n public IPersonBirthdayDifference Find(FinderType finderType)\n {\n var peopleInOrder = this.PopulateListInOrder();\n\n return peopleInOrder.Any() ? GetAnswer(peopleInOrder, finderType) : PersonBirthdayDifference.Empty;\n }\n\n private static IPersonBirthdayDifference GetAnswer(\n IEnumerable&lt;IPersonBirthdayDifference&gt; peopleInOrder,\n FinderType finderType)\n {\n IPersonDifferenceComparer comparer;\n\n switch (finderType)\n {\n case FinderType.LessThan:\n comparer = LessThanComparer.Create();\n break;\n case FinderType.GreaterThan:\n comparer = GreaterThanComparer.Create();\n break;\n default:\n return PersonBirthdayDifference.Empty;\n }\n\n var answer = peopleInOrder.First();\n\n foreach (var person in peopleInOrder)\n {\n if (comparer.Compare(person.AgeDifference, answer.AgeDifference))\n {\n answer = person;\n }\n }\n\n return answer;\n }\n\n private IEnumerable&lt;IPersonBirthdayDifference&gt; PopulateListInOrder()\n {\n IList&lt;IPersonBirthdayDifference&gt; peopleInOrder = new List&lt;IPersonBirthdayDifference&gt;();\n\n for (var i = 0; i &lt; this.people.Count - 1; i++)\n {\n for (var j = i + 1; j &lt; this.people.Count; j++)\n {\n var isYounger = this.people[i].BirthDate &lt; this.people[j].BirthDate;\n var youngerPerson = isYounger ? this.people[i] : this.people[j];\n var elderPerson = isYounger ? this.people[j] : this.people[i];\n\n peopleInOrder.Add(PersonBirthdayDifference.Create(youngerPerson, elderPerson));\n }\n }\n\n return peopleInOrder;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T18:12:25.757", "Id": "17119", "Score": "1", "body": "Re: specific to the Person class. I see this pattern a lot and like that it is immutable. Contrary to this approach, if I was to put on my devil's advocate hat, I'd be curious to your thoughts on this presentation about \"Stop writing classes\". In it, Jack Diederich claims that if you have a class with two methods and one of those is a [constructor], it shouldn't be a class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T18:39:57.587", "Id": "17121", "Score": "1", "body": "I'm still watching the video, but he makes sense with his hypothesis of favor simplicity over complexity. This is a laudable goal, but I think it should follow the computer programming maxim of *\"it depends\"*. It depends if you know this little complex beeble bobble will be needed down the road or it allows for better integration with unit testing, etc. I don't know if C# has a good analogue to the function construct he refers to in Python that would help accomplish that goal. I also think the dynamic nature of Python allows for some natural code shrinkage." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T19:48:38.087", "Id": "17123", "Score": "0", "body": "@JesseC.Slicer Thanks for sharing these enhacenments. I think that's really a good example for using the Null Object pattern; I like that you handled the case of one or both persons being `null` when calculating the Age (which I inexcusably forgot) and that the classes are immutable. I also think that your use of comparers can be more readable than the lambdas in my example. In this scenario, however, I think I'd go without extracting interfaces for the classes, unless I really have to for some reason." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T20:04:08.053", "Id": "17124", "Score": "0", "body": "@RyanMiller Thanks for sharing this interesting video. Jack's the examples are expressive and I perfectly agree with the idea of keeping things simple, but I also think he employs some extreme arguments in order to make his point. For example, encapsulation, decoupling and separation of concerns are not jokes, but concepts that actually yield great benefits when correctly applied. I agree with Jesse's *\"it depends\"*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-01T16:45:20.743", "Id": "243034", "Score": "0", "body": "I've seen static creates like this before.. why not In your person class just remove the create and make the ctor public, you can still get immutability?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-01T17:57:01.787", "Id": "243059", "Score": "0", "body": "@CSharper I feel a bit differently now than I did a little over four years ago. In this case, the `Person` object is a simple data transfer object (DTO) with no behavior, so I'd not have it interfaced. Possibly only the `Finder` class as it's a \"service\"." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T17:23:17.073", "Id": "10729", "ParentId": "10726", "Score": "2" } }, { "body": "<p>Here's a stab at an extensible solution (I crammed everything into a single file to reduce the length). While some would argue this goes beyond the scope of the original requirements, it aims to provide extensibility points and keeps the Open-Close Principle (and DRY) in mind throughout. The client can either use an existing search algorithm (greatest or least age difference) or specify their own. Although both of these built-in solutions execute O(n) linear searches, the open interface would allow a client to provide a different / more efficient algorithm if they so desired. </p>\n\n<p>This is certainly a worthwhile exercise, especially to anyone that doesn't fully realize the importance of writing legible code and proper Unit Tests. The real beauty of all that time spent writing tests is immediately apparent when you start modifying the internals and can confirm at a glance that the changes have not inadvertently broken some other part of the system. The need for legible code speaks for itself when you start with something as unbelievably cryptic as this sample.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Algorithm\n{\n /// &lt;summary&gt;\n /// Provides search capability over a given set of persons in order to select\n /// an appropriate pair of persons.\n /// &lt;/summary&gt;\n public class PersonPairSearcher\n {\n private readonly IEnumerable&lt;Person&gt; persons;\n private readonly IEnumerable&lt;PersonPair&gt; pairs;\n\n public PersonPairSearcher(List&lt;Person&gt; persons)\n {\n this.persons = persons;\n this.pairs = new PersonPairGenerator(persons).Pairs;\n }\n\n /// &lt;summary&gt;\n /// Locates the best matching pair in the given list of people\n /// based upon the specified search criteria.\n /// &lt;/summary&gt;\n /// &lt;param name=\"mode\"&gt;Search algorithm to be used to locate the best matching pair.&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public PersonPair Find(IPersonSearchBehavior searchBehavior)\n {\n if (!pairs.Any())\n return PersonPair.Empty;\n\n return searchBehavior.GetMatch(pairs);\n }\n }\n\n /// &lt;summary&gt;\n /// Represents a pair of Persons.\n /// &lt;/summary&gt;\n public class PersonPair\n {\n public static PersonPair Empty { get { return new PersonPair(null, null); } }\n\n public PersonPair(Person person1, Person person2)\n {\n //a pair can't have only one person.\n if (person1 == null || person2 == null)\n return;\n\n if (person1.BirthDate &gt; person2.BirthDate)\n {\n YoungerPerson = person2;\n OlderPerson = person1;\n }\n else\n {\n YoungerPerson = person1;\n OlderPerson = person2;\n }\n }\n\n public Person YoungerPerson { get; private set; }\n public Person OlderPerson { get; private set; }\n public TimeSpan AgeDifference { get { return OlderPerson.BirthDate - YoungerPerson.BirthDate; } }\n }\n\n /// &lt;summary&gt;\n /// Represents a Person.\n /// &lt;/summary&gt;\n public class Person\n {\n public string Name { get; set; }\n public DateTime BirthDate { get; set; }\n }\n\n /// &lt;summary&gt;\n /// Generates a set of pairs from the given set of persons.\n /// &lt;/summary&gt;\n internal class PersonPairGenerator\n {\n private IEnumerable&lt;Person&gt; persons;\n private IEnumerable&lt;PersonPair&gt; pairs;\n\n public PersonPairGenerator(IEnumerable&lt;Person&gt; persons)\n {\n this.persons = persons;\n BuildPairs();\n }\n\n public IEnumerable&lt;PersonPair&gt; Pairs\n {\n get\n {\n return this.pairs;\n }\n }\n\n private void BuildPairs()\n {\n var pairs = new List&lt;PersonPair&gt;();\n\n for (var i = 0; i &lt; persons.Count() - 1; i++)\n {\n for (var j = i + 1; j &lt; persons.Count(); j++)\n {\n var pair = new PersonPair(persons.ElementAt(i), persons.ElementAt(j));\n pairs.Add(pair);\n }\n }\n\n this.pairs = pairs;\n }\n }\n\n /// &lt;summary&gt;\n /// A contract for a search algorithm that selects the best matching pair from the available set.\n /// &lt;/summary&gt;\n public interface IPersonSearchBehavior\n {\n PersonPair GetMatch(IEnumerable&lt;PersonPair&gt; pairs);\n }\n\n /// &lt;summary&gt;\n /// A person pair searcher that locates the pair with the greatest difference in age.\n /// &lt;/summary&gt;\n public sealed class LargestAgeDifferenceSearch : LinearSearchBehavior\n {\n protected override bool SuperseedsExistingMatch(PersonPair candidate, PersonPair existing)\n {\n return candidate.AgeDifference &gt; existing.AgeDifference;\n }\n }\n\n /// &lt;summary&gt;\n /// A person pair searcher that locates the pair with the smallest difference in age.\n /// &lt;/summary&gt;\n public sealed class SmallestAgeDifferenceSearch : LinearSearchBehavior\n {\n protected override bool SuperseedsExistingMatch(PersonPair candidate, PersonPair existing)\n {\n return candidate.AgeDifference &lt; existing.AgeDifference;\n }\n }\n\n /// &lt;summary&gt;\n /// Searches the given set of pairs linearly, checking if each is a better match than the last.\n /// &lt;/summary&gt;\n public abstract class LinearSearchBehavior : IPersonSearchBehavior\n {\n public PersonPair GetMatch(IEnumerable&lt;PersonPair&gt; pairs)\n {\n if (!pairs.Any())\n return null;\n\n var result = pairs.ElementAt(0);\n for (int i = 1; i &lt; pairs.Count(); i++)\n {\n var candidate = pairs.ElementAt(i);\n if (SuperseedsExistingMatch(candidate, result))\n result = candidate;\n }\n\n return result;\n }\n\n protected abstract bool SuperseedsExistingMatch(PersonPair candidate, PersonPair existing);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T10:20:47.977", "Id": "412459", "Score": "0", "body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T04:21:34.260", "Id": "10847", "ParentId": "10726", "Score": "1" } }, { "body": "<p>I found this interesting and I did the job as well</p>\n\n<p>I fully believe on the <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">solid principles</a> and <a href=\"https://en.wikipedia.org/wiki/Object-oriented_programming\" rel=\"nofollow noreferrer\">object oriented principles</a>, that's how I ended up with the following code:</p>\n\n<p>The idea behind <code>IFindStrategy</code> interface is to make the solution extensible. That's why I have created it and my strategies inherit from it (<a href=\"https://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow noreferrer\">See Strategy pattern</a>)</p>\n\n<p><code>IFindStrategy</code> is the interface from which all my strategies will inherit</p>\n\n<pre><code>public interface IFindStrategy\n{\n PeopleTuple Execute();\n}\n</code></pre>\n\n<p>I have created an abstract class for my strategies so that the logic inside <code>LessThan2People</code> is not spread throughout the solution. We can also think about extending this abstract class in the feature (if needed). This is handy if we want to add behaviour to all our strategies from one place.</p>\n\n<pre><code>public abstract class FindStrategyBase\n{\n protected readonly List&lt;Person&gt; Persons;\n\n protected FindStrategyBase(List&lt;Person&gt; persons)\n {\n Persons = persons;\n }\n\n public bool LessThan2People()\n {\n return Persons.Count &lt; 2;\n }\n}\n</code></pre>\n\n<p><code>FindStrategyBase</code> is our based class and we inherited because we need the behaviour in that class inside our strategy.</p>\n\n<p><code>IFindStrategy</code> makes possible to pass millions of different strategies in our finder class without changing the code of our finder class, this is the beauty of the <a href=\"https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle\" rel=\"nofollow noreferrer\">Open/Close principle</a>. This is possible thanks to Thanks to <a href=\"https://en.wikipedia.org/wiki/Polymorphism_(computer_science)\" rel=\"nofollow noreferrer\">polymorphism</a> </p>\n\n<p><code>FurthestTwoPeopleByAgeStrategy</code> is one of my strategies, it inherits from <code>FindStrategyBase</code> and <code>IFindStrategy</code>. It looks for the Furthest two people inside the list persons base on their age.</p>\n\n<pre><code>public class FurthestTwoPeopleByAgeStrategy : FindStrategyBase, IFindStrategy\n{\n public FurthestTwoPeopleByAgeStrategy(List&lt;Person&gt; persons) : base(persons)\n {\n }\n\n public PeopleTuple Execute()\n {\n if (LessThan2People())\n return PeopleTuple.None;\n\n var tr = new List&lt;PeopleTuple&gt;();\n\n for (var i = 0; i &lt; Persons.Count - 1; i++)\n {\n for (var j = i + 1; j &lt; Persons.Count; j++)\n {\n var r = new PeopleTuple(Persons[i], Persons[j]);\n tr.Add(r);\n }\n }\n\n return tr.Count == 1 ? tr[0] : tr.Aggregate((agg, next) =&gt;\n next.DifferenceOfAges &gt; agg.DifferenceOfAges ? next : agg);\n }\n}\n</code></pre>\n\n<p><code>ClosestTwoPeopleByAgeStrategy</code> is one of my strategies, it inherits from <code>FindStrategyBase</code> and <code>IFindStrategy</code>. It looks for the closest two people inside the list persons base on their age.</p>\n\n<pre><code>public class ClosestTwoPeopleByAgeStrategy : FindStrategyBase, IFindStrategy\n{\n public ClosestTwoPeopleByAgeStrategy(List&lt;Person&gt; persons) : base(persons)\n {\n }\n\n public PeopleTuple Execute()\n {\n if (LessThan2People())\n return PeopleTuple.None;\n\n var tr = new List&lt;PeopleTuple&gt;();\n\n for (var i = 0; i &lt; Persons.Count - 1; i++)\n {\n for (var j = i + 1; j &lt; Persons.Count; j++)\n {\n var r = new PeopleTuple(Persons[i], Persons[j]);\n tr.Add(r);\n }\n }\n\n return tr.Count == 1 ? tr[0] : tr.Aggregate((agg, next) =&gt;\n next.DifferenceOfAges &lt; agg.DifferenceOfAges ? next : agg);\n }\n}\n</code></pre>\n\n<p>Finder receives any strategy and executes it. <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility principle</a>.</p>\n\n<pre><code>public class Finder\n{\n private readonly IFindStrategy _findStrategy;\n\n public Finder(IFindStrategy findStrategy)\n {\n _findStrategy = findStrategy;\n }\n\n public PeopleTuple Find()\n { \n return _findStrategy.Execute();\n }\n}\n</code></pre>\n\n<p>Person class complies with <a href=\"https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)\" rel=\"nofollow noreferrer\">encapsulation Object Oriented Principle</a>. It forbids the access to its properties and provides only methods that are needed for the client.</p>\n\n<pre><code>public class Person : IEquatable&lt;Person&gt;\n{\n private readonly string _name;\n private readonly DateTime _birthDate;\n\n public Person(string name, DateTime birthDate)\n {\n _name = name;\n _birthDate = birthDate;\n }\n\n public bool IsOlderThan(Person p) =&gt; _birthDate &gt; p._birthDate;\n\n public TimeSpan DifferenceOfAges(Person p) =&gt; _birthDate - p._birthDate;\n\n public override bool Equals(object obj)\n {\n if (ReferenceEquals(null, obj)) return false;\n if (ReferenceEquals(this, obj)) return true;\n if (obj.GetType() != GetType()) return false;\n return Equals((Person) obj);\n }\n\n public override int GetHashCode()\n {\n unchecked\n {\n return ((_name != null ? _name.GetHashCode() : 0) * 397) ^ _birthDate.GetHashCode();\n }\n }\n\n public bool Equals(Person other)\n {\n if (ReferenceEquals(null, other)) return false;\n if (ReferenceEquals(this, other)) return true;\n return string.Equals(_name, other._name) &amp;&amp; _birthDate.Equals(other._birthDate);\n }\n}\n</code></pre>\n\n<p><code>PeopleTuple</code> class complies with <a href=\"https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)\" rel=\"nofollow noreferrer\">encapsulation Object Oriented Principle</a>. It forbids the access to its properties and provides only methods that are needed for the client.</p>\n\n<pre><code>public class PeopleTuple\n{\n public static PeopleTuple None =&gt; null;\n\n private Person YoungerPerson { get; set; }\n private Person OlderPerson { get; set; }\n public TimeSpan DifferenceOfAges =&gt; OlderPerson.DifferenceOfAges(YoungerPerson);\n\n public PeopleTuple(Person p1, Person p2)\n {\n OlderPerson = p1.IsOlderThan(p2) ? p1 : p2;\n YoungerPerson = p1.IsOlderThan(p2) ? p2 : p1;\n }\n\n public bool IsEqualsToYoungerPerson(Person p)\n {\n return YoungerPerson.Equals(p);\n }\n\n public bool IsEqualsToOlderPerson(Person p)\n {\n return OlderPerson.Equals(p);\n }\n}\n</code></pre>\n\n<p>I have also changed the unit tests to reflect my changes</p>\n\n<pre><code>public class FinderTests\n{\n [Fact]\n public void Returns_Empty_Results_When_Given_Empty_List()\n {\n var list = new List&lt;Person&gt;();\n var finder = new Finder(new ClosestTwoPeopleByAgeStrategy(list));\n var result = finder.Find();\n\n Assert.True(result == PeopleTuple.None);\n }\n\n [Fact]\n public void Returns_Empty_Results_When_Given_One_Person()\n {\n var list = new List&lt;Person&gt;() { sue };\n var finder = new Finder(new ClosestTwoPeopleByAgeStrategy(list));\n var result = finder.Find();\n\n Assert.True(result == PeopleTuple.None);\n }\n\n [Fact]\n public void Returns_Closest_Two_For_Two_People()\n {\n var list = new List&lt;Person&gt;() { sue, greg };\n var finder = new Finder(new ClosestTwoPeopleByAgeStrategy(list));\n var result = finder.Find();\n\n Assert.True(result.IsEqualsToYoungerPerson(sue));\n Assert.True(result.IsEqualsToOlderPerson(greg));\n }\n\n [Fact]\n public void Returns_Furthest_Two_For_Two_People()\n {\n var list = new List&lt;Person&gt;() { greg, mike };\n var finder = new Finder(new FurthestTwoPeopleByAgeStrategy(list));\n var result = finder.Find();\n\n Assert.True(result.IsEqualsToYoungerPerson(greg));\n Assert.True(result.IsEqualsToOlderPerson(mike));\n }\n\n [Fact]\n public void Returns_Furthest_Two_For_Four_People()\n {\n var list = new List&lt;Person&gt;() { greg, mike, sarah, sue };\n var finder = new Finder(new FurthestTwoPeopleByAgeStrategy(list));\n var result = finder.Find();\n\n Assert.True(result.IsEqualsToYoungerPerson(sue));\n Assert.True(result.IsEqualsToOlderPerson(sarah));\n }\n\n [Fact]\n public void Returns_Closest_Two_For_Four_People()\n {\n var list = new List&lt;Person&gt;() { greg, mike, sarah, sue };\n var finder = new Finder(new ClosestTwoPeopleByAgeStrategy(list));\n var result = finder.Find();\n\n Assert.True(result.IsEqualsToYoungerPerson(sue));\n Assert.True(result.IsEqualsToOlderPerson(greg));\n }\n\n Person sue = new Person(\"Sue\", new DateTime(1950, 1, 1));\n Person greg = new Person(\"Greg\", new DateTime(1952, 6, 1));\n private Person sarah = new Person(\"Sarah\", new DateTime(1982, 1, 1));\n private Person mike = new Person(\"Mike\", new DateTime(1979, 1, 1));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T10:20:36.643", "Id": "412458", "Score": "0", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T15:15:27.953", "Id": "213144", "ParentId": "10726", "Score": "0" } } ]
{ "AcceptedAnswerId": "10729", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T15:31:28.503", "Id": "10726", "Score": "3", "Tags": [ "c#" ], "Title": "OdeToCode Refactoring Kata" }
10726
<p>I had originally posted this question without posting the full algorithm. Here is the whole thing.</p> <p>I have an HTML page like this:</p> <pre><code>&lt;table id="inputTable"&gt; &lt;tr&gt; &lt;td&gt;Label1&lt;/td&gt; &lt;td&gt;&lt;input type="text" value="" id="inputA1"&gt;&lt;/td&gt; &lt;td&gt;&lt;span id="inputA1ErrMsg"/&gt;&lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" value="" id="inputA1_"&gt;&lt;/td&gt; &lt;td&gt;&lt;span id="inputA1ErrMsg_"/&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Label1&lt;/td&gt; &lt;td&gt;&lt;input type="text" value="" id="inputA2"&gt;&lt;/td&gt; &lt;td&gt;&lt;span id="inputA2ErrMsg"/&gt;&lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" value="" id="inputA2_"&gt;&lt;/td&gt; &lt;td&gt;&lt;span id="inputA2ErrMsg_"/&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Label1&lt;/td&gt; &lt;td&gt;&lt;input type="text" value="" id="inputA3"&gt;&lt;/td&gt; &lt;td&gt;&lt;span id="inputA3ErrMsg"/&gt;&lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" value="" id="inputA3_"&gt;&lt;/td&gt; &lt;td&gt;&lt;span id="inputA3ErrMsg_"/&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; // ... repeat all the way up to A15. &lt;tr&gt; &lt;td&gt;Label1&lt;/td&gt; &lt;td&gt;&lt;input type="text" value="" id="inputB1"&gt;&lt;/td&gt; &lt;td&gt;&lt;span id="inputB1ErrMsg"/&gt;&lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" value="" id="inputB1_"&gt;&lt;/td&gt; &lt;td&gt;&lt;span id="inputB1ErrMsg_"/&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Label1&lt;/td&gt; &lt;td&gt;&lt;input type="text" value="" id="inputB2"&gt;&lt;/td&gt; &lt;td&gt;&lt;span id="inputB2ErrMsg"/&gt;&lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" value="" id="inputB2_"&gt;&lt;/td&gt; &lt;td&gt;&lt;span id="inputB2ErrMsg"/&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; // ... so on up to E1. &lt;/table&gt; </code></pre> <p>I want my JavaScript to do three things:</p> <ul> <li><p>It takes input <code>input*5</code> and sums up it up. If it is less than 20, show the next input.</p> <ul> <li><p><code>inputA5 + inputB5 &lt; 20</code> than show input for <code>inputC*</code></p> <p>In the same way, do it for <code>input*5_</code>. If it is less than 5, show the next set of input.</p></li> <li><code>inputA5_ + inputB5_ &lt; 20</code> then show input for <code>inputC*_</code> which is <code>inputC1_</code>, <code>inputC2_</code>, <code>inputC3_</code>... else we hide it. </li> </ul></li> <li>Now if, let's say, they enter 20 for <code>inputA5</code> and 20 for <code>inputA5_</code>, then it would not only hide the input but the entire row.</li> </ul> <p>To make it easier I added <code>class = "inputTrigger"</code> to each of <code>input*5</code> and <code>inputTrigger_</code> to each of <code>input*5_</code>.</p> <p><strong>jQuery</strong></p> <pre><code>$("inputTable").on("change", "inputTrigger", function() { inputChange(this.id, indexArray.indexOf(this.id.replace("input", "").replace("5", "")); // so we can get if it is A, B, C, D }); </code></pre> <p><strong>My functions:</strong></p> <pre><code>var indexArray = { 'A', 'B', 'C', 'D', 'E'}; function getTotal(id, index) { var total = 0; var len = indexArray.length; for (var i = 0; i != len; ++i) { total += parseFloat($(input + indexArray[i] + "5").val()); } return total; } function inputChange(id,currentIndex) { var nextIndex, total, isShow, MAX_INDEX; nextIndex = +currentIndex + 1; MAX_INDEX= '5'; if (nextIndex &lt; MAX_INDEX) { total = parseFloat(getTotal(id, currentIndex)); if (nextIndex === 1) { nextIndex += 1; } isShow = (total &lt; 20.0 &amp;&amp; document.getElementById(id).value &gt; 0.0); showOrHideInput(isShow, nextIndex, resetValue); inputChange(id, nextIndex); } } function showOrHideInput(isShow, nextIndex) { var id1 = $("#input" + nextIndex + "1"); var id2 = $("#input" + nextIndex + "2"); var id10 = ..... var id1Other = $("#input" + nextIndex + "1_"); var id2Other = $("#input" + nextIndex + "2_"); var id10Other = .... if (isShow) { if (id1.length) { id1.show(); } // ... so on up to id10 } else { if (id1.length) { id1.hide(); } // .. so on up to id10 } showOrHideRows(isShow, id1, id1Other); showOrHideRows(isShow, id2, id2Other); showOrHideRows(isShow, id3, id3Other); // ... up to id10. } function showOrHideRows(isShow, id, idOther) { if (isShow) { id.closest("tr").show(); } else { if (!idOther.is(":visible")) { id.closest("tr").hide(); } } } </code></pre> <p>I know my function works but it seems really slow on IE 8 and 9, and sometimes causes a memory leak. I have analyzed the speed with <code>dynaTrace</code> and <code>showOrHideInput</code> takes over 800 ms.</p> <ol> <li>What is the fastest way to tell if a jQuery element is visible? It seems <code>is(":visible")</code> has performance hit.</li> <li>What is the best way to hide the first ancestor table row (in terms of performance)?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T15:49:24.063", "Id": "17117", "Score": "0", "body": "Often a good way to speed up jQuery code is to use less jQuery. This means being comfortable with the native API, and using it directly. For example, if you know *how* the element is being hidden, then you don't need `.is(':visible')`." } ]
[ { "body": "<p>As a general advice - use less document-wide selectors. I meant that you always selected something from entire document context: </p>\n\n<pre><code>$(input + indexArray[i] + \"5\")\n//.........\n$(\"#input\" + nextIndex + \"1\")\n</code></pre>\n\n<p>Try to narrow context - for example, assign a class to all '#inputWhatever and then</p>\n\n<pre><code>var myInputs = $(\".assignedClass\");\n$(\"#input\" + nextIndex + \"1\", myInputs);\n</code></pre>\n\n<p>The code in</p>\n\n<pre><code>if (id1.length) {\n id1.show();\n}\n</code></pre>\n\n<p>looks strange: if element length is 0, it is hidden anyway, isn't it? I'm not sure in this for all kinds of browsers... If what I suppose is true, better do:</p>\n\n<pre><code>if(isShow) {\n $(\".assignedClass\").show();\n} else {\n $(\".assignedClass\").hide();\n}\n</code></pre>\n\n<p>Other things:</p>\n\n<pre><code>if (!idOther.is(\":visible\"))\n</code></pre>\n\n<p>looks better in style as </p>\n\n<pre><code>if (idOther.is(\":hidden\")) \n</code></pre>\n\n<p>Btw, what if <code>isShow</code> is <code>false</code> and <code>!idOther.is(\":visible\"</code> is <code>false</code> too? What about <code>id</code> visibility? May it be a bug?</p>\n\n<p>If you use a lot of \"if something then show else hide\" consider <code>toggle()</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T18:26:59.530", "Id": "17120", "Score": "0", "body": "id1.length is to check if element exists or not. If it exists than id1.show() will show the element.\n\n2.) showOrHideRows deals with isShow = false.. if both are false, hide the entire row. (not just the inputs/table cell)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T17:48:24.363", "Id": "10730", "ParentId": "10727", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T15:29:14.413", "Id": "10727", "Score": "5", "Tags": [ "javascript", "jquery", "performance" ], "Title": "Conditional sum of table cells" }
10727
<p>I'm very new to backbone.js and JavaScript. I would like to hear some reasonable critiques / advice against my JavaScript code based on backbone.js framework with backbone-forms.</p> <p>The aim of this simple app is to present a user with a simple registration form (twitter bootstrap modal dialog) and upon clicking on registration button post the model to a RESTful web service.</p> <p>Model:</p> <pre><code>var MemberModel = Backbone.Model.extend({ schema: { name: { type: 'Text', title: 'Full Name', validators: [ 'required' ], editorAttrs: { 'placeholder': 'Type in your full name...', 'class':'input-xlarge' } }, email: { dataType: 'email', title: 'E-mail address', validators: [ 'required', 'email' ], editorAttrs: { 'placeholder': 'Type in your email address...', 'class':'input-xlarge' } }, country: { type: 'Select', options: [ { val: 0, label: 'Choose a country...' }, { val: 1, label: 'Country #1' }, { val: 2, label: 'Country #2' }, { val: 3, label: 'Country #3' } ], editorAttrs: { 'data-placeholder': 'Choose a country', 'class': 'input-xlarge' } } }, urlRoot: '/api/members', validate: function(attrs) { var errors = {}; if ( attrs.country == 0 ) { errors.country = 'Choose a country from list'; } if ( !_.isEmpty(errors) ) return errors; } }); </code></pre> <p>Create an instance of the model:</p> <pre><code>var member = new MemberModel(); </code></pre> <p>The View:</p> <pre><code>var MemberSignUpView = Backbone.View.extend({ name: "MemberSignUpView", model: MemberModel, el: $('#frontend'), initialize: function() { if ( ! ich['signup'] ) { ich.addTemplate('signup', 'ajax:/media/js/tpl/frontend/' + this.name + '.html?' + (Math.random() * 1000000).toString()); } }, events: { "click #wndSignupClose": "onCloseClick", "click #wndSignupSubmit": "onSubmitClick" }, onSubmitClick: function() { var errors = frmSignUp.commit(); if ( _.isEmpty(errors) ) { member.save(); } }, onCloseClick: function() { this.el.modal('hide'); this.el.remove(); this.undelegateEvents(); }, render: function() { this.el = ich.signup(); if ( typeof window.frmSignUp == "undefined" ) { window.frmSignUp = new Backbone.Form({ model: member }).render(); } $(this.el).find('.modal-body').append(window.frmSignUp.el); $(this.el).modal({ backdrop: 'static', keyboard: false }); return this; } }); </code></pre> <p>Create modal window uppon clicking on a button:</p> <pre><code>$(function() { $('#btnSignup').bind('click', function(){ var wndSignUp; if ( typeof wndSignUp == "undefined" ) { wndSignUp = new MemberSignUpView().render().el; } $('#frontend').append(wndSignUp); wndSignUp.modal('show'); }); }); </code></pre>
[]
[ { "body": "<p>It's pretty good code. Well done! There are no major mistakes or pain points that would annoy other developers. All I can do is to nitpick a little bit.</p>\n\n<ol>\n<li><p>First of all take a look at some JavaScript style guide. jQuery has <a href=\"http://docs.jquery.com/JQuery_Core_Style_Guidelines\" rel=\"nofollow noreferrer\">a good one</a> and <a href=\"http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml\" rel=\"nofollow noreferrer\">Google has a great one</a>, too. You may <a href=\"http://javascript.crockford.com/code.html\" rel=\"nofollow noreferrer\">find</a> <a href=\"http://dojotoolkit.org/community/styleGuide\" rel=\"nofollow noreferrer\">many</a> <a href=\"https://github.com/rwldrn/idiomatic.js/\" rel=\"nofollow noreferrer\">others</a> and although they all diverge a little bit there are a lot of common practices that they all agree on. One of those is braces' positioning. Instead of</p>\n\n<pre><code>render:\n function()\n {\n</code></pre>\n\n<p>you'd better use</p>\n\n<pre><code>render: function () { // note the spaces, too :)\n</code></pre></li>\n<li><p>Another point is the use of <code>===</code> instead of <code>==</code>. I've noticed that you've never used a triple-equals operator in your code and I'm a little bit nervous. Maybe you know about <a href=\"https://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use\">the one vs. the other</a> and you know what are you doing in this particular code <sub>(and btw your code works totally fine with double-equals)</sub>. But what if you don't know? And what if some other developer who doesn't know JavaScript well take a look at your code and try to do something similar? Suppose he doesn't know the rules and you code is the largest and most complicated piece of JavaScript he's ever seen. Which way of thinking do you think is more bullet-proof for a JS-newbie:</p>\n\n<blockquote>\n <p>JavaScript is somewhat weird: I have to use <code>===</code> to compare things.</p>\n</blockquote>\n\n<p>or</p>\n\n<blockquote>\n <p>JavaScript is so easy! I'll use <code>==</code> to compare stuff <em>everywhere</em> in my code!</p>\n</blockquote>\n\n<p>I guess the former is better.</p></li>\n<li><p>I noticed you use <code>.bind()</code> method for event binding. Consider switching to <a href=\"https://stackoverflow.com/questions/8065305/whats-the-difference-between-on-and-live-or-bind\">new <code>.on()</code> method introduced in jQuery 1.7</a>. One of the current goals for jQuery team is to make their library smaller and more lightweight so they work hard to cut off all the fat that's accumulated over the years. At some point in future they may remove the old API so it's better start using new API today to make your code future-proof. It''l be a lot less hassle to switch to new version of jQuery in future.</p></li>\n</ol>\n\n<p>Other than that your code is fine. I really like the fact that you use <a href=\"http://documentcloud.github.com/underscore/\" rel=\"nofollow noreferrer\">Underscore JS</a>. That saves you and other developers a lot of time and headaches.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T16:53:53.863", "Id": "18605", "Score": "1", "body": "`===` vs `==` is nitpicking, and not a pain point? JSLint and Douglas Crockford beg to differ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T09:04:07.993", "Id": "18697", "Score": "1", "body": "Here it _may_ be a nitpicking. Here: `typeof wndSignUp == \"undefined\"` - `typeof` operator always returns string. So the'll be no conversion. And here: `attrs.country == 0` the values of country are taken from `val` field in model JSON. Which is fine, too, since there is a limited set of possible labels which are safe for `==`. In general, yes, it's better to simply stick with `===` but who knows, maybe the author knows the rules and wants to save one character." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T06:54:07.753", "Id": "11585", "ParentId": "10728", "Score": "5" } }, { "body": "<p>About Backbone I could add some suggestions:</p>\n\n<ol>\n<li>Pass selector string to the <code>el</code> property — <a href=\"http://backbonejs.org/docs/backbone.html#section-140\" rel=\"nofollow\">Backbone will handle it</a>.</li>\n<li>You can change initializing block to be more \"Backbonish\":</li>\n</ol>\n\n<pre class=\"lang-js prettyprint-override\"><code>$(function() {\n $('#btnSignup').on('click', function () { \n if ( typeof wndSignUp == \"undefined\" ) {\n // Initialize view\n var wndSignUp = new MemberSignUpView({el: '#frontend'});\n // Append form and modal into DOM\n wndSignUp.render();\n }\n // Display modal to the user\n wndSignUp.showModal();\n });\n});\n</code></pre>\n\n<p>In this case render view should be changed to:</p>\n\n<pre><code>var MemberSignUpView = Backbone.View.extend({\n ...\n // el: $('#frontend'), // — don't hardcode your el, pass it into constructor as above\n ...\n frmSignUp: function() {\n return new Backbone.Form({\n model: member\n }).render();\n }\n render: function () { \n // this.el = ich.signup(); -- what is this? Do you really want to replace el?\n\n // Clear #frontend from all child nodes\n this.$el.empty();\n this.$el.append( ich.signup() );\n\n // Don't use super global variables, use it as view property instead\n // or even as local variable in render() scope\n //if ( typeof window.frmSignUp == \"undefined\" ) {\n // window.frmSignUp = new Backbone.Form({\n // model: member\n // }).render();\n //}\n\n // Backbone creates good object for you: this.$el, so don't do $(this.el)\n this.$el.find('.modal-body').append(this.frmSignUp);\n this.$el.modal({\n backdrop: 'static',\n keyboard: false\n });\n\n // return this; // Don't do this, but encapsulate logic instead\n },\n showModal: function() {\n this.$el.modal('show');\n }\n});\n</code></pre>\n\n<p>Suggested approach is valid for SLAs, but good code style and patterns are usable and readable even with small tasks.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-07T19:39:54.693", "Id": "46583", "ParentId": "10728", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T14:43:17.087", "Id": "10728", "Score": "5", "Tags": [ "javascript", "form", "backbone.js" ], "Title": "Simple registration form" }
10728
<p>I need a simple singly-linked list to help implement some memory management functionality. I just finished writing it up and would really like a code review since I haven't written this particular data structure in a long time.</p> <pre><code>struct pid_node { int PID; struct pid_node* next; }; struct pid_node* pid_node_create(int PID) { struct pid_node* new; new = kmalloc(sizeof(struct pid_node)); if (new == NULL) return NULL; new-&gt;PID = PID; new-&gt;next = NULL; return new; } void add_pid_node(struct pid_node* head, struct pid_node* new) { struct pid_node* temp; temp = head; while(temp-&gt;next != NULL) temp = temp-&gt;next; temp-&gt;next = new; } void remove_pid_node(struct pid_node* head, struct pid_node* dead) { struct pid_node* temp, other_part_of_list, delete_node; temp = head; while(temp-&gt;next != NULL) { if (temp-&gt;next == dead) { delete_node = temp-&gt;next; other_part_of_list = temp-&gt;next-&gt;next; temp-&gt;next = other_part_of_list; kfree(delete_node); //don't leak memory return; } temp = temp-&gt;next; } kprintf("Got to end of PID list, didn't remove 'dead'!\n"); } //returns true or false (1 or 0) if a particular PID is within my list int query_pid(int PID, struct pid_node* head) { struct pid_node* temp; temp = head; while(temp-&gt;next != NULL) { if (temp-&gt;PID == PID) return 1; temp = temp-&gt;next; } return 0; //didn't find it } </code></pre> <p>It doesn't have to be super fancy or anything. It just has to properly carry out the four functions.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T22:05:10.630", "Id": "17126", "Score": "1", "body": "Since you're using kmalloc, why don't you use [klist](http://isis.poly.edu/kulesh/stuff/src/klist/)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T22:17:03.763", "Id": "17127", "Score": "1", "body": "It is best to make the code compile before submitting it for review (other_part_of_list, delete_node should be pointers)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T22:20:25.210", "Id": "17128", "Score": "0", "body": "Oh shoot, I meant for them to be pid_node* variables by listing them like that (e.g. int x, y, z). Does that not work for pointers?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T00:19:03.690", "Id": "17135", "Score": "0", "body": "EDITED - added another snippet of code I'm pretty is wrong that I want to implement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T00:49:59.143", "Id": "17136", "Score": "0", "body": "@YoungMoney See my edit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T00:53:28.590", "Id": "17137", "Score": "0", "body": "Why not have the delete function return a pointer to `head`; if the head is deleted, return the new one: `if (head == dead) { newhead = head->next; kfree(head); return newhead; }` otherwise return the old head. Caller has to remember to assign head." } ]
[ { "body": "<p>General:</p>\n\n<ul>\n<li><p>Algorithm looks good. </p></li>\n<li><p>Functions normally start with the brace on column 0.</p></li>\n<li><p>Add a typedef so that you can refer to just <code>pid_node *</code>, not <code>struct\npid_node *</code>, throughout (except in the struct declaration).</p>\n\n<p>typedef struct pid_node pid_node;</p></li>\n<li><p>I usually prefer to assign an initial value to variables where they are\ndeclared (but that is just a personal preference):</p>\n\n<pre><code> pid_node* temp = head;\n ...\n</code></pre></li>\n<li><p>variables are not normally capitalized (<code>PID</code>)</p></li>\n</ul>\n\n<p>add_pid_node:</p>\n\n<ul>\n<li>what if head == NULL ?</li>\n</ul>\n\n<p>remove_pid_node</p>\n\n<ul>\n<li><p>best to put each variable definition on its own line.</p></li>\n<li><p><code>other_part_of_list</code> and <code>delete_node</code> should be pointers.</p></li>\n<li><p>what if head == NULL ?</p></li>\n<li><p><code>other_part_of_list</code> is not necessary:</p>\n\n<p><code>temp-&gt;next = temp-&gt;next-&gt;next;</code></p></li>\n</ul>\n\n<p>query_pid:</p>\n\n<ul>\n<li><p>other functions have <code>head</code> first in parameter list, but here not. Inconsistent.</p></li>\n<li><p>what if head == NULL ?</p></li>\n<li><p><code>head</code> and <code>temp</code> should be <code>const</code></p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T22:38:57.370", "Id": "17129", "Score": "0", "body": "Wow that was great! I will definitely do some revisions based on your comments. Thanks a bunch. EDIT - I guess in my head I was implicitly thinking that I would only ever call these functions when I know head is not NULL, but that's definitely not reliable/good practice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T22:37:28.543", "Id": "10732", "ParentId": "10731", "Score": "2" } }, { "body": "<p>A couple of conceptual errors:</p>\n\n<h1>Pass by value</h1>\n\n<p>You can remove the temporary copy of <code>head</code> in your functions. In C, all arguments are passed by value. This means you can operate directly on the <code>head</code> parameter exposed to your function without worrying about the argument in the calling code. Although both point to the same location, each is a different pointer variable with its own address.</p>\n\n<h1>Pointer declarations</h1>\n\n<pre><code>struct pid_node* temp, other_part_of_list, delete_node;\n</code></pre>\n\n<p>Remember that the <code>*</code> is not part of the type, but part of the declarator. A clearer way to write declarations involving pointers is to move the <code>*</code> directly in front of the identifier. This follows the C convention that \"declaration mimics use.\" So, the line changes to</p>\n\n<pre><code>struct pid_node *temp, other_part_of_list, delete_node;\n</code></pre>\n\n<p>Now the error (and fix) is obvious. If there is no <code>*</code> before a variable, its a variable of the type instead of a pointer to the type.</p>\n\n<pre><code>struct pid_node *temp, *other_part_of_list, *delete_node;\n</code></pre>\n\n<h1>Edit: remove <code>head</code> special case</h1>\n\n<p>In order to modify the <code>head</code> argument itself, which is a pointer-to-struct, you need to pass a pointer-to-pointer-to-struct or return the new <code>head</code>. For example (pointer-to-pointer-to-struct):</p>\n\n<pre><code>void remove_pid_node(struct pid_node **head, struct pid_node *dead) {\n...\n if (*head == dead) {\n temp = *head;\n *head = temp-&gt;next; \n kfree(temp);\n return; \n }\n</code></pre>\n\n<p>Then you would call the code like this:</p>\n\n<pre><code>remove_pid_node(&amp;head, head);\n</code></pre>\n\n<p>Note: don't forget to check for <code>NULL</code> arguments.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T23:17:37.973", "Id": "17130", "Score": "0", "body": "Thanks for the feedback. About the pass-by-value: I understand what you're saying. but there's nothing wrong with what I'm doing right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T23:22:32.153", "Id": "17131", "Score": "0", "body": "Depends on what you mean by wrong. Technically you can add as many extra variables you want to any function, but it decreases readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T23:44:19.147", "Id": "17132", "Score": "0", "body": "Ah, I just mean functionality-wise. It should work, yes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T23:46:37.787", "Id": "17133", "Score": "0", "body": "Yes, of course." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T00:03:24.177", "Id": "17134", "Score": "0", "body": "OK, I want to make a small addition to my remove function: a case for if the entry I want to remove is the head. I've added the code to the OP." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T00:57:15.357", "Id": "17138", "Score": "1", "body": "Regarding operating directly on `head`, using a `temp` is quite ok. The compiler will optimise this away anyway. Note that if you use `head` directly, your code becomes untruthful; variable `head` will point in sequence to all the members of the list and only at the start truly points to what its name says it points to. This could be considered wrong. Calling it something other than `head` would cure this. I have worked at places where they would code this function parameter `const struct pid_node * const head`, (extra const) which prevents such modification, but that is just silly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T01:01:49.253", "Id": "17139", "Score": "1", "body": "Wish I could give you guys more upvotes, code review is great!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T01:14:07.100", "Id": "17141", "Score": "0", "body": "@William Morris I agree that the `head` parameter deserves a better name. The primary reason I took issue with `temp`: the reflex betrays a fundamental misunderstanding." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T10:55:55.473", "Id": "17555", "Score": "0", "body": "@mteckert: The head param has a perfectly good name. It's the head of the list. The temp local variable needs a better name, but the general principle \"don't muck about with the passed in parameters just because you can\" is a good one to follow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T10:58:29.277", "Id": "17556", "Score": "0", "body": "@William: No don't rename the parameter. It documents for the caller what they should pass in. If you rename it to reflect how it is being used inside the function (as an iterator), you are leaking implementation details. What needs to happen is that `temp` needs to be more descriptively named, that is all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T14:49:29.393", "Id": "17587", "Score": "0", "body": "@JeremyP: you are right of course. To be fair I wasn't really recommending renaming, it was just an observation. I suppose there might be cases where naming the parameter (eg) `list` would be valid; for example if it were useful to pass a pointer to an arbitrary position in the list, not just the head." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T23:15:43.987", "Id": "10733", "ParentId": "10731", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T21:49:01.367", "Id": "10731", "Score": "3", "Tags": [ "algorithm", "c", "linked-list" ], "Title": "Quick linked-list implementation" }
10731
<p>I'm trying to use inheritance and polymorphism to make it easy for the program to be enhance to many more rules. <code>ClassificationRule</code> is the base class and <code>RuleFirstOccrnc</code> and <code>RuleOccrncCount</code> and derived classes and by using the same non-static <code>apply()</code> method <code>ClassificationRule</code> should invoke all other non-static <code>apply()</code> method. I'm just starting on Java and I'm not sure if I'm doing it right. Can anyone tell me if I'm using inheritance or just calling the <code>apply()</code> method? </p> <pre><code>//PrioritRule Class public class PrioritRuls { final static ArrayList&lt;ClassificationRule&gt; rulesA = new ArrayList&lt;ClassificationRule&gt;(); static{ rulesA.add( new RuleFirstOccrnc() ); rulesA.add( new RuleOccrncCount() ); } public static void prioritize( final String aUserInput ){ for (ClassificationRule rule:rulesA) rule.apply(aUserInput); } } // ClassificationRule Class - Based Class public class ClassificationRule { public void apply (final String aUserInput) { apply( aUserInput ); } } //RuleFirstOccrnc - Derived Class public class RuleFirstOccrnc extends ClassificationRule { public void apply ( final String aUserInput ) { for( TweetCat t: TwtClassif.tCat ) applyFirstOccurrenceRuleTo( t, aUserInput ); } * * * //RuleOccrncCount - Derived Class public class RuleOccrncCount extends ClassificationRule { public void apply ( final String aUserInput ) { for( TweetCat t: TwtClassif.tCat ) applyOccurrenceCountRuleTo( t, aUserInput ); } * * * </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T16:28:58.430", "Id": "18202", "Score": "1", "body": "Do yourself (and everybody else) a favor - don't use arbitrarily shortened class (or variable) names. Also, what's the point of using prefixed or suffixed variable names (`aUserInput`)? It makes it harder to tell what you're doing, without giving you any benefit." } ]
[ { "body": "<p>In your code, two classes differently extend a base class <code>ClassificationRule</code>. \nObjects of these classes are added to a list, cast as the base class. \nThey are retrieved from the list and a method, <code>apply()</code>, which is present in the base class but overridden in the child classes.\nAs you intend, the <code>apply()</code> method as present in the child class will run, not the <code>apply()</code> method from the base class. </p>\n\n<p>In the case of your code, the child class does not actually gain functionality from the base class. You are inheriting solely in order manipulate objects of different types as if they were of one homogenous type, because you know they provide certain functionality.</p>\n\n<p>In software engineering terms, you would say 'the classes implement an interface'. \nAn interface looks very much like an empty base class, like the one you wrote, and it is a Java language feature different from a base class. Implementing an interface (i.e. providing some agreed functionality) is different from inheriting functionality. </p>\n\n<p>And the code for it is different, you would write <code>public interface ClassificationRule {</code>, and <code>public class RuleFirstOccrnc implements ClassificationRule {</code>.</p>\n\n<p>In Java, you can only inherit from one class (thought that class may itself have a parent). But you can implement as many interfaces as you like. A typical java object will implement interfaces that let it be sorted (comparable), serialized to transmissable data (serializable), etc, but can only ever inherit from a single base class. \nC++ lets you inherit multiple base classes. Things go horribly wrong when you do. Or at least when I do. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T01:04:00.043", "Id": "10736", "ParentId": "10735", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T00:35:00.310", "Id": "10735", "Score": "4", "Tags": [ "java" ], "Title": "Using inheritance and polymorphism in Java" }
10735
<p>What can I do with this program to improve its performance?</p> <pre><code>#!/usr/bin/env ruby require 'open-uri' print "URL: " add = gets puts "Info from #{add}" begin open(add) do |f| puts "Fetching images..." puts "Fetching links..." puts "Fetching div tags..." puts "Fetching headers..." puts "Fetching forms..." puts "Processing..." img = f.read.scan(/&lt;img/).length puts "\t#{img} images" f.close end open(add) do |f| links = f.read.scan(/&lt;a/).length puts "\t#{links} links" f.close end open(add) do |f| div = f.read.scan(/&lt;div/).length puts "\t#{div} div tags" f.close end open(add) do |f| head = f.read.scan(/&lt;h1/).length puts "\t#{head} 'h1 type' headers" f.close end open(add) do |f| form = f.read.scan(/&lt;form/).length puts "\t#{form} forms" f.close end rescue puts "An error occured, either you entered an invalid URL or your internet connection is messed up!" end </code></pre>
[]
[ { "body": "<p>Instead of opening, reading and closing the file all the time, you should read it once and then just use the string multiple times (this will also safe time and bandwidth).</p>\n\n<pre><code>img = f.read.scan(/&lt;img/).length\n</code></pre>\n\n<p>This won't necessarily give you an accurate count of <code>&lt;img&gt;</code> tags. For example it will also count occurrences of <code>&lt;img</code> that appear in comments or in scripts. If you want an accurate count, you should use an HTML parsing library. (Same applies to when you do the same thing to the other tags of course).</p>\n\n<p>Also, as helpfully pointed out by Christopher Creutzig, in case of the a-tag your regex will also count <code>&lt;address</code> tags or anything else that starts with <code>a</code> (and if there should ever be HTML tags whose name start with <code>div</code> or <code>h1</code> etc., those will be miscounted as well). This can be fixed by adding a <code>\\b</code> after the tag as Christopher suggested (so that the tag name can't be followed by another word-character). Using a proper HTML parsing library is still your best option though.</p>\n\n<pre><code>f.close\n</code></pre>\n\n<p>No need to close the stream when using <code>open</code> with a block. The stream will be closed automatically when the block ends.</p>\n\n<hr>\n\n<p>I'd also recommend to put the tag-counting code into a method. This way you don't need to repeat the same code for each tag.</p>\n\n<p>If you're okay with changing the output, so that it's uniform for all tags, you might even turn the whole thing into a loop, so there's no repetition at all. Something like this:</p>\n\n<pre><code>%w(img a div h1 form).each do |tag|\n count = contents.scan(/&lt;#{tag}\\b/).length\n puts \"\\t#{count} #{tag} tags\"\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T17:33:35.787", "Id": "17158", "Score": "2", "body": "And for good measure, make that `/<#{tag}\\b/` so `<address>` is not counted as an `a` tag." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T03:41:56.620", "Id": "10741", "ParentId": "10737", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T03:26:41.427", "Id": "10737", "Score": "6", "Tags": [ "ruby", "html" ], "Title": "HTML tag counter" }
10737
<p>After a whole night of work I finally have my first useful class - for reading database.</p> <p>It works like a charm, but if you got a moment, please take a glance and give me feedback. Harsh criticism welcome.</p> <p>Please note that security is not addressed yet, as well as usual SQL clauses, but I'd like to know am I on the right way to writing better software. </p> <p>Here it is:</p> <pre><code>class DatabaseRead { protected $dbh; // Database handle connection public $columns = array(); // Columns to be read public $table; // Table to be read from public $resultSet = array(); // Returned results public function __construct( $dbh, $columns, $table ) { $this-&gt;dbh = $dbh; $this-&gt;columns = $columns; $this-&gt;column = ''; $this-&gt;table = $table; $this-&gt;resultSet = array(); $read_database = $this-&gt;dbh-&gt;query('SELECT ' . implode(',' , $this-&gt;columns) . ' FROM ' . $this-&gt;table); while ($row = $read_database-&gt;fetch()) { foreach($this-&gt;columns as $this-&gt;column) { $this-&gt;resultSet[$this-&gt;column] = $row[$this-&gt;column]; } } return $this-&gt;resultSet; } </code></pre> <p>}</p> <p>Have I wrote an actual class that makes sense, or just a glorified function?</p> <p>Thanks.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T03:32:59.877", "Id": "17142", "Score": "6", "body": "You can't return a value from a constructor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T09:22:34.380", "Id": "17145", "Score": "0", "body": "Add to @Corbin note: Because the constructor is there only for initialization of class variables, nothing more." } ]
[ { "body": "<p>Why don't you split the \"constructor\" part and the \"get the values\" part?</p>\n\n<p><strong>Code :</strong></p>\n\n<pre><code>class Database {\n\n protected $dbh; // Database handle connection\n\n public function __construct( $dbh) {\n $this-&gt;dbh = $dbh;\n }\n\n public function getResults($columns,$table)\n {\n $resultSet = array();\n\n $read_database = $this-&gt;dbh-&gt;query('SELECT ' . implode(',' , $columns) . ' FROM ' . $table);\n while ($row = $read_database-&gt;fetch()) { \n foreach($columns as $column) {\n $resultSet[$column] = $row[$column];\n }\n }\n return $resultSet;\n }\n}\n</code></pre>\n\n<p><strong>Usage :</strong></p>\n\n<pre><code>$db = new Database($dbh);\n$db-&gt;getResults($columns, $table);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T03:32:30.373", "Id": "10740", "ParentId": "10738", "Score": "4" } }, { "body": "<p>Some time ago, I had the same problem than you, wanting to create an useful and secure database handling class.</p>\n\n<p>In your case, there are some flaws in its design:</p>\n\n<ol>\n<li>Constructors are <strong>only</strong> for initializing class instance, not for doing anything else.</li>\n<li>Your class is <strong>too</strong> specific, only allowing to perform one single action, which is not too useful because in that case you'd need X different classes for your X different needs (queries) which is not the goal for a class.</li>\n<li>Also, as you pointed, there is nothing about security there, which can be very hard to implement if you start to use a model like that in your project (I mean, several changes later in several files, etc...).</li>\n<li>Your class seems not scalable nor reusable, which will make you work more rather than work less by allowing you to reuse code (which is one of the goals of OO).</li>\n</ol>\n\n<p>So what I'd recommend you to do is the following (now you are on time to do so without side effects in your project, and a class that could be reusable):</p>\n\n<ol>\n<li>Create an abstract class for handling a generic database, with configurable parameters, such as host, username, dbname that will be initialized in constructor (in a class you inherit from this one)</li>\n<li>Create class functions to execute SQL:\n<ol>\n<li>Run SQL queries</li>\n<li>Prepare prepared statements</li>\n<li>Execute prepared statements </li>\n<li>Connect/disconnect</li>\n</ol></li>\n</ol>\n\n<p>Once done that, you have a reusable class for everytime you want to access a database in every project you may have in a future.</p>\n\n<p>After that, just create a new class inheriting from this one (one per database you use (what means in practice one per project you have).\nThis new class should be database specific (having the parameters to connect to database, preparing statements you will need and so on) rather than general, but reusing all its base code.</p>\n\n<p>I have made something similar in the past I posted in my blog (will provide link rather than include it here because it is too long), you are welcome to use it as you like: <a href=\"http://stormbyte.blogspot.com.es/2011/03/mysqls-prepared-statements-made-really.html\" rel=\"nofollow\">http://stormbyte.blogspot.com.es/2011/03/mysqls-prepared-statements-made-really.html</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T15:24:31.760", "Id": "29353", "Score": "0", "body": "I would also add some other functionality that will be important down the road: getting the rowcount (# of affected rows from an UPDATE/INSERT statement) as well as grabbing the last insert ID." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T13:48:44.900", "Id": "29563", "Score": "0", "body": "That is already implemented in the class I propose in the link provided :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T07:10:54.090", "Id": "10742", "ParentId": "10738", "Score": "4" } }, { "body": "<p>If you wan't to write more bug-free, secure and extensible applications with highly reusable code, try to focus more on OOP.</p>\n\n<p>So for example such class as DatabaseRead should always return object (Entity) not array. Why? Bacause you can then do much better validation of its data. So for example it returns instance of class Article. Article has no public properties, only getters and setters. This will grant you, that (if well written) $article->getTitle() will allways return string.</p>\n\n<p>You can then reuse the class Article in administration, so Admin will always create the Article correctly.</p>\n\n<p>You can then use type-hinting through your application as well, which will provide you with certainty, that the parameter which was passed to method is really an Article, not some uknown array (which could be in inconsistent state).</p>\n\n<pre><code>function foo(Article $article) {\n // we are now sure that we work with valid data of article\n $title = $article-&gt;getTitle();\n}\n</code></pre>\n\n<p>As a showcase, have a look at this example:\n<a href=\"https://github.com/Dundee/testing-showcase/blob/master/app/models/ArticleRepositorySqlite.php\" rel=\"nofollow\">https://github.com/Dundee/testing-showcase/blob/master/app/models/ArticleRepositorySqlite.php</a></p>\n\n<p>This class (ArticleRepository) has one responsibulity (see Single Responsibility Principle): the persistence of an Article. Class Article doesn't know about persitence at all. Bacause of this we can have multiple repository instances, which stores Article on different medium (memory, database, filesystem).</p>\n\n<p>The concrete class ArticleRepositorySqlite uses some DB framework, but this is not always neccessary. The class could take PDO connection in constructor and execute ordinary SQL queries as well.</p>\n\n<p>Hope it's understandable :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T17:49:27.370", "Id": "17161", "Score": "0", "body": "Yes, I sort of get the basic idea, but am yet to understand practical implementation. Thanks for the link, will definitely dive more into this. +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T18:03:11.050", "Id": "17162", "Score": "0", "body": "PS.@Daniel Milde: Other than that, do you think I'm on a good way, does it make sense creating class like the one above?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T12:54:16.813", "Id": "19462", "Score": "0", "body": "I think there is quite a lot of such database layers, so there is probably not needed to write our own. Try look on Doctrine 2, NotOrm, Dibi etc." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T16:05:20.163", "Id": "10753", "ParentId": "10738", "Score": "2" } }, { "body": "<p>Unfortunately this is not the path to follow, Rather than focusing on DataBase level read and write classes etc. consider higher concepts, the best you can get out of this approach is the right OO way of doing a wrong thing.</p>\n\n<p>What you want to research is design patterns and more specifically Patterns of Enterprise Application Architecture, Active Record, Business Objects, Repository pattern Design etc. Also lookup ORM. That would give you a better idea of what type of classes that you should focus on.</p>\n\n<p>Getting the deisgn and implementation of this DataTable read class will take further away from the right approach.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T05:09:46.667", "Id": "10770", "ParentId": "10738", "Score": "1" } } ]
{ "AcceptedAnswerId": "10770", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T03:24:34.527", "Id": "10738", "Score": "3", "Tags": [ "php", "object-oriented" ], "Title": "PHP OOP - Does this database reading class make sense?" }
10738
<p>I used this code in several projects. But I am not sure if it is stable. However on production it is working well, but I want to listen your advices:</p> <pre><code>/// &lt;summary&gt; /// Standard abstract parent for Timer-powered classes. Has Start|Stop|Pulse events /// &lt;/summary&gt; public abstract class TimerContainer : IDisposable { protected Timer Timer { get; set; } protected TimeSpan Interval { get; set; } protected TimerContainer() : this(TimeSpan.FromSeconds(1)) { } protected TimerContainer(TimeSpan interval) { Status = TimerStatus.NotInitialized; Timer = new Timer(OnTick, null, Timeout.Infinite, Timeout.Infinite); Interval = interval; } protected abstract void OnTick(object sender); #region Standard Events public event EventHandler OnStart; public event EventHandler OnStop; public event EventHandler OnPulse; public TimerStatus Status { get; protected set; } public void Start() { Timer.Change(TimeSpan.Zero, Interval); Status = TimerStatus.Running; if (OnStart != null) { OnStart(this, new EventArgs()); } } public void Stop() { Status = TimerStatus.Stopped; Timer.Change(Timeout.Infinite, Timeout.Infinite); if (OnStop != null) { OnStop(this, new EventArgs()); } } protected void InvokePulse() { if (OnPulse != null) { OnPulse(this, new EventArgs()); } } #region IDisposable Members protected bool disposed = false; ~TimerContainer() { Dispose(false); } public virtual void Dispose() { if (!disposed) { Dispose(true); GC.SuppressFinalize(this); disposed = true; } } protected virtual void Dispose(bool disposing) { if (disposing) { if (Status != TimerStatus.Stopped) { Stop(); } if (Timer != null) { Timer.Dispose(); Timer = null; } } } #endregion #endregion } /// &lt;summary&gt; /// Timer status /// &lt;/summary&gt; public enum TimerStatus { NotInitialized = 0, Running = 1, Stopped = 2 } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T13:00:42.787", "Id": "17200", "Score": "0", "body": "Hi Orif, i loved your code and i wonder, for what the use of OnPulse ? should the derived class put the InvokePulse be in OnTick ?" } ]
[ { "body": "<p>One thing is that the way you're calling the events is not thread-safe:</p>\n\n<pre><code>if (OnStop != null) {\n OnStop(this, new EventArgs());\n}\n</code></pre>\n\n<p>If the only subscriber to the event unsubscribes between the <code>null</code> check and the invoke, you will get a <code>NullReferenceException</code>. The correct way is like this:</p>\n\n<pre><code>var onStop = OnStop;\nif (onStop != null) {\n onStop(this, new EventArgs());\n}\n</code></pre>\n\n<p>Or, alternatively, you can make sure that the events are never <code>null</code> by adding a subscriber that does nothing:</p>\n\n<pre><code>public event EventHandler OnStart = delegate { };\n</code></pre>\n\n<p>That way, you don't have to check for <code>null</code> at all. This could hurt performance a bit, but it shouldn't be noticeable (especially since the events most likely won't be invoked more frequently than once every few milliseconds).</p>\n\n<p>Another thing is that your finalizer is completely useless, since you don't have any unmanaged resources. It could make sense if some of the children of this class did have some unmanaged resources, but I think those could have their own fianlizer.</p>\n\n<p>Also, in the usual <code>Dispose()</code> pattern, the parameterless <code>Dispose()</code> method is not <code>virtual</code>. I don't see any reason for it here, having <code>virtual Dispose(bool)</code> should be enough.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T14:28:37.570", "Id": "17154", "Score": "0", "body": "Tips about null check and virtual Dispose() is great. But I am not sure on removing Dispose. Anyway, I marked your post as an answer. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T14:43:52.037", "Id": "17155", "Score": "0", "body": "I didn't say anything about removing `Dispose()`. I meant the finalizer: `~TimerContainer()`. If that's what you meant, why aren't you sure about it?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T11:54:04.823", "Id": "10745", "ParentId": "10744", "Score": "2" } } ]
{ "AcceptedAnswerId": "10745", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T11:16:58.363", "Id": "10744", "Score": "1", "Tags": [ "c#", "multithreading", "timer" ], "Title": "Timer wrapper review" }
10744
<p><a href="https://github.com/asimihsan/crypto_example" rel="nofollow noreferrer">Python Cryptography Example</a></p> <p>Last weekend I wrote some code to help people use <a href="https://www.dlitz.net/software/pycrypto/" rel="nofollow noreferrer">PyCrypto</a> in a canonical fashion to symmetrically encrypt and decrypt strings and files. By canonical I mean I've followed Colin Percival's advice in <a href="http://www.daemonology.net/blog/2009-06-11-cryptographic-right-answers.html" rel="nofollow noreferrer">Cryptographic Right Answers</a>.</p> <p>The code isn't very verbose, and I'd appreciate any comments or questions about the code, the tests, and the documentation. After I get this review I'm going to submit this to <a href="https://security.stackexchange.com/">Security Stack Exchange</a> for a design review.</p> <p>Source code and a subset of tests follow:</p> <p>crypto.py:</p> <pre><code># --------------------------------------------------------------------------- # Copyright (c) 2012 Asim Ihsan (asim dot ihsan at gmail dot com) # Distributed under the MIT/X11 software license, see the accompanying # file license.txt or http://www.opensource.org/licenses/mit-license.php. # --------------------------------------------------------------------------- import os import sys import struct import cStringIO as StringIO import bz2 from Crypto.Cipher import AES from Crypto.Hash import SHA256, HMAC from Crypto.Protocol.KDF import PBKDF2 # ---------------------------------------------------------------------------- # Constants. # ---------------------------------------------------------------------------- # Length of salts in bytes. salt_length_in_bytes = 16 # Hash function to use in general. hash_function = SHA256 # PBKDF pseudo-random function. Used to mix a password and a salt. # See Crypto\Protocol\KDF.py pbkdf2_prf = lambda p, s: HMAC.new(p, s, hash_function).digest() # PBKDF count, number of iterations. pbkdf2_count = 1000 # PBKDF derived key length. pbkdf2_dk_len = 32 # ---------------------------------------------------------------------------- class HMACIsNotValidException(Exception): pass class InvalidFormatException(Exception): def __init__(self, reason): self.reason = reason def __str__(self): return repr(self.reason) class CTRCounter: """ Callable class that returns an iterating counter for PyCrypto AES in CTR mode.""" def __init__(self, nonce): """ Initialize the counter object. @nonce An 8-byte binary string. """ assert(len(nonce)==8) self.nonce = nonce self.cnt = 0 def __call__(self): """ Return the next 16 byte counter, as a binary string. """ right_half = struct.pack('&gt;Q', self.cnt) self.cnt += 1 return self.nonce + right_half def encrypt_string(plaintext, key, compress=False): plaintext_obj = StringIO.StringIO(plaintext) ciphertext_obj = StringIO.StringIO() encrypt_file(plaintext_obj, key, ciphertext_obj, compress=compress) return ciphertext_obj.getvalue() def decrypt_string(ciphertext, key): plaintext_obj = StringIO.StringIO() ciphertext_obj = StringIO.StringIO(ciphertext) decrypt_file(ciphertext_obj, key, plaintext_obj) return plaintext_obj.getvalue() def decrypt_file(ciphertext_file_obj, key, plaintext_file_obj, chunk_size=4096): # ------------------------------------------------------------------------ # Unpack the header values from the ciphertext. # ------------------------------------------------------------------------ header_format = "&gt;HHHHHQ?H" header_size = struct.calcsize(header_format) header_string = ciphertext_file_obj.read(header_size) try: header = struct.unpack(header_format, header_string) except struct.error: raise InvalidFormatException("Header is invalid.") pbkdf2_count = header[0] pbkdf2_dk_len = header[1] password_salt_size = header[2] nonce_size = header[3] hmac_salt_size = header[4] ciphertext_size = header[5] compress = header[6] hmac_size = header[7] # ------------------------------------------------------------------------ # Unpack everything except the ciphertext and HMAC, which are the # last two strings in the ciphertext file. # ------------------------------------------------------------------------ encrypted_string_format = ''.join(["&gt;", "%ss" % (password_salt_size, ) , "%ss" % (nonce_size, ), "%ss" % (hmac_salt_size, )]) encrypted_string_size = struct.calcsize(encrypted_string_format) body_string = ciphertext_file_obj.read(encrypted_string_size) try: body = struct.unpack(encrypted_string_format, body_string) except struct.error: raise InvalidFormatException("Start of body is invalid.") password_salt = body[0] nonce = body[1] hmac_salt = body[2] # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # Prepare the HMAC with everything except the ciphertext. # # Notice we do not HMAC the ciphertext_size, just like the encrypt # stage. # ------------------------------------------------------------------------ hmac_password_derived = PBKDF2(password = key, salt = hmac_salt, dkLen = pbkdf2_dk_len, count = pbkdf2_count, prf = pbkdf2_prf) elems_to_hmac = [str(pbkdf2_count), str(pbkdf2_dk_len), str(len(password_salt)), password_salt, str(len(nonce)), nonce, str(len(hmac_salt)), hmac_salt] hmac_object = HMAC.new(key = hmac_password_derived, msg = ''.join(elems_to_hmac), digestmod = hash_function) # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # First pass: stream in the ciphertext object into the HMAC object # and verify that the HMAC is correct. # # Notice we don't need to decompress anything here even if compression # is in use. We're using Encrypt-Then-MAC. # ------------------------------------------------------------------------ ciphertext_file_pos = ciphertext_file_obj.tell() ciphertext_bytes_read = 0 while True: bytes_remaining = ciphertext_size - ciphertext_bytes_read current_chunk_size = min(bytes_remaining, chunk_size) ciphertext_chunk = ciphertext_file_obj.read(current_chunk_size) if ciphertext_chunk == '': break ciphertext_bytes_read += len(ciphertext_chunk) hmac_object.update(ciphertext_chunk) if ciphertext_bytes_read != ciphertext_size: raise InvalidFormatException("first pass ciphertext_bytes_read %s != ciphertext_size %s" % (ciphertext_bytes_read, ciphertext_size)) # the rest of the file is the HMAC. hmac = ciphertext_file_obj.read() if len(hmac) != hmac_size: raise InvalidFormatException("len(hmac) %s != hmac_size %s" % (len(hmac), hmac_size)) hmac_calculated = hmac_object.digest() if hmac != hmac_calculated: raise HMACIsNotValidException # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # Second pass: stream in the ciphertext object and decrypt it into the # plaintext object. # ------------------------------------------------------------------------ cipher_password_derived = PBKDF2(password = key, salt = password_salt, dkLen = pbkdf2_dk_len, count = pbkdf2_count, prf = pbkdf2_prf) cipher_ctr = AES.new(key = cipher_password_derived, mode = AES.MODE_CTR, counter = CTRCounter(nonce)) ciphertext_file_obj.seek(ciphertext_file_pos, os.SEEK_SET) ciphertext_bytes_read = 0 if compress: decompressor = bz2.BZ2Decompressor() while True: bytes_remaining = ciphertext_size - ciphertext_bytes_read current_chunk_size = min(bytes_remaining, chunk_size) ciphertext_chunk = ciphertext_file_obj.read(current_chunk_size) end_of_file = ciphertext_chunk == '' ciphertext_bytes_read += len(ciphertext_chunk) plaintext_chunk = cipher_ctr.decrypt(ciphertext_chunk) if compress: try: decompressed = decompressor.decompress(plaintext_chunk) except EOFError: decompressed = "" plaintext_chunk = decompressed plaintext_file_obj.write(plaintext_chunk) if end_of_file: break if ciphertext_bytes_read != ciphertext_size: raise InvalidFormatException("second pass ciphertext_bytes_read %s != ciphertext_size %s" % (ciphertext_bytes_read, ciphertext_size)) # ------------------------------------------------------------------------ def encrypt_file(plaintext_file_obj, key, ciphertext_file_obj, chunk_size = 4096, compress = False): # ------------------------------------------------------------------------ # Prepare input key. # ------------------------------------------------------------------------ password_salt = os.urandom(salt_length_in_bytes) cipher_password_derived = PBKDF2(password = key, salt = password_salt, dkLen = pbkdf2_dk_len, count = pbkdf2_count, prf = pbkdf2_prf) # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # Prepare cipher object. # ------------------------------------------------------------------------ nonce_size = 8 nonce = os.urandom(nonce_size) cipher_ctr = AES.new(key = cipher_password_derived, mode = AES.MODE_CTR, counter = CTRCounter(nonce)) # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # Prepare HMAC object, and hash what we have so far. # # Notice that we do not HMAC the size of the ciphertext. We don't # know how big it'll be until we compress it, if we do, and we can't # compress it without reading it into memory. So let the HMAC of # the ciphertext itself do. # ------------------------------------------------------------------------ hmac_salt = os.urandom(salt_length_in_bytes) hmac_password_derived = PBKDF2(password = key, salt = hmac_salt, dkLen = pbkdf2_dk_len, count = pbkdf2_count, prf = pbkdf2_prf) elems_to_hmac = [str(pbkdf2_count), str(pbkdf2_dk_len), str(len(password_salt)), password_salt, str(len(nonce)), nonce, str(len(hmac_salt)), hmac_salt] hmac_object = HMAC.new(key = hmac_password_derived, msg = ''.join(elems_to_hmac), digestmod = hash_function) # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # Write in what we have so far into the output, ciphertext file. # # Given that the plaintext may be compressed we don't know what # it's final length will be without compressing it, and we can't # do this without reading it all into memory. Hence let's # put 0 as the ciphertext length for now and fill it in after. # ------------------------------------------------------------------------ header_format = ''.join(["&gt;", "H", # PBKDF2 count "H", # PBKDF2 derived key length "H", # Length of password salt "H", # Length of CTR nonce "H", # Length of HMAC salt "Q", # Length of ciphertext "?", # Is compression used? "H", # Length of HMAC "%ss" % (len(password_salt), ) , # Password salt "%ss" % (nonce_size, ), # CTR nonce "%ss" % (len(hmac_salt), )]) # HMAC salt header = struct.pack(header_format, pbkdf2_count, pbkdf2_dk_len, len(password_salt), len(nonce), len(hmac_salt), 0, # This is the ciphertext size, wrong for now. compress, hmac_object.digest_size, password_salt, nonce, hmac_salt) ciphertext_file_obj.write(header) # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # Stream in the input file and stream out ciphertext into the # ciphertext file. # ------------------------------------------------------------------------ ciphertext_size = 0 if compress: compressor = bz2.BZ2Compressor() while True: plaintext_chunk = plaintext_file_obj.read(chunk_size) end_of_file = plaintext_chunk == '' if compress: if end_of_file: compressed = compressor.flush() else: compressed = compressor.compress(plaintext_chunk) plaintext_chunk = compressed ciphertext_chunk = cipher_ctr.encrypt(plaintext_chunk) ciphertext_size += len(ciphertext_chunk) ciphertext_file_obj.write(ciphertext_chunk) hmac_object.update(ciphertext_chunk) if end_of_file: break # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # Write the HMAC to the ciphertext file. # ------------------------------------------------------------------------ hmac = hmac_object.digest() ciphertext_file_obj.write(hmac) # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # Go back to the header and update the ciphertext size. # # Notice that we capture the header such that the last unpacked # element of the struct is the unsigned long long of the ciphertext # length. # ------------------------------------------------------------------------ # Read in. ciphertext_file_obj.seek(0, os.SEEK_SET) header_format = "&gt;HHHHHQ" header_size = struct.calcsize(header_format) header = ciphertext_file_obj.read(header_size) # Modify. header_elems = list(struct.unpack(header_format, header)) header_elems[-1] = ciphertext_size # Write out. header = struct.pack(header_format, *header_elems) ciphertext_file_obj.seek(0, os.SEEK_SET) ciphertext_file_obj.write(header) # ------------------------------------------------------------------------ </code></pre> <p>test_crypto.py:</p> <pre><code>#!/usr/bin/env python2.7 # --------------------------------------------------------------------------- # Copyright (c) 2012 Asim Ihsan (asim dot ihsan at gmail dot com) # Distributed under the MIT/X11 software license, see the accompanying # file license.txt or http://www.opensource.org/licenses/mit-license.php. # --------------------------------------------------------------------------- import os import sys import tempfile import cStringIO as StringIO src_path = os.path.abspath(os.path.join(__file__, os.pardir, os.pardir, "src")) assert(os.path.isdir(src_path)) sys.path.append(src_path) from utilities import crypto from nose.tools import raises, assert_false, assert_true, assert_not_equal, assert_equal, assert_less from nose.plugins.skip import SkipTest, Skip _multiprocess_can_split_ = True def test_encrypt_then_decrypt_string(): plaintext = "this is some text" key = "this is my key" ciphertext = crypto.encrypt_string(plaintext, key) plaintext_after = crypto.decrypt_string(ciphertext, key) assert_equal(plaintext_after, plaintext) @raises(crypto.HMACIsNotValidException) def test_encrypt_then_alter_raises_exception(): plaintext = "this is some text" key = "this is my key" ciphertext = crypto.encrypt_string(plaintext, key) ciphertext = ciphertext[:-len(plaintext)] + '\0' * len(plaintext) plaintext_after = crypto.decrypt_string(ciphertext, key) @raises(crypto.InvalidFormatException) def test_decrypt_then_damage_raises_exception(): plaintext = "this is some text" key = "this is my key" ciphertext = crypto.encrypt_string(plaintext, key) ciphertext = ciphertext[:len(ciphertext)-5] plaintext_after = crypto.decrypt_string(ciphertext, key) @raises(crypto.HMACIsNotValidException) def test_decrypt_with_wrong_password_raises_exception(): plaintext = "this is some text" key = "this is my key" ciphertext = crypto.encrypt_string(plaintext, key) another_key = "this is my key 2" plaintext_after = crypto.decrypt_string(ciphertext, another_key) def test_encrypt_then_decrypt_empty_string(): plaintext = "" key = "this is my key" ciphertext = crypto.encrypt_string(plaintext, key) plaintext_after = crypto.decrypt_string(ciphertext, key) assert_equal(plaintext_after, plaintext) def test_compressed_encrypt_then_decrypt_string(): plaintext = "X" * 4096 key = "this is my key" ciphertext = crypto.encrypt_string(plaintext, key, compress=True) assert_less(len(ciphertext), len(plaintext) / 10) plaintext_after = crypto.decrypt_string(ciphertext, key) assert_equal(plaintext, plaintext_after) def test_compressed_encrypt_then_decrypt_random_string(): plaintext = os.urandom(1024 * 1024) key = "this is my key" ciphertext = crypto.encrypt_string(plaintext, key, compress=True) plaintext_after = crypto.decrypt_string(ciphertext, key) assert_equal(plaintext, plaintext_after) def _test_encrypt_then_decrypt_file(plaintext_size, chunk_size, wrong_password=False, alter_file=False, truncate_header=False, truncate_body=False, compress=False): tempfile.tempdir = os.path.join(__file__, os.pardir) plaintext_file = tempfile.NamedTemporaryFile(delete=False) ciphertext_file = tempfile.NamedTemporaryFile(delete=False) plaintext_after_file = tempfile.NamedTemporaryFile(delete=False) plaintext_filepath = plaintext_file.name ciphertext_filepath = ciphertext_file.name plaintext_after_filepath = plaintext_after_file.name plaintext_file.close() ciphertext_file.close() plaintext_after_file.close() try: key = "this is my key" # -------------------------------------------------------------------- # Write plaintext to file. # -------------------------------------------------------------------- with open(plaintext_filepath, "wb") as f: cnt = 0 while cnt &lt; plaintext_size: current_chunk_size = min(4096, plaintext_size - cnt) f.write("X" * current_chunk_size) cnt += current_chunk_size # -------------------------------------------------------------------- # -------------------------------------------------------------------- # Encrypt plaintext file to ciphertext file. # # Notice that the output, ciphertext file requires read and # write access. # -------------------------------------------------------------------- with open(plaintext_filepath, "rb") as f_in: with open(ciphertext_filepath, "rb+") as f_out: crypto.encrypt_file(f_in, key, f_out, chunk_size=chunk_size, compress=compress) # -------------------------------------------------------------------- # -------------------------------------------------------------------- # If wrong password then let's adjust the password. # -------------------------------------------------------------------- if wrong_password: key = "this is my key 2" # -------------------------------------------------------------------- # -------------------------------------------------------------------- # If alter file then let's alter the file. # If truncate_body then let's skip the last ten bytes from the # file. # If truncate_header then let's skip the first ten bytes from the # file. # -------------------------------------------------------------------- if alter_file: with open(ciphertext_filepath, "rb+") as f: f.seek(-10, os.SEEK_END) f.write('\0' * 10) if truncate_header or truncate_body: with open(ciphertext_filepath, "rb") as f: contents = f.read() if truncate_header: with open(ciphertext_filepath, "wb") as f: f.write(contents[10:]) else: with open(ciphertext_filepath, "wb") as f: f.write(contents[:-10]) # -------------------------------------------------------------------- # -------------------------------------------------------------------- # Decrypt ciphertext file to another plaintext file. # -------------------------------------------------------------------- with open(ciphertext_filepath, "rb") as f_in: with open(plaintext_after_filepath, "wb") as f_out: crypto.decrypt_file(f_in, key, f_out, chunk_size=chunk_size) # -------------------------------------------------------------------- with open(plaintext_filepath, "rb") as f_original: with open(plaintext_after_filepath, "rb") as f_after: while True: f_original_chunk = f_original.read(chunk_size) f_after_chunk = f_after.read(chunk_size) assert_equal(f_original_chunk, f_after_chunk) if f_original_chunk == '': break finally: for (file_obj, filepath) in [(plaintext_file, plaintext_filepath), (ciphertext_file, ciphertext_filepath), (plaintext_after_file, plaintext_after_filepath)]: os.remove(filepath) def test_encrypt_then_decrypt_file_normal(): _test_encrypt_then_decrypt_file(plaintext_size = 17, chunk_size = 4096) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T22:14:03.573", "Id": "32960", "Score": "0", "body": "I think lining up code (like the parameters of `_test_encrypt_then_decrypt_file`) is not good, because it get's out of sync quickly. I don't know about the encryption, but I know that the function `decrypt_file` is far too long. You should split it up in multiple functions and maybie create a class for some parts of your code." } ]
[ { "body": "<p>Well then, I guess no one is stepping up to review the code! I've been thinking it over and reading over the code and tests a few times and have come up with the following review comments. These comments apply to the git branch at <a href=\"https://github.com/asimihsan/crypto_example/commit/655694e0bea974813d2252a54e69478e272b1d1e\" rel=\"nofollow\">commit 655694e</a>.</p>\n\n<ul>\n<li><a href=\"https://github.com/asimihsan/crypto_example/blob/master/src/utilities/crypto.py#L171\" rel=\"nofollow\">crypto.py line 171</a> compares the calculated HMAC with the correct HMAC using a linear-time comparison operator. This leaks potentially useful information via a timing attack if this function is used as part of a web service. Fix is to use Nate Lawson's constant-time comparison function, <a href=\"http://codahale.com/a-lesson-in-timing-attacks/\" rel=\"nofollow\">described by Coda Hale here</a>.</li>\n<li><a href=\"https://github.com/asimihsan/crypto_example/blob/master/src/utilities/crypto.py#L39\" rel=\"nofollow\">crypto.py lines 39 and 42</a>. All different exceptions thrown by this library should derive from a base \"BaseCryptoException\". This allows callers to catch the base exception, in cases where they don't care why the decryption failed.</li>\n<li><a href=\"https://github.com/asimihsan/crypto_example/blob/master/src/utilities/crypto.py#L211\" rel=\"nofollow\">crypto.py line 211</a>. Why is the PBKDF2 iteration count (1000) hard-coded? I agree the caller maybe shouldn't be allowed to modify this, because we want to simply the API. But we may need to increase this number depending on the speed of the machine in use. Automatically determining a constant to use also seems too complicated. I suggest allowing the caller to set a value, with it set to 1000 by default. You'll also want to pack this as an unsigned integer (\"I\") rather than an unsigned short (\"H\") in order to allow > 65535 values.</li>\n<li><a href=\"https://github.com/asimihsan/crypto_example/blob/master/test/test_crypto.py#L31\" rel=\"nofollow\">test_crypto.py lines 31 and 39</a>. Damaging the ciphertext payload and then attempting decryption needs to be more comprehensive. I suggest testing that strings that have a bit-wise <a href=\"http://en.wikipedia.org/wiki/Levenshtein_distance\" rel=\"nofollow\">Levenshtein edit distance</a> of one (i.e. all strings with one bit added, removed, or toggled) fail decryption either because the format is wrong or because the HMAC fails.</li>\n</ul>\n\n<p>If anyone has anything else to add please let me know, thanks.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-05T16:07:21.880", "Id": "208827", "Score": "0", "body": "I'd rather say *variable-time* instead of *linear-time*." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T13:14:32.663", "Id": "10784", "ParentId": "10746", "Score": "3" } }, { "body": "<p>Some thoughts -- mostly stylistic. I'm not qualified to comment on the crypto stuff!</p>\n\n<ul>\n<li><p>I'm not sure why you need to have a package called <code>utilities</code>, given that it just contains a single file. <code>utilities</code> is a pretty common name. Perhaps you could just have a module called <code>crypto_utils</code> or something.</p></li>\n<li><p>You don't need to define <code>__init__</code> and <code>__str__</code> for <code>InvalidFormatException</code> -- you'll get these for free by inheriting from <code>Exception</code>.</p></li>\n<li><p><code>encrypt_file()</code> and <code>decrypt_file()</code> are both fairly long functions. Could you break them up so that it's easier to see what they're doing?</p></li>\n<li><p>Encrypting and decrypting are symmetric operations -- is there any way you could exploit the symmetry to share code? For example, could you reuse the patterns you use to pack and unpack data?</p></li>\n<li><p>There's a bunch of repetition (eg <code>key = \"this is my key\"</code>) in your tests. Could you make your tests functions of a subclass of <code>unittest.TestCase</code> and provide a common <code>setup()</code> function?</p></li>\n<li><p>I'm not a fan of the <code>@raises</code> decorator -- I think it's useful to know where the exception has been raised, since good tests serve as documentation.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T10:59:52.037", "Id": "10818", "ParentId": "10746", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T12:07:40.330", "Id": "10746", "Score": "7", "Tags": [ "python", "programming-challenge", "security", "cryptography" ], "Title": "Canonical Python symmetric cryptography example" }
10746
<p>I am having some performance problems with a little R script of mine that I use to visualize simulation results of a <a href="https://github.com/mapa17/Eruliaf" rel="nofollow">project of mine</a>. It now takes longer on my machine to run the R script than the simulation itself, and I guess I am doing something wrong.</p> <pre><code>library(ggplot2) DownloadTime &lt;- function(data, prefix) { pIds = unique(data$Pid) nPeers = length(pIds) type &lt;- 1:nPeers downloadTime &lt;- 1:nPeers for(i in 1:(nPeers)){ type[i] &lt;- toString(unique(data[ (data$Pid == i), ]$Type)) start &lt;- unique(data[ (data$Pid == i), ]$Start) lastRound &lt;- max(data[ (data$Pid == i), ]$Tick) end &lt;- data[ (data$Tick == lastRound) &amp; (data$Pid==i), ]$End if( end &gt;= 0){ downloadTime[i] &lt;- end - start } else { downloadTime[i] &lt;- -1 } } pData &lt;- data.frame(type, downloadTime ) hist = ggplot(pData, aes(x=downloadTime, fill=type)) + xlab("Download time [ticks]") + ylab("Peers") + geom_histogram(position=position_dodge()) + opts(title="Download time") + scale_fill_hue( name="Peers", breaks=c("Peer", "Peer_C1"), labels=c("BT","BT_ext") ) density = ggplot(pData, aes(x=downloadTime, colour=type)) + xlab("Download time [ticks]") + ylab("Peers [ratio]") + geom_density() + opts(title="Download time") + scale_colour_hue( name="Peers", breaks=c("Peer", "Peer_C1"), labels=c("BT","BT_ext") ) path = paste(prefix, "downloadTime_hist.png", sep="_") ggsave(file=path , plot=hist , dpi=100) path = paste( prefix, "downloadTime_den.png", sep="_") ggsave(file=path, plot=density , dpi=100) return(pData) } proccessData &lt;- function(data, prefix) { maxTick = data$Tick[length(data$Tick)] tick &lt;- 0:(maxTick*2-1) type &lt;- 1:(maxTick*2) online &lt;- 1:(maxTick*2) completed &lt;- 1:(maxTick*2) avgnTFTSlots &lt;- 1:(maxTick*2) avgnOUSlots &lt;- 1:(maxTick*2) upRate &lt;- 1:(maxTick*2) downRate &lt;- 1:(maxTick*2) type &lt;- 1:(maxTick*2) tftouUpRatio &lt;- 1:(maxTick*2) tftouDownRatio &lt;- 1:(maxTick*2) shareRatio &lt;- 1:(maxTick*2) for(i in 0:(maxTick-1)){ tick[i*2 + 1] &lt;- i type[i*2 +1] &lt;- "Peer" online[i*2 +1] &lt;- nrow( data[ (data$Tick == i) &amp; (data$Type=="Peer"), ] ) completed[i*2 +1] &lt;- nrow( data[ (data$Tick == i) &amp; (data$Type=="Peer") &amp; (data$End != -1), ] ) avgnTFTSlots[i*2 +1] &lt;- mean( data[ (data$Tick == i) &amp; (data$Type=="Peer") &amp; (data$End == -1),]$TFT ) avgnOUSlots[i*2 +1] &lt;- mean( data[ (data$Tick == i) &amp; (data$Type=="Peer") &amp; (data$End == -1),]$OU ) downRate[i*2 +1] &lt;- mean( data[ (data$Tick == i) &amp; (data$Type=="Peer") &amp; (data$End == -1),]$Download/data[(data$Tick == i) &amp; (data$Type=="Peer") &amp; (data$End == -1),]$MaxDownload ) upRate[i*2 +1] &lt;- mean( data[ (data$Tick == i) &amp; (data$Type=="Peer") &amp; (data$End == -1),]$Upload/data[(data$Tick == i) &amp; (data$Type=="Peer") &amp; (data$End == -1),]$MaxUpload ) tftouUpRatio[i*2 +1] &lt;- mean( data[ (data$Tick == i) &amp; (data$Type=="Peer") &amp; (data$End == -1),]$tftouUpRatio ) tftouDownRatio[i*2 +1] &lt;- mean( data[ (data$Tick == i) &amp; (data$Type=="Peer") &amp; (data$End == -1),]$tftouDownRatio ) shareRatio[i*2 +1] &lt;- mean( data[ (data$Tick == i) &amp; (data$Type=="Peer") &amp; (data$End == -1),]$shareRatio ) tick[i*2+1 + 1] &lt;- i type[i*2+1 + 1] &lt;- "Peer_C1" online[i*2+1 +1] &lt;- nrow( data[ (data$Tick == i) &amp; (data$Type=="Peer_C1"), ] ) completed[i*2+1 +1] &lt;- nrow( data[ (data$Tick == i) &amp; (data$Type=="Peer_C1") &amp; (data$End != -1), ] ) avgnTFTSlots[i*2+1 +1] &lt;- mean( data[ (data$Tick == i) &amp; (data$Type=="Peer_C1") &amp; (data$End == -1),]$TFT ) avgnOUSlots[i*2+1 +1] &lt;- mean( data[ (data$Tick == i) &amp; (data$Type=="Peer_C1") &amp; (data$End == -1),]$OU ) downRate[i*2+1 + 1] &lt;- mean( data[ (data$Tick == i) &amp; (data$Type=="Peer_C1") &amp; (data$End == -1) ,]$Download/data[(data$Tick == i) &amp; (data$Type=="Peer_C1") &amp; (data$End == -1),]$MaxDownload ) upRate[i*2+1 + 1] &lt;- mean( data[ (data$Tick == i) &amp; (data$Type=="Peer_C1") &amp; (data$End == -1),]$Upload/data[(data$Tick == i) &amp; (data$Type=="Peer_C1") &amp; (data$End == -1),]$MaxUpload ) tftouUpRatio[i*2+1 +1] &lt;- mean( data[ (data$Tick == i) &amp; (data$Type=="Peer_C1") &amp; (data$End == -1),]$tftouUpRatio ) tftouDownRatio[i*2+1 +1] &lt;- mean( data[ (data$Tick == i) &amp; (data$Type=="Peer_C1") &amp; (data$End == -1),]$tftouDownRatio ) shareRatio[i*2+1 +1] &lt;- mean( data[ (data$Tick == i) &amp; (data$Type=="Peer_C1") &amp; (data$End == -1),]$shareRatio ) } pData &lt;- data.frame(tick, type, online, completed, avgnTFTSlots, avgnOUSlots, upRate, downRate, tftouUpRatio, tftouDownRatio, shareRatio ) #Generate Plots cm = scale_color_manual( name="Peers (without seeders)", breaks=c("Peer", "Peer_C1"), labels=c("BT","BT_ext") , values=c("red", "blue") ) pData.upload = ggplot(pData, aes(x=tick) ) + geom_line(aes(y=upRate, colour=type) ) + xlab("Ticks") + ylab("Ratio") + opts(title="Upload usage") + cm pData.download = ggplot(pData, aes(x=tick) ) + geom_line(aes(y=downRate, colour=type) ) + xlab("Ticks") + ylab("Ratio") + opts(title="Download usage") + cm pData.shareRatio = ggplot(pData, aes(x=tick) ) + geom_line(aes(y=shareRatio, colour=type) ) + xlab("Ticks") + ylab("Ratio") + opts(title="Download / Upload") + cm pData.tftouUpRatio = ggplot(pData, aes(x=tick) ) + geom_line(aes(y=tftouUpRatio, colour=type) ) + xlab("Ticks") + ylab("Ratio") + opts(title="TFT/OU Upload") + cm pData.tftouDownRatio = ggplot(pData, aes(x=tick) ) + geom_line(aes(y=tftouDownRatio, colour=type) ) + xlab("Ticks") + ylab("Ratio") + opts(title="TFT/OU Download") + cm pData.connPlot = ggplot(pData, aes(x=tick) ) + geom_area(aes(y=online, fill=type) , alpha=0.4 , position=position_identity() ) + geom_line( aes(y=completed, colour=type) ,position=position_identity()) + ylab("Peers") + xlab("Ticks") + opts(title="Total and completed Peers") + scale_fill_manual( name="Total Peers", breaks=c("Peer", "Peer_C1"), labels=c("BT","BT_ext") , values=c("red", "blue") ) + scale_color_manual( name="Completed Peers", breaks=c("Peer", "Peer_C1"), labels=c("BT","BT_ext") , values=c("red", "blue") ) pData.ouPlot = ggplot(pData, aes(x=tick) ) + geom_line(aes(y=avgnOUSlots, colour=type) ) + xlab("Ticks") + ylab("OU Slots") + opts(title="Average number of OU Slots") + cm pData.tftPlot = ggplot(pData, aes(x=tick) ) + geom_line(aes(y=avgnTFTSlots, colour=type) ) + xlab("Ticks") + ylab("TFT Slots") + opts(title="Average number of TFT Slots") + cm #Save Plots path = paste(prefix, "Connections_OU.png", sep="_") ggsave(file=path , plot=pData.ouPlot, dpi=100) path = paste(prefix, "Connections_TFT.png", sep="_") ggsave(file=path , plot=pData.tftPlot, dpi=100) path = paste(prefix, "Peer_Count.png", sep="_") ggsave(file=path , plot=pData.connPlot, dpi=100) path = paste(prefix, "uploadRatio.png", sep="_") ggsave(file=path, plot = pData.upload, dpi=100) path = paste(prefix, "downloadRatio.png", sep="_") ggsave(file=path, plot=pData.download, dpi=100) path = paste(prefix, "shareRatio.png", sep="_") ggsave(file=path, plot=pData.shareRatio, dpi=100) path = paste(prefix, "tftouUpRatio.png", sep="_") ggsave(file=path, plot=pData.tftouUpRatio, dpi=100) path = paste(prefix, "tftouDownRatio.png", sep="_") ggsave(file=path, plot=pData.tftouDownRatio, dpi=100) return(pData) } #Generate a copy of an vector v, with elment e insert at position pos ( index starting from 1 ) , pos = -1 appends e to the end insert &lt;- function(v, e, pos) { if( pos == 1){ return( c(e,v) ) } else { if( pos &gt; length(v) | (pos == -1) ) pos = length(v) if( pos == length(v)) return( c(v,e) ) else return( c(v[1:(pos-1)],e,v[(pos):length(v)])) } } #Script has to be called like : Rscript Statistics.R [STATS_FILE] [OUTPUT_DIR] [SUMMARY_FILE] [PREFIX] OR [SUMMARY_FILE] [SUMMART_OUTPUT_DIR] [PREFIX] #Whereby STATS_FILE points to the csv input file and PREFIX will be #Check arguments ( argument TRUE will filter all system arguments ) arg = commandArgs() writeLines( paste("Received " , length(arg) , " arguments", sep="") ) writeLines( paste("Received args ... ", arg, sep="") ) #Own arguments start with arg[6] if(length(arg) &lt; 9){ writeLines( "Missing arguments!" ) #quit("no") } #writeLines("Enough arguments!") #writeLines(paste("arg[6] ", arg[6], sep="")) if( length(arg) == 8 ){ dataFile = arg[6] outputDir = arg[7] prefix = arg[8] outputDir = paste( outputDir, prefix, sep="/") ecdfFile = paste( outputDir, "ECDF.png", sep="") histFile = paste( outputDir, "histogram.png", sep="") writeLines( "Assuming script was called to generate summary statistics!" ) #Load data data = read.csv(dataFile, comment.char='#', sep=';', header=F ) #Set col names colnames(data) &lt;- c("Type", "DownloadTime") #Create plot and store file hist = ggplot(data, aes(x=DownloadTime, fill=Type)) + xlab("Download time") + ylab("Peers") + geom_histogram(position=position_dodge()) + opts(title="Download time") + scale_fill_hue( name="Peers", breaks=c("Peer", "Peer_C1"), labels=c("BT","BT_ext") ) ggsave(file=histFile, plot=hist , dpi=100) #Create ECDF data.reduced = data[data$DownloadTime != -1, ] #Remove peers that did not complete their download #Adds a ecdf column to the data, containing the ecdf value for each line #Note: the ddply is used to group the data depening on the Type coloum ( so is like generating two tables, calculating ecdf for each and than join them again) data.reduced &lt;- ddply(data.reduced, .(Type), transform , ecdf = ecdf(DownloadTime)(DownloadTime) ) data.ecdf = ggplot(data=data.reduced) + geom_step(aes(x=DownloadTime, y=ecdf, color=Type) ) + xlab("Download Time") + ylab("ECDF") + opts(title="Download time") + scale_color_hue( name="Peers", breaks=c("Peer", "Peer_C1"), labels=c("BT","BT_ext") ) ggsave(file=ecdfFile, plot=data.ecdf , dpi=100) } if( length(arg) == 9) { dataFile = arg[6] workingDir = arg[7] histFile = arg[8] prefix = arg[9] writeLines( paste("Assuming script was called to generate simulation statistics! On statistic data ", dataFile, " with histfile ", histFile , " and prefix ", prefix ,sep="") ) setwd(workingDir) #Load data data = read.csv(dataFile, comment.char='#', sep=';', header=F ) # Log format &lt;Tick&gt; &lt;peer Type&gt; &lt;id&gt; &lt;downloadStart&gt; &lt;DownloadEnd&gt; \ #&lt;Max Upload Rate&gt; &lt;Max Download Rate&gt; &lt;Current Upload Rate&gt; &lt;Current Download Rate&gt; \ #&lt;Total # of max TFT Slots&gt; &lt;Total # of max OU Slots&gt; &lt;Total # of used TFT Slots&gt; &lt;Total # of used OU Slots&gt;\n" #Name data colnames(data) &lt;- c("Tick","Type","Pid","Start","End","MaxUpload","MaxDownload","Upload","Download","MaxTFT","MaxOU","TFT","OU","TFTDown","TFTUp","OUDown","OUUp" ) #Calculate averages data$upUsage &lt;- data$Upload / data$MaxUpload data$downUsage &lt;- data$Download / data$MaxDownload data$shareRatio &lt;- data$Download / data$Upload data$tftouUpRatio &lt;- data$TFTUp / data$OUUp data$tftouDownRatio &lt;- data$TFTDown / data$OUDown #Remove irregularities , NaN and inf are set to zero data[ is.nan(data$tftouUpRatio),]$tftouUpRatio = 0 data[ is.nan(data$tftouDownRatio),]$tftouDownRatio = 0 data[ is.nan(data$shareRatio),]$shareRatio = 0 data[ is.infinite(data$tftouUpRatio),]$tftouUpRatio = 0 data[ is.infinite(data$tftouDownRatio),]$tftouDownRatio = 0 data[ is.infinite(data$shareRatio),]$shareRatio = 0 #Filter too high values m = mean(data$shareRatio) * 10 data = data[ ((data$shareRatio) &lt; m),] m = mean(data$tftouUpRatio) * 10 data = data[ ((data$tftouUpRatio) &lt; m),] m = mean(data$tftouDownRatio) * 10 data = data[ ((data$tftouDownRatio) &lt; m),] #Do processing and generate Plots proccessData(data, prefix) pData = DownloadTime(data, prefix) #Save the processed data into the summary file write.table(pData, file=histFile, sep=";", append=TRUE, col.names=FALSE, row.names = FALSE) } </code></pre> <p>The heavy lifting is done in <code>processData()</code>. I think the problem is either the <code>for</code> loop itself or the condition based filtering on the data table.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T20:59:43.720", "Id": "17147", "Score": "0", "body": "Oh, didnt know about something like this existing. Is there a way to move the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T21:15:02.203", "Id": "17148", "Score": "0", "body": "Try these tips first: http://stackoverflow.com/a/8474941/636656" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T21:36:39.877", "Id": "17149", "Score": "1", "body": "@user - if you want, you can flag the question for a moderator to move it for you. Alternatively, I'd recommend paring your question down and focusing it on a specific part of your code that isn't performing optimally. `?Rprof` can help identify which parts of your code are slow. Having some sample data to go with it will also encourage others to try and help! Here's the guide to making a great question: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example. Good luck!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T21:59:13.200", "Id": "17150", "Score": "0", "body": "Too much code. But you should read *The R Inferno* to get awesome tips on speeding up your loops: http://www.burns-stat.com/pages/Tutor/R_inferno.pdf" } ]
[ { "body": "<p>That's a lot of code to wade through. But after a quick look at your <code>processData</code> function, some things stand out. </p>\n\n<pre><code># This part:\nonline[i*2 +1] &lt;- nrow( data[ (data$Tick == i) &amp; (data$Type==\"Peer\"), ] )\ncompleted[i*2 +1] &lt;- nrow( data[ (data$Tick == i) &amp; (data$Type==\"Peer\") &amp; (data$End != -1), ] )\n# etc ...\n\n# Can be replaced with this:\nd &lt;- data[ (data$Tick == i) &amp; (data$Type==\"Peer\"), ]\nonline[i*2 +1] &lt;- nrow( d )\ncompleted[i*2 +1] &lt;- nrow( d[(data$End != -1), ] )\n# etc...\n\n\n# And yet again replaced with this:\nidx &lt;- (data$Tick == i) &amp; (data$Type==\"Peer\")\nonline[i*2 +1] &lt;- sum(idx)\ncompleted[i*2 +1] &lt;- sum( idx &amp; (data$End != -1) )\n# etc...\n</code></pre>\n\n<p>..The basic idea here is to avoid doing the same calculation many times. Extracting data from a data.frame is rather costly, and you seem to only need the number of matches. Indexing using a logical expression will produce a TRUE/FALSE vector, and the rows extracted are the TRUE values, so summing the index vector is the same as the row count...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T21:45:31.870", "Id": "10748", "ParentId": "10747", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T20:49:54.877", "Id": "10747", "Score": "1", "Tags": [ "performance", "r" ], "Title": "Visualizing simulation results of a project" }
10747
<p>I have this simple object setup in JavaScript - <a href="http://jsbin.com/uqacop/11/edit#javascript,live" rel="nofollow">Full code on jsbin</a></p> <p>I'll break it up below, but the question(s) -</p> <ol> <li>Does it break? I mean, I'm sure we can find a interesting case where this would be broken, but how much work do we have to do before it breaks?</li> <li>I started out thinking I needed to explicitly store a list of classes (variable _heap below; yes, calling it heap is rather overdone for what it is) to keep the inheritance tree and avoid memory leaks when an object is instantiated multiple times. I've got the feeling it's unnecessary but I haven't found how to not use it...</li> <li>Any points on how this could be better really! Is this very contrived code?</li> </ol> <p>I'm trying to allow common object creation technique like:</p> <pre><code>function FourLegged() { this.CRY = "ffffhhhh!"; // method this.talk = function() { writeln( this.CRY); }; } </code></pre> <p>But also to have the class, constructor and inheritance in a one block, as OO languages usually do:</p> <pre><code>function Cat() { // inheritance this._parent = FourLegged; // constructor this.construct = function(n) { // private var defined in instance var name; name = n; // methods that use private var - Douglas Crockford nethod // avoid it, it wastes memory if there are multiple instances this.setName = function(n) { name = n; }; this.getName = function() { return name; }; }; // methods will operate in instance context (ie "this" is the instance) this.talk = function() { writeln( this.getName() + " says " + this.CRY); }; } </code></pre> <p>So to do this, I wrap the creation of a new instance:</p> <pre><code>cat1 = new instance(Cat, "felix"); </code></pre> <p>The wrapper processes the function so as to use the constructor and inheritance, but also maintains the _heap (the class list):</p> <pre><code>function instance() { var c = getConstructor(arguments[0]); var args = Array.prototype.slice.call(arguments, 1); return new c(args); } var _heap = {}; function getConstructor(cls) { var cons; // try to retrieve from _heap if (!(cons = _heap[cls])) { // if not already in heap var c = new cls(); if (c._parent) { // set up class-superclass relation cls.prototype = new instance(c._parent); // class has changed, re-intantiate c = new cls(); } if (!c.construct) { // if there is no constructor c.construct = function() {}; // make one } cons = function(args) { return c.construct.apply(this, args); }; cons.prototype = c; // set up class-instance relation _heap[cls] = cons; } return cons; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T18:57:06.337", "Id": "17165", "Score": "1", "body": "Have you looked at how something like coffeescript achieves this? I'm of the opinion that OO-style programming is usually a bad idea in javascript but when I need it I just write a first pass in coffeescript and rip off the generated structure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T10:45:09.200", "Id": "17195", "Score": "0", "body": "I haven't - or hadn't. I'll try to understand how they record classes. I work with students, ideally I'd like to give them something they can quite easily follow through." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T14:32:08.323", "Id": "17208", "Score": "2", "body": "Well in that case there is absolutely nothing easier then going over to the coffeescript page on github, clicking try coffee, and typing \"class Cat\" on the left hand side and seeing what kind of javascript it gets translated to on the right. It also does a good job of underlying the point that javascript OO is very different from traditional OO and the metaphors can only go so far. Finally, theirs is a process tuned by a lot of smart people using some very common patterns so your students would get the benefit of that too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T09:35:06.160", "Id": "17238", "Score": "1", "body": "Yes, the look at their \"class inheritance and super\" example made me realise the quality of their work - especially their use of established javascript patterns." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T14:07:39.923", "Id": "17240", "Score": "0", "body": "Glad to be of help :)" } ]
[ { "body": "<p>My perspective on your questions:</p>\n\n<ol>\n<li><p>It breaks when you want to change the behavior of all cats, since you do not store functions in the <code>.prototype</code> of the classes. Also, not using <code>.prototype</code> makes your code consume more memory.</p></li>\n<li><p>There is indeed a standard way of doing this, however it kind of breaks your requirement : <em>\"But also to have the class, constructor and inheritance in a one block, as OO languages usually do.\"</em> </p></li>\n<li><p>I think vanilla JS does better and is less contrived.</p></li>\n</ol>\n\n<p>Most of the code I borrowed from this excellent <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript\" rel=\"nofollow\">text</a>.</p>\n\n<p>Your FourLegged class would be:</p>\n\n<pre><code>function FourLegged() {\n this.cry = \"ffffhhhh!\"; //default value\n}\n//Functions/methods should be part of prototype\nFourLegged.prototype.talk = function talk(){\n writeln( this.cry);\n};\n</code></pre>\n\n<p>If you absolutely insist on doing this in 1 block, you could do this : </p>\n\n<pre><code>var FourLegged = (function() {\n\n function f() {\n this.cry = \"ffffhhhh!\"; //default value\n }\n\n f.prototype.talk = function talk(){\n writeln( this.cry);\n };\n\n return f;\n}());\n</code></pre>\n\n<p>Then the cat would be this ( wrapped in a function, not required )</p>\n\n<pre><code>var Cat = (function() {\n\n function f(name){\n\n FourLegged.call(this);\n\n (function nameProperty( o , name) {\n // private var defined in instance\n var _name = name;\n // methods that use private var - Douglas Crockford nethod\n o.setName = function(name) { _name = name; };\n o.getName = function() { return _name; };\n })(this , name);\n }\n\n f.prototype = new FourLegged();\n f.prototype.constructor = f;\n\n f.prototype.talk = function talk() {\n writeln( this.getName() + \" says \" + this.cry);\n };\n f.prototype.setCry = function setCry( s ) {\n this.cry = s;\n };\n\n return f;\n}());\n</code></pre>\n\n<p>Your tests will perform exactly the same, except you do not need <code>_parent</code>, <code>_heap</code>, <code>instance()</code> or <code>getConstructor()</code>.</p>\n\n<p><strong>Update</strong></p>\n\n<p>A clarification on 'it does not use memory'.When I create objects this way in the console in Chrome : </p>\n\n<pre><code>function FourLegged() \n{\n this.CRY = \"ffffhhhh!\";\n this.talk = function() { writeln( this.CRY); };\n}\n</code></pre>\n\n<p>I find that these object take 88 bytes. ( Take a head snapshot with developer tools ).</p>\n\n<p>When I create objects the following way in the console in Chrome:</p>\n\n<pre><code>function FourLegged() \n{\n this.CRY = \"ffffhhhh!\";\n}\nFourLegged.prototype.talk = function() { writeln( this.CRY); };\n</code></pre>\n\n<p>These objects take 48 bytes, and that is because the <code>talk</code> function remains on <code>prototype</code>, it does not get copied over the object.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-31T09:20:06.627", "Id": "63886", "Score": "0", "body": "On your point 1 - not so, the function \"instance\" picks up the contructor and uses that to instantiate prototype. So it doesn't waste memory or break in this particular way. But on your points 2 and 3, yes I've come to realise that what I'm trying to do breaks what it now established JS practice, and doesn't provide any real benefits." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-01T23:47:13.473", "Id": "63971", "Score": "0", "body": "@boisvert I updated my answer with empirical data, I am correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-02T09:29:54.957", "Id": "63983", "Score": "0", "body": "I think you tested it using foo = new Fourlegged() rather than foo = instance(FourLegged) which is what I use to manage object reuse. But that shows again that what I did here is too different from established pattern to be useful." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-26T20:46:19.707", "Id": "38134", "ParentId": "10749", "Score": "5" } }, { "body": "<blockquote>\n <p>Does this break?</p>\n</blockquote>\n\n<p>That really depends on the functionality you want to guarantee. Assuming this is working code and your interest is to \"declare\" all aspects of a \"class\" in one block and also have reflection (access to the class hierarchy, via <code>_parent</code> in your example, it breaks if you have a name collision. i.e. you want properties called <code>_parent</code> and <code>construct</code> that have nothing to do with the framework.</p>\n\n<p>I'm having a little trouble seeing how this code works, though:</p>\n\n<pre><code>\nfunction getConstructor(cls) {\n var cons;\n // try to retrieve from _heap\n if (!(cons = _heap[cls])) { // cls is a string\n // if not already in heap\n var c = new cls(); // cls is a constructor?!\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Using a function as a property key, while it may work as expected in whatever environments you've tested, is a risky proposition. According to the ES5 standard, all property keys are strings. Even array indexes are required to behave <em>as if</em> they were first coerced to strings. Any non-string used as a property key to a plain object is implicitly coerced to a string by calling its <code>toString</code> method - you can verify this either by reading the standard or by adding <code>cls.toString = null</code> at the top of the function and observing the error. <code>Function.prototype.toString</code> is defined by the standard as returning \"an implementation-dependent representation of the function...\" that \"...has the syntax of a FunctionDeclaration\". According to the definition of \"FunctionDeclaration\", it is permissible for an implementation to return <code>\"function(){}\"</code> for <em>all functions</em>, i.e. you have no guarantee that the key will involve the function's given name, the function's given formal parameters, or the given function body verbatim, or at all.</p>\n\n<p>Some fairly common patterns are particularly potentially brittle:</p>\n\n<pre><code>\n\nmyModule.Foo = function () {};\nmyModule.Bar = function () {};\n\nconsole.assert(getConstructor(myModule.Foo) !== getConstructor(myModule.Bar)); // uh oh\n\n</code></pre>\n\n<p><strong>/UPDATE</strong></p>\n\n<p>In a more inclusive sense, the pattern you're describing breaks a lot of the functionality that JavaScript provides natively when you use established idioms for creating objects. You lose <code>instanceof</code>, you lose <code>Object.isPrototypeOf</code>, you lose <code>Object.create</code>, you lose <code>constructor</code>, you lose <code>prototype</code>, and you lose either lint or <code>new</code>. You're also forfeiting your IDE's documentation and code completion for your classes and constructors (unless you're writing code in notepad anyway, or something). It comes down to priorities: how desperately do you need single block \"classes\" and reflection, and how certain are you that this is the only way to do it?</p>\n\n<blockquote>\n <p>Is the <code>_heap</code> necessary?</p>\n</blockquote>\n\n<p>Well, yes and no. If you <em>absolutely must</em> instantiate classes <em>by name as a string</em>, and you <em>absolutely must</em> have exactly one namespace for classes, and you <em>absolutely must not</em> use the <code>window</code> object or a module scope as that one namespace (i.e. just declare a function in your source), the way you're doing it is probably the simplest method. I would add a <code>hasOwnProperty(name)</code> to make it more user-proof.</p>\n\n<p>However, for all the same reasons as above, I would again have a good hard think about how badly you need to instantiate objects by the name of their class. If you want to actually do reflection, you'll need to re-implement <code>instanceof</code> by name, etc. etc.; if you want to segregate your classes into namespaces or give them any other kind of scope, you have to re-implement scope.</p>\n\n<blockquote>\n <p>Can this be better?</p>\n</blockquote>\n\n<p>Assuming the constraints are that you <em>must</em> have classes defined in a single block, you <em>must</em> be able to create objects by providing a string instead of a reference to the constructor, and you <em>must</em> use JavaScript:</p>\n\n<ul>\n<li><p>Use a self-invoking lambda as your single block, and have it return a real live constructor with a real live prototype. It's pretty much a fine grained module pattern, and it preserves your reference to the constructor within its scope and thus the availability of JS and your IDE's tools for dealing with objects and constructors.</p></li>\n<li><p>Instead of a single <code>_heap</code>, make a class that will serve as an instance factory and/or namespace for classes. That means you don't have to re-implement scope, and you're protected from future changes to your object creation scheme.</p></li>\n<li><p>Figure out whether <code>cls</code> is a string or a constructor.</p></li>\n</ul>\n\n<p>If you don't really need to constrain your declaration to one block, stick with <code>function Foo</code> and <code>Foo.prototype.bar =</code>. You can still stick it in a hash or factory class if you like. That's the idiom that everyone understands, and it will do the same thing.</p>\n\n<p>If you don't really need to look up classes by name, use function scopes (again, look up module pattern) to manage your namespace instead of a hash.</p>\n\n<p>If you don't really need to be writing JS... well, it seems like you'd really rather be writing Ruby or Python. Those languages have classes. JS doesn't. It has prototypes and constructors and function scope.</p>\n\n<blockquote>\n <p>I work with students.</p>\n</blockquote>\n\n<p>I am begging you to reconsider. If your students ever work with real world programmers, they won't be able to read each other's code. If you want them to learn OO, teach it in an OO language. Really, if they aren't ready for the idea of a prototype the way JS supports it already, they probably aren't ready for JS. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-02T09:12:44.227", "Id": "63980", "Score": "0", "body": "thank you, this is the clearest discussion of the code I've had. I'll explain the cls string/constructor confusion in a separate comment, but your detailed criticism confirms what previous answers and comments showed me: the framework I have here breaks established practice, and besides lost functionality, it's a *very* bad idea especially when teaching students." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-02T09:51:58.317", "Id": "63984", "Score": "0", "body": "Regarding cls being a string or a constructor. cls is a function; it is the class description, e.g. Cat - and not \"Cat\". The _heap array uses the values of cls to index its values, therefore _heap[cls] is the constructor for Cat, with the class-instance and if need be class-parent relation established using prototype. Therefore, I don't lose instanceOf and prototypeOf, but I do lose lint, because that entirely relies on established practice, and object.create." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-03T07:56:28.613", "Id": "64116", "Score": "0", "body": "That sort of changes things; you definitely don't need `_heap` if `cls` is not a string. You're looking for a `Class` class with `Class.prototype.instance` and a `._parent` etc. etc. unless you specifically need to iterate over all defined classes for some reason." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-03T08:15:53.773", "Id": "64118", "Score": "1", "body": "And just to clarify, I don't think this is a terrible objective if you're in a situation where everyone who might read the code is on the same page and is a professional that already knows the accepted idioms and their shortcomings. `function Foo(){}; Foo.prototype.bar=/*...*/` *does* have shortcomings (like no `super`), and they're problems worth solving. Many libraries e.g. dojo make attempts at fixing the JS class pattern, and if your framework solves what you see as a problem, it's fine to push it on your well-paid underlings. But not students." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-03T10:24:18.057", "Id": "64128", "Score": "0", "body": "I very much understand your point. I think I became distracted as I prepared to teach, by the comparison between class implementations in various languages. The question is a year old... I haven't been using this technique." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-02T02:42:16.993", "Id": "38407", "ParentId": "10749", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-09T12:55:42.847", "Id": "10749", "Score": "6", "Tags": [ "javascript", "object-oriented" ], "Title": "Improving a JS object \"framework\"" }
10749
<p>I've added a function that checks if the user is trying to use/access something which requires a session. I'd love to hear some criticisms of my choice of design.</p> <pre><code>class MY_Controller extends CI_Controller { function __construct() { parent::__construct(); if(!$this-&gt;input-&gt;is_ajax_request()) { if(!$this-&gt;session-&gt;userdata('is_logged_in')) { $this-&gt;load-&gt;view('header_public_view'); if($this-&gt;login_required()) //do something, redirect etc.. } else { $this-&gt;load-&gt;model('user_model'); $data['user'] = $this-&gt;user_model-&gt;get_user($this-&gt;session-&gt;userdata('userid')); $this-&gt;load-&gt;view('header_user_view', $data); } } } function login_required() { if($this-&gt;uri-&gt;total_segments() &gt; 3) $request = $this-&gt;uri-&gt;segment(3); else $request = $this-&gt;uri-&gt;segment(2); foreach(unserialize(SESSION_RESOURCES) as $required) { if($request == $required) return true; } } } </code></pre>
[]
[ { "body": "<p>You don't really need to check for <code>is_logged_in</code>. If you destroy/build the session data correctly all you should care about is \"<em>Does a user id exist in the session?</em>\", then you can let your main controller handle the rest.</p>\n\n<pre><code>class MY_Controller extends CI_Controller{\n\n //here we just build some constants to check against values\n //in the permissions array\n const PERM_READ = \"read\";\n const PERM_EDIT = \"update\";\n const PERM_DELETE = \"delete\";\n\n //here we let the main controller take care of our auth/permissions/roles etc\n //first check if a user id exists in the session\n //if so assign a user, group, permissions and check for authentication where\n //you need it ( ie: child controllers)\n\n protected $_user, $_group, $_permissions = array();\n\n public function __construct(){\n parent::__construct();\n\n //check for a user id in the session\n $this-&gt;user = ( $this-&gt;session-&gt;userdata('uid') )\n ? User::find_by_id( $this-&gt;session-&gt;userdata('uid') )\n : NULL;\n\n //if user exists assign permissions and group\n if ($this-&gt;user !== NULL) {\n $this-&gt;_assign_group();\n $this-&gt;_assign_permissions();\n $this-&gt;_check_for_banned_users();\n }\n\n }\n\n protected function _assign_group() {\n return $this-&gt;group = $this-&gt;user-&gt;group-&gt;name;\n }\n\n\n // {[\"read\", \"update\", \"delete\"]}\n protected function _assign_permissions() {\n return $this-&gt;permissions = json_decode($this-&gt;user-&gt;permissions);\n }\n\n protected function _check_for_banned_users() {\n if ($this-&gt;group === 'banned') {\n show_error('You have been banned from this website!');\n return;\n }\n }\n\n protected function _can_read(){\n return (bool) ( in_array( self::PERM_READ, $this-&gt;permissions) );\n }\n\n public function _can_edit(){\n return (bool) ( in_array( self::PERM_EDIT, $this-&gt;permissions) );\n }\n\n public function _can_delete(){\n return (bool) ( in_array( self::PERM_DELETE, $this-&gt;permissions) );\n }\n} \n</code></pre>\n\n<p>This might give you some idea, as your user table won't look like that, I'm sure.</p>\n\n<p>Now, you have control over any child classes.</p>\n\n<pre><code>class some_child extends MY_Controller{\n\n public function __construct(){\n parent::__construct();\n }\n public function show_something(){\n\n if($this-&gt;is_ajax_request()){\n if($this-&gt;user &amp;&amp; $this-&gt;_can_read()){\n //yes a user exists and is logged in,\n //yes he has permission to read from this section\n $this-&gt;load-&gt;view('some_view');\n }\n }\n else\n show_404();\n }\n}\n</code></pre>\n\n<p>Just be careful to destroy your session properly.</p>\n\n<pre><code>function logout(){\n $this-&gt;session-&gt;set_userdata(array(\n 'uid' =&gt; 0,\n //any others you created upon user login\n ));\n return (bool) $this-&gt;session-&gt;sess_destroy();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T07:22:49.230", "Id": "10772", "ParentId": "10750", "Score": "1" } } ]
{ "AcceptedAnswerId": "10772", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T13:09:38.323", "Id": "10750", "Score": "1", "Tags": [ "php", "codeigniter" ], "Title": "Handling session resources in MY_Controller with Codeigniter" }
10750
<p>I'm a not-really-recent-anymore graduate of Michigan Tech. I've been a cook since graduation and I'm an eensie teensie bit rusty in pretty much all my learnin'. Couple weeks ago I got hired on to help create an online learning system. Essentially, it's going to be an online school. I need to be able to have departments, majors, classes, students, instructors, grades, etc. ad nauseum.</p> <p>I know I've got a lot more to go, but before I get much further, I'd like to know if I'm on the right track. I'm really just looking for criticism, best practices, suggestions... praise if it's deserved.</p> <p>This is the ERD I have constructed:</p> <p><a href="https://i.stack.imgur.com/Zw0Gj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zw0Gj.jpg" alt="ERD"></a></p> <p>This is auto-generated SQL by DBdesigner4:</p> <pre><code>CREATE TABLE department ( dpt_name VARCHAR(50) NOT NULL AUTO_INCREMENT, dpt_abbrev VARCHAR(10) NOT NULL, dpt_desc TEXT NOT NULL, PRIMARY KEY(dpt_name) ); CREATE TABLE users ( usr_id INT(8) NOT NULL AUTO_INCREMENT, usr_lname VARCHAR(50) NOT NULL, usr_fname VARCHAR(50) NOT NULL, usr_mname VARCHAR(50) NOT NULL, usr_primary_email VARCHAR(100) NOT NULL, usr_reg_date TIMESTAMP NOT NULL, PRIMARY KEY(usr_id) ); CREATE TABLE program ( pro_abbrev VARCHAR(8) NOT NULL, pro_dpt_name VARCHAR(50) NOT NULL, pro_name VARCHAR(255) NOT NULL, pro_majormin VARCHAR(50) NOT NULL, pro_short_desc VARCHAR(255) NULL, pro_long_desc TEXT NULL, PRIMARY KEY(pro_abbrev), INDEX program_FKIndex1(pro_dpt_name) ); CREATE TABLE hometowninfo ( home_usr_id INT(8) NOT NULL AUTO_INCREMENT, home_addr1 VARCHAR(100) NULL, home_addr2 VARCHAR(100) NULL, home_city VARCHAR(100) NULL, home_state VARCHAR(100) NULL, home_zip INT(15) NULL, home_country VARCHAR(100) NULL, PRIMARY KEY(home_usr_id), INDEX hometowninfo_FKIndex1(home_usr_id) ); CREATE TABLE contact ( con_usr_id INT(8) NOT NULL AUTO_INCREMENT, con_second_email VARCHAR(100) NULL, con_phone1 VARCHAR(20) NULL, con_phone2 VARCHAR(20) NULL, con_local_addr1 VARCHAR(100) NULL, con_local_addr2 VARCHAR(100) NULL, con_local_city VARCHAR(100) NULL, con_local_state VARCHAR(100) NULL, con_local_zip VARCHAR(15) NULL, PRIMARY KEY(con_usr_id), INDEX contact_FKIndex1(con_usr_id) ); CREATE TABLE course ( co_pro_abbrev VARCHAR(8) NOT NULL, co_coursenumber INT(4) NOT NULL, co_desc_short VARCHAR(255) NULL, co_desc_long TEXT NULL, co_days VARCHAR(15) NOT NULL, co_semester VARCHAR(6) NOT NULL, co_start_date DATE NOT NULL, co_stop_date DATE NOT NULL, co_start_time TIME NOT NULL, co_stop_time TIME NOT NULL, PRIMARY KEY(co_pro_abbrev, co_coursenumber), INDEX course_FKIndex1(co_pro_abbrev) ); CREATE TABLE student ( st_usr_id INT(8) NOT NULL, st_co_coursenumber INT(4) NOT NULL, st_co_pro_abbrev VARCHAR(8) NOT NULL, PRIMARY KEY(st_usr_id, st_co_coursenumber, st_co_pro_abbrev), INDEX users_has_course_FKIndex1(st_usr_id), INDEX users_has_course_FKIndex2(st_co_pro_abbrev, st_co_coursenumber) ); CREATE TABLE instructor ( ins_co_coursenumber INT(4) NOT NULL, ins_usr_id INT(8) NOT NULL, ins_pro_abbrev VARCHAR(8) NOT NULL, PRIMARY KEY(ins_co_coursenumber, ins_usr_id, ins_pro_abbrev), INDEX users_has_course_FKIndex1(ins_usr_id), INDEX users_has_course_FKIndex2(ins_pro_abbrev, ins_co_coursenumber), INDEX instructor_FKIndex3(ins_pro_abbrev) ); CREATE TABLE coursefile ( file_co_coursenumber INT(4) NOT NULL, file_pro_abbrev VARCHAR(8) NOT NULL, file_fname VARCHAR(255) NOT NULL, file_type VARCHAR(15) NOT NULL, file_size VARCHAR(45) NOT NULL, file_content LONGBLOB NOT NULL, file_extension VARCHAR(10) NOT NULL, PRIMARY KEY(file_co_coursenumber, file_pro_abbrev), INDEX coursefile_FKIndex2(file_pro_abbrev, file_co_coursenumber) ); CREATE TABLE assignment ( as_id INT(8) NOT NULL AUTO_INCREMENT, as_pro_abbrev VARCHAR(8) NOT NULL, as_co_coursenumber INT(4) NOT NULL, as_name VARCHAR(50) NOT NULL, as_datecreated DATE NOT NULL, as_timecreated TIME NOT NULL, as_desc TEXT NULL, as_instructions INTEGER UNSIGNED NULL, PRIMARY KEY(as_id, as_pro_abbrev, as_co_coursenumber), INDEX assignment_FKIndex1(as_pro_abbrev, as_co_coursenumber) ); CREATE TABLE assignmentfile ( asgf_pro_abbrev VARCHAR(8) NOT NULL, asgf_co_coursenumber INT(4) NOT NULL, asgf_as_id INT(8) NOT NULL, PRIMARY KEY(asgf_pro_abbrev, asgf_co_coursenumber, asgf_as_id), INDEX assignment_has_coursefile_FKIndex1(asgf_as_id, asgf_pro_abbrev, asgf_co_coursenumber), INDEX assignment_has_coursefile_FKIndex2(asgf_co_coursenumber, asgf_pro_abbrev) ); CREATE TABLE assigned ( asg_pro_abbrev VARCHAR(8) NOT NULL, asg_co_coursenumber INT(4) NOT NULL, vsg_usr_id INT(8) NOT NULL, asg_as_id INT(8) NOT NULL, asg_date_due DATE NULL, asg_time_due TIME NULL, asg_points_earned INT(5) NULL, asg_comment TEXT NULL, asg_submit_date DATE NULL, asg_submit_time TIME NULL, asg_attempt INTEGER UNSIGNED NULL, PRIMARY KEY(asg_pro_abbrev, asg_co_coursenumber, asg_usr_id, asg_as_id), INDEX student_has_assignment_FKIndex1(asg_usr_id, asg_co_coursenumber, asg_pro_abbrev), INDEX student_has_assignment_FKIndex2(asg_as_id, asg_pro_abbrev, asg_co_coursenumber) ); </code></pre>
[]
[ { "body": "<p>This is pretty minor but I wonder why Contact, HometownInfo are seperate tables. \nIf you have that information, it is assosiated with a single user via usr_id, so it may as well be in the same table as the other data assosiated with that user.\nOtherwise you risk orphan data in those tables after a user is deleted, that sort of thing. </p>\n\n<p>I think you should be making more use of Enums, for things like Semester, because that way you can guarantee the data is in some a standard form when you need to search by semester. </p>\n\n<p>Personally, and some may disagree, I don't like storing files as blobs in the database, rather I prefer to store them as randomly named files in a directory, with a reference to the file in the database. This keeps the DB smaller, and allows staff to upload really big files (with videos in) without trouble...</p>\n\n<p>Also, good luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T19:37:28.640", "Id": "17167", "Score": "0", "body": "Yeah, the contact and hometowninfo tables can be combined. I was going to do something convoluted and unnecessary to deal with vagueness on the client's part, but I should really get clearer directions before continuing that part.\n\nI totally forgot about adding the enums! Thanks for reminding me. And I'll look into your file storage method. I really just wanted some columns to fill out that table. I haven't yet decided how files will be stored.\n\nThanks for your advice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T18:41:32.860", "Id": "10756", "ParentId": "10751", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T14:57:16.907", "Id": "10751", "Score": "3", "Tags": [ "sql", "mysql" ], "Title": "Online learning system database" }
10751
<p><a href="http://en.wikipedia.org/wiki/Adobe_ColdFusion" rel="nofollow">ColdFusion</a> is a commercial rapid web application development platform invented by Jeremy and JJ Allaire in 1995. ColdFusion is an Adobe product today.</p> <p><a href="/questions/tagged/cfml" class="post-tag" title="show questions tagged &#39;cfml&#39;" rel="tag">cfml</a> is the main scripting language for the ColdFusion platform but can be used with <a href="/questions/tagged/java" class="post-tag" title="show questions tagged &#39;java&#39;" rel="tag">java</a> and <a href="/questions/tagged/.net" class="post-tag" title="show questions tagged &#39;.net&#39;" rel="tag">.net</a> frameworks after installation.</p> <p>"ColdFusion" is often used synonymously with <a href="/questions/tagged/cfml" class="post-tag" title="show questions tagged &#39;cfml&#39;" rel="tag">cfml</a> or "CFM", but there are additional CFML application servers besides ColdFusion, such as Railo and Open BlueDragon. Also, ColdFusion supports programming languages other than CFML, such as server-side <a href="/questions/tagged/actionscript" class="post-tag" title="show questions tagged &#39;actionscript&#39;" rel="tag">actionscript</a> and CFScript (a JavaScript-like language).</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T20:41:31.900", "Id": "10757", "Score": "0", "Tags": null, "Title": null }
10757
ColdFusion is a commercial rapid web application development platform invented by Jeremy and JJ Allaire in 1995 and is now an Adobe product. The main programming language for ColdFusion is CFML. Use this tag for code that targets the ColdFusion platform, and also add the "cfml" tag if applicable.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T20:41:31.900", "Id": "10758", "Score": "0", "Tags": null, "Title": null }
10758
<p>Pvik is a lighweight PHP framework that uses the model, view, controller principle.</p> <p><strong>-- EXAMPLE --</strong></p> <p>Here is a very simple example how you build a website with the framework. <strong>I'm asking you if this is easy to understand or just for me because I know the framework and of course if there are things that I can build better</strong>. Our sample database looks like this:</p> <pre><code>Authors - AuthorID (int, primarykey, auto increment) - Firstname (text) - Lastname (text) Books - BookID (int, primarykey, auto increment) - Title (text) - AuthorID (int) </code></pre> <p>At first we have to tell Pvik how our database looks like. So we're creating a ModelTable that has field definitions and also Model which will be used as object for a single line (in folder /model/):</p> <pre><code>&lt;?php class AuthorsModelTable extends ModelTable { public function __construct(){ // define the table name $this-&gt;TableName = 'Authors'; // define the class name for the model // 'Model' is the standard suffix: 'AuthorModel' $this-&gt;ModelName = 'Author'; // define the primarykey $this-&gt;PrimaryKeyName = 'AuthorID'; // define a new attribute from type primary key $this-&gt;FieldDefinition['AuthorID'] = array ('Type' =&gt; 'PrimaryKey'); // define a new attribute from type normal (text, number, anything) $this-&gt;FieldDefinition['Firstname'] = array ('Type' =&gt; 'Normal'); // define a new attribute from type normal (text, number, anything) $this-&gt;FieldDefinition['Lastname'] = array ('Type' =&gt; 'Normal'); // define a new attribute from type many foreign object // this field contains an ModelArray from 'BookModel's that are associated with a author $this-&gt;FieldDefinition['Books'] = array ('Type' =&gt; 'ManyForeignObjects', 'ModelTable' =&gt; 'Books','ForeignKey' =&gt; 'AuthorID'); } } // this phpdoc is usefull for code completion /** * @property int $AuthorID * @property string $Firstname * @property string $Lastname * @porperty ModelArray $Books */ class AuthorModel extends Model { public function __construct(){ // define the class name for the model table // 'ModelTable' is the standard suffix: 'AuthorsModelTable' $this-&gt;ModelTableName = 'Authors'; } } ?&gt; </code></pre> <p>and now for books:</p> <pre><code>&lt;?php class BooksModelTable extends ModelTable { public function __construct() { // define the table name $this-&gt;TableName = 'Books'; // define the class name for the model // 'Model' is the standard suffix: 'BookModel' $this-&gt;ModelName = 'Book'; // define the primarykey $this-&gt;PrimaryKeyName = 'BookID'; // define a new attribute from type primary key $this-&gt;FieldDefinition['BookID'] = array('Type' =&gt; 'PrimaryKey'); // define a new attribute from type normal (text, number, anything) $this-&gt;FieldDefinition['Title'] = array('Type' =&gt; 'Normal'); // define a new attribute from type foreign key // this field contains the real id $this-&gt;FieldDefinition['AuthorID'] = array('Type' =&gt; 'ForeignKey', 'ModelTable' =&gt; 'Authors'); // define a new attribute from type foreign object // this field contains a object from type 'AuthorModel' $this-&gt;FieldDefinition['Author'] = array('Type' =&gt; 'ForeignObject', 'ForeignKey' =&gt; 'AuthorID'); } } // this phpdoc is usefull for code completion /** * @property int $BookID * @property string $Title * @property int $AuthorID * @property AuthorModel $Author */ class BookModel extends Model { public function __construct() { // define the class name for the model table // 'ModelTable' is the standard suffix: 'BooksModelTable' $this-&gt;ModelTableName = 'Books'; } } ?&gt; </code></pre> <p>Now Pvik knows everthing about our database (I skip the part where in the config we fill in the login data). The next step is creating a controller (in folder /controllers/), I don't want to overfill this post, so the controller just loads the data and refers to the view.</p> <pre><code>&lt;?php class BooksController extends Controller { // action public function Overview(){ // load all books $Books = ModelTable::Get('Books')-&gt;LoadAll(); // passing the data to the view $this-&gt;ViewData-&gt;Set('Books', $Books); $this-&gt;ExecuteView(); } } ?&gt; </code></pre> <p>and of course the view (in /views/books/overview.php #/views/controller name/action name.php ):</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;All books&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;?php // getting the data from the controller $Books = $this-&gt;ViewData-&gt;Get('Books'); /* @var $Books ModelArray */ ?&gt; &lt;table&gt; &lt;tr&gt;&lt;th&gt;Title&lt;/th&gt;&lt;th&gt;Author&lt;/th&gt;&lt;th&gt;How many books did the author write?&lt;/th&gt;&lt;/tr&gt; &lt;?php foreach($Books as $Book){ /* @var $Book BookModel */ ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $Book-&gt;Title;?&gt;&lt;/td&gt; &lt;!-- Uses lazy loading to get the author --&gt; &lt;td&gt;&lt;?php echo $Book-&gt;Author-&gt;Firstname . ' ' . $Book-&gt;Author-&gt;Lastname ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo count($Book-&gt;Author-&gt;Books);?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php } ?&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The last step is that we have to tell pvik which controller should be called when. Therefor we add a route in the config.php:</p> <pre><code>self::$Config['Routes'] = array ( array ('Url' =&gt; '/books/', 'Controller' =&gt; 'Books', 'Action' =&gt; 'Overview') ); </code></pre> <p>If we would access our side now under the URL example.org/books/ Pvik automatically calls the controller, which loads a list of books. Than the view get called which does create the HTML.</p> <p>Pvik also provides methods to insert/update Models. You could set up a masterpage. Add parameters to a route. As is said this example is just a simple one to show something. If you have further questions don't hesitate to ask me and don't forget to have a look at the documentation which explains it much more in detail.</p> <p><strong>--- FURTHER EXAMPLE / INFORMATION ---</strong></p> <p>Some might ask why Pvik uses classes for the definition of a database. This gives you the possibilty to add function to you ModelTable and your Model:</p> <pre><code>&lt;?php class AuthorsModelTable extends ModelTable { // ... // // returns a AuthorModel or null by its name public function LoadAuthorByFullname($Firstname, $Lastname){ // this variable indicates if all authors already loaded // into the cache if($this-&gt;LoadedAll){ // if everything is loaded this functions doesn't run a sql // instead it loads the authors from the cache $Authors = $this-&gt;LoadAll(); $Author = $Authors-&gt;FilterEquals('Firstname', $Firstname) -&gt;FilterEquals('Lastname', $Lastname) -&gt;GetFirst(); return $Author; } else { // we have to run a sql statement $Query = new Query('Authors'); $Query-&gt;SetConditions('WHERE Authors.Firstname = "%s" AND Authors.Lastname = "%s"'); $Query-&gt;AddParameter($Firstname); $Query-&gt;AddParameter($Lastname); $Author = $Query-&gt;SelectSingle(); return $Author; } } } class AuthorModel extends Model { // ... // public function GetFullname(){ return $this-&gt;Firstname . ' ' . $this-&gt;Lastname; } } </code></pre> <p>A new controller:</p> <pre><code>class AuthorsController extends Controller { public function Author(){ // get parameters from the url $Firstname = $this-&gt;Parameters-&gt;Get('firstname'); $Lastname = $this-&gt;Parameters-&gt;Get('lastname'); // call our new function $Author = ModelTable::Get('Authors')-&gt;LoadAuthorByFullname($Firstname, $Lastname); if($Author!=null){ $this-&gt;ViewData-&gt;Set('Author', $Author); $this-&gt;ExecuteView(); } else { // redirects to the root page $this-&gt;RedirectToPath('~/'); } } } ?&gt; </code></pre> <p>Our very simple view:</p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Author&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;?php // getting the data from the controller $Author = $this-&gt;ViewData-&gt;Get('Author'); /* @var $Author AuthorModel */ // we just display the fullname echo $Author-&gt;GetFullname(); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And again we need to register the route in the config:</p> <pre><code>self::$Config['Routes'] = array ( // ... // array ('Url' =&gt; '/author/{firstname}/{lastname}/', 'Controller' =&gt; 'Authors', 'Action' =&gt; 'Authors') ); </code></pre> <p>Now we can call our website via <code>example.org/author/william/shakespear/</code></p> <p><a href="http://www.roccosportal.com/how-to/" rel="nofollow">Documentation</a></p> <p><a href="https://github.com/Roccosportal/Pvik" rel="nofollow">Github</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T00:17:17.603", "Id": "17172", "Score": "0", "body": "You'll have to move the code you want reviewed here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T00:30:50.020", "Id": "17173", "Score": "0", "body": "It is more a project review than a code review. And I think it wouldn't make sense to move all the code (54 files) here. As I said in the first sentences, I'm not sure if this here is the right place and I apologize if it isn't but maybe you could suggest a better place?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T00:33:36.880", "Id": "17174", "Score": "0", "body": "You don't have to move _all_ the code, you could start by moving some of the more essential parts of it. This is the right place for your question, but it's a bit unreasonable to expect people to go to your repository and review 54 files. You can always post more than one questions, no need to have all the code in one..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T00:40:17.667", "Id": "17176", "Score": "0", "body": "Ok, that makes more sense. Do you think the documentation -> http://roccosportal.com/how-to/ is better? Than I'll move parts from it to here. It's just a complex system and it is hard to explain it without mention other parts of the framework." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T03:19:58.413", "Id": "17186", "Score": "0", "body": "Hmm, that's completely up to you, I don't know your code well enough to tell you which parts should be reviewed first. Pick the most interesting parts ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T04:32:59.790", "Id": "17187", "Score": "0", "body": "Maybe the most interesting part is how easy (in my eyes) you can set up a full working website. I hope this example is good enough even when I had to strip out so many functions because nobody wants to read too much ;). What do you think?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T14:37:30.667", "Id": "17242", "Score": "0", "body": "Strip out the framework advertising from this question and it would be good. That would be why you got the -1 (and probably more to come). Only include information which is helpful to review your code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T10:37:15.660", "Id": "17267", "Score": "0", "body": "That is maybe because I actually search for a place to \"advertise\" my framework or in other words to search for programmers which are keen to use a new framework. I stripped out the advertisment. Is this better? I hope you considering that I'm trying my best ;)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T10:40:49.940", "Id": "17268", "Score": "1", "body": "Yes, this is good now, +1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T10:43:16.010", "Id": "17269", "Score": "0", "body": "Thank you very much. Let me know if I should change anything, include further examples or something else. And by the way thumbs up to you guys for letting me know what exactly is wrong with my post so that I got -1." } ]
[ { "body": "<p>Do not force developers to hand-code ModelTable subclasses (it is error-prone, monotonous, and time-consuming). Use PDO to automatically create base classes for all selected tables (entities) in the system. You could develop a web UI for table selection, column selection, and so forth. You could also generate \"List of Value\" view objects that are derived from foreign-key relationships.</p>\n\n<p>As a developer, if I wanted to change an entity's behaviour, I would subclcass it then use polymorphism to inject custom code.</p>\n\n<p>The relationship becomes:</p>\n\n<pre><code>ModelTable -&gt; AuthorsGeneratedModelTable -&gt; AuthorsModelTable\n</code></pre>\n\n<p>The <code>AuthorsModelTable</code> could be optional.</p>\n\n<p>If you are looking to create a framework that generates a web site for editing code tables, I suggest researching <a href=\"http://www.sqlmaestro.com/products/postgresql/phpgenerator/\" rel=\"nofollow\">existing solutions</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-21T21:25:23.183", "Id": "20776", "ParentId": "10761", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T22:54:31.183", "Id": "10761", "Score": "5", "Tags": [ "php", "mvc" ], "Title": "Pvik - a small PHP framework" }
10761
<p>The problem description is: </p> <blockquote> <p>You are given n types of coin denominations of values v(1) &lt; v(2) &lt; ... &lt; v(n) (all integers). Assume v(1) = 1, so you can always make change for any amount of money C. Give an algorithm which makes change for an amount of money C with as few coins as possible. [on problem set 4]</p> </blockquote> <p>Taken from <a href="http://people.csail.mit.edu/bdean/6.046/dp/" rel="nofollow">MIT Dynamic Programming Problems</a></p> <p>Is there a linear time solution to this problem?</p> <pre><code>#include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;list&gt; #include &lt;iostream&gt; typedef std::vector&lt;int&gt;::iterator monetary_finder; /*! * Change System class: Responsible for * keeping track of value to make change for * and the actual monetary values of our system. * To avoid round off error multiply everything by * 100 and type cast it to an integer. */ class change_system { public: change_system(float money) : m_C(money * 100), m_RemainingChange(money * 100) { m_MonetaryValues.push_back(0.00 * 100); /* TODO -- MH Allow for other monetary systems * this will require a sort on the values. And * allowing the users to pass in a vector. */ m_MonetaryValues.push_back(0.01 * 100); m_MonetaryValues.push_back(0.05 * 100); m_MonetaryValues.push_back(0.10 * 100); m_MonetaryValues.push_back(0.25 * 100); m_MonetaryValues.push_back(0.50 * 100); m_MonetaryValues.push_back(1.00 * 100); m_MonetaryValues.push_back(5.00 * 100); m_MonetaryValues.push_back(10.00 * 100); m_MonetaryValues.push_back(20.00 * 100); m_MonetaryValues.push_back(50.00 * 100); m_MonetaryValues.push_back(100.00 * 100); /* * Don't assume that users will give you currency values * in order. O(nlgn) */ std::sort(m_MonetaryValues.begin(), m_MonetaryValues.end()); } float money() const {return m_C;} float remaining_change() const {return m_RemainingChange;} std::vector&lt;int&gt; &amp;get_m_MonetaryValue() { return m_MonetaryValues; } float make_change(); private: monetary_finder find_largest_smallest_value(); std::vector&lt;int&gt; m_MonetaryValues; // v(1),v(2),...,v(n) float m_C; float m_RemainingChange; }; /*! * Find the largest value just below the change * remaining. Binary search results in O(lg n) look up * complexity */ monetary_finder change_system::find_largest_smallest_value() { /* * If you know that your largest currency is smaller * than what is remaining then just return that */ if(m_MonetaryValues[m_MonetaryValues.size() - 1] &lt; m_RemainingChange) { return m_MonetaryValues.end() - 1; } monetary_finder left = m_MonetaryValues.begin(); monetary_finder right = m_MonetaryValues.end(); unsigned int index = std::distance(left, right)/2; monetary_finder loc = m_MonetaryValues.begin() + index; /* * A binary search to find largest value less than * the remaining change */ int distance = std::distance(left, right); while (distance &gt; 1 &amp;&amp; (*loc) != m_RemainingChange) { if ((*loc) &lt; m_RemainingChange) { left = loc; } else if ((*loc) &gt; m_RemainingChange) { right = loc; } distance = std::distance(left, right); index = std::distance(left, right)/2; loc = left + index; } /* * When left with two elements in the array the choice should * be to take the largest. But if it is larger than what is remaining * then take the other. */ if ((*loc) != m_RemainingChange) { loc = std::max_element(left, right); if ((*loc) &gt; m_RemainingChange) { loc = left; } } return loc; } /*! * Method that finds the exact change for the value * specified in the constructor of the object. This will * be printed to the screen. */ float change_system::make_change() { monetary_finder find = find_largest_smallest_value(); float largest_less_than = (*find); while (largest_less_than != 0) { while (m_RemainingChange &gt; 0) { m_RemainingChange -= largest_less_than; if (m_RemainingChange &gt;= 0) { std::cout &lt;&lt; "You get " &lt;&lt; (largest_less_than/100) &lt;&lt; std::endl; } } if (m_RemainingChange != 0) { m_RemainingChange += largest_less_than; } find = find_largest_smallest_value(); largest_less_than = (*find); } return 0.0; } int main (int argc, char *argv[]) { std::vector&lt;int&gt; test_value; test_value.push_back(6); test_value.push_back(8); test_value.push_back(11); test_value.push_back(12); test_value.push_back(13); test_value.push_back(16); test_value.push_back(19); test_value.push_back(21); test_value.push_back(22); for (std::vector&lt;int&gt;::iterator i = test_value.begin(); i &lt; test_value.end(); ++i) { change_system change_for_10cents(*i); change_for_10cents.make_change(); std::cout &lt;&lt; "Is what you get back for: " &lt;&lt; (*i) &lt;&lt; std::endl; } } </code></pre> <p>Results:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>You get 5 You get 1 Is what you get back for: 6 You get 5 You get 1 You get 1 You get 1 Is what you get back for: 8 You get 10 You get 1 Is what you get back for: 11 You get 10 You get 1 You get 1 Is what you get back for: 12 You get 10 You get 1 You get 1 You get 1 Is what you get back for: 13 You get 10 You get 5 You get 1 Is what you get back for: 16 You get 10 You get 5 You get 1 You get 1 You get 1 You get 1 Is what you get back for: 19 You get 20 You get 1 Is what you get back for: 21 You get 20 You get 1 You get 1 Is what you get back for: 22 </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T23:51:44.843", "Id": "17169", "Score": "0", "body": "float are not good a representing monetary units (because of their precision (or imprecision (and thus rounding errors))). So it is best to use integers. So rather than store the value as dollars and cents $12.34 store the value as only cents 1234c" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T00:06:54.607", "Id": "17170", "Score": "0", "body": "The following quick test gives the wrong results: 6/8/11/12/13/16/19/21/22" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T02:57:30.703", "Id": "17184", "Score": "0", "body": "Are those your currency values or are those the values you are look to produce?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T16:49:00.743", "Id": "17219", "Score": "0", "body": "Sorry: That is $0.06 and $0.08 and $0.11 etc The float point register on your machine is different from mine. Just run through the number $0.01 to $100.00 see if you get any anomalies. Given you are using float you will probably get some very quickly." } ]
[ { "body": "<p>Firstly, yes there are better solutions: see <a href=\"http://www.algorithmist.com/index.php/Coin_Change\" rel=\"nofollow\">http://www.algorithmist.com/index.php/Coin_Change</a></p>\n\n<pre><code>/*!\n * Find the largest value just below the change\n * remaining. Binary search results in O(lg n) look up\n * complexity\n */\nmonetary_finder change_system::find_largest_smallest_value()\n{\n</code></pre>\n\n<p>I see where largest comes in. I'm not seeing where smallest does. Why are you returning an iterator rather then the value?</p>\n\n<pre><code> /*\n * If you know that your largest currency is smaller\n * than what is remaining then just return that\n */\n if(m_MonetaryValues[m_MonetaryValues.size() - 1] &lt; m_RemainingChange) {\n return m_MonetaryValues.end() - 1;\n }\n</code></pre>\n\n<p>Dubious optimization. </p>\n\n<pre><code> monetary_finder left = m_MonetaryValues.begin();\n monetary_finder right = m_MonetaryValues.end();\n\n unsigned int index = std::distance(left, right)/2;\n monetary_finder loc = m_MonetaryValues.begin() + index;\n\n /*\n * A binary search to find largest value less than\n * the remaining change\n */\n int distance = std::distance(left, right);\n while (distance &gt; 1 &amp;&amp; (*loc) != m_RemainingChange) {\n if ((*loc) &lt; m_RemainingChange) {\n left = loc;\n } else if ((*loc) &gt; m_RemainingChange) {\n right = loc;\n }\n distance = std::distance(left, right);\n index = std::distance(left, right)/2;\n loc = left + index;\n }\n</code></pre>\n\n<p>So, there's a <code>std::lower_bound</code> function that implements this binary search for you. </p>\n\n<pre><code> /*\n * When left with two elements in the array the choice should\n * be to take the largest. But if it is larger than what is remaining\n * then take the other.\n */\n if ((*loc) != m_RemainingChange) {\n loc = std::max_element(left, right);\n if ((*loc) &gt; m_RemainingChange) {\n loc = left;\n }\n }\n</code></pre>\n\n<p>This should really be handled in the binary search</p>\n\n<pre><code> return loc;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T04:50:49.440", "Id": "17188", "Score": "0", "body": "\"Dubious optimization\" ??? Saves you time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T13:08:34.263", "Id": "17202", "Score": "0", "body": "@MatthewHoggan, it doesn't save you much time, and there are much better optimizations for this problem." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T04:00:09.763", "Id": "10769", "ParentId": "10762", "Score": "1" } } ]
{ "AcceptedAnswerId": "10769", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T23:32:30.640", "Id": "10762", "Score": "4", "Tags": [ "c++", "algorithm", "programming-challenge", "change-making-problem" ], "Title": "More optimal \"Making Change\" Problem: Knapsack challenge" }
10762
<p>Is this going to leak memory or is it ok? Please also let me know if there is something else that I need to pay attention to.</p> <pre><code>typedef struct { int len; UC * message; }pack; pack * prepare_packet_to_send(const int length,const unsigned char tag,const int numargs, ... ) { pack *layer= malloc(sizeof(pack)); va_list listp; va_start( listp, numargs ); int step = 0; layer-&gt;message = (unsigned char *) malloc(length); layer-&gt;len = length; int i = 0; int len = 0; unsigned char *source_message ; for( i = 0 ; i &lt; numargs; i++ ) { source_message = va_arg( listp, unsigned char *); len = va_arg( listp, long); memcpy(layer-&gt;message+step, source_message, (long) len); step+=len; } va_end( listp ); return layer; } main() { pack *test = call prepare_packet_to_send(sizeof(var1)+sizeof(var2),any tag,any args) // are following two frees correct/enough? or is there something else i need to do to prevent mem leak? free(test-&gt;message); free(test); } </code></pre>
[]
[ { "body": "<p>Yes and no.</p>\n\n<p>As you've used it here, I don't see a memory leak, so that would be a \"no.\"</p>\n\n<p>The function itself, however allocates memory without ever freeing it, so it's pretty much a memory leak waiting to happen -- the client code has to free the memory it allocates. Worse, freeing that memory is slightly non-trivial (two separate <code>free</code>s that have to happen in the right order) so it's not <em>just</em> a matter of whoever uses it <em>remembering</em> to free the memory, but there's also a possibility of them doing it wrong even if they do remember. Granted, it's not terribly complex either, but I'd still probably add a little function like:</p>\n\n<pre><code>void destroy_sent_packet(pack *p) { \n free(p-&gt;message);\n free(p);\n}\n</code></pre>\n\n<p>So it's at least back to the client just remembering to free the memory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T00:46:48.443", "Id": "17177", "Score": "0", "body": "Thank you so much, so If I understood you correctly, as long as I use your free function after each call it won't leak?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T00:08:02.777", "Id": "10764", "ParentId": "10763", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T23:54:53.643", "Id": "10763", "Score": "1", "Tags": [ "c", "memory-management" ], "Title": "Free memory outside function" }
10763
<p>This is a script that emulates a recycle bin in the CLI.<br> You can undo your last changes and delete files</p> <p>This is my first bash script so don't hesitate to bash me. Thank you for taking a look.</p> <pre><code>#! /bin/bash usage(){ cat &lt;&lt; EOF Sends and restores files to and from the recycle bin Usage: rm [options] file1 [file2] ... Files can be either files or directories Options: -v verbose mode -h this help message -n dry run -r restore the file(s) specified -e empties the bin -s stop on errors -u undo last batch -d &lt;DIR&gt; specify the recycle directory (defaults to '.recycle' in your ~) All other options are ignored when moving files. When removing permanently, these options are passed to /bin/rm EOF } FILES="" VERBOSE=0 DRY=0 RESTORE=0 ERRORSTOP=0 TROOT="$HOME" UNDO=0 RBIN=".recycle" CURR=`pwd` EMPTY=0 UNDOFILE= while getopts “hvnrsued:” OPTION do case $OPTION in h) usage exit 0 ;; v) VERBOSE=1 ;; n) DRY=1 ;; r) RESTORE=1 ;; u) UNDO=1 ;; d) RBIN=$OPTARG ;; e) EMPTY=1 ;; s) ERRORSTOP=1 ;; ?) echo "Invalid option: -$OPTARG" &gt;&amp;2 usage exit 1 ;; esac done #setting the undo file name, will be ~/.recycle-log by default UNDOFILE=$TROOT/$RBIN"-log" #setting full path for the recycle bin dir RBIN="$TROOT/$RBIN" if [ "$VERBOSE" = 1 ]; then echo "recycle dir: $RBIN" echo "current dir: $CURR" fi # creating the recycle bin dir if it does not exist test -d "$RBIN" || mkdir -p "$RBIN" if [ ! -d "$RBIN" ]; then echo "could not create the directory $RBIN" &gt;&amp;2 exit 1 fi # if -u was passed, undo and exit if [ "$UNDO" = 1 ]; then if [ -f "$UNDOFILE" ]; then source $UNDOFILE rm $UNDOFILE echo "undone" &gt;&amp;2 exit 0 else echo "no undo file found, cannot undo" &gt;&amp;2 exit 1 fi fi # resetting undo file for changes to come if [ -f "$UNDOFILE" ]; then rm $UNDOFILE fi shift $(( OPTIND - 1 )) # if -e or -u were passed, no arguments is ok # if not, then the used should provide at least # one filename if [ "$EMPTY" = 0 ]; then if [ -z "$1" ]; then echo "you should pass at least one filename" &gt;&amp;2 echo "use -h for help" &gt;&amp;2 exit 1 fi else # if -e was passed, empty the directory if [ "$DRY" = 0 ]; then rm -r "$RBIN" mkdir -p "$RBIN" fi if [ "$VERBOSE" = 1 ]; then echo "bin emptied" &gt;&amp;2 fi exit 0 fi # setting the in and out dir # By default, in is the current dir and out is the bin dir IN="$CURR" OUT="$RBIN" # but if -r was passed, switch them if [ "$RESTORE" = 1 ]; then let IN="$RBIN" let OUT="$CURR" fi if [ "$IN" = "$OUT" ]; then echo "Error: you are trying to move files to same directory" &gt;&amp;2 exit 1 fi orig= dest= # preparing undo file touch $UNDOFILE while [ "$1" ]; do orig="$IN/$(basename $1)" dest="$OUT/$(basename $1)" if [ "$DRY" = 1 ]; then if [ "$RESTORE" = 1 ]; then echo "restore $orig" &gt;&amp;2 else echo "delete $orig" &gt;&amp;2 fi fi if [ -e "$orig" ]; then # if file already exists, rename it by appending a number if [ -e "$dest" ]; then version=2 while [ -e "$dest$version" ]; do let version=$version+1 done if [ "$DRY" = 0 ]; then mv "$dest" "$dest$version" echo "mv $dest$version $dest" &gt;&gt; $UNDOFILE fi if [ "$VERBOSE" = 1 ];then echo "moving old existing $dest to $dest$version" &gt;&amp;2 fi fi if [ "$DRY" = 0 ]; then mv "$orig" "$dest" echo "mv $dest $orig" &gt;&gt; $UNDOFILE fi if [ "$VERBOSE" = 1 ]; then echo "$orig → $dest" &gt;&amp;2 fi else if [ "$VERBOSE" = 1 ]; then echo "file '$(basename $1)' could not be processed" &gt;&amp;2 fi if [ "$ERRORSTOP" = 1 ]; then echo "there were errors" &gt;&amp;2 exit 1 fi fi shift done </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T07:17:36.833", "Id": "17193", "Score": "0", "body": "Looks nice. I'd reconsider naming it `rm`. Something like `srm - safe remove` or `urm - undo-able remove` sounds better and you can also leave the command in place. If you'd override the default `rm` this might lead to confusion of users which are not familiar with the system." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T17:07:54.497", "Id": "17221", "Score": "0", "body": "Oh definitely. Thanks for pointing this out. This reference to rm was from when I began writing it and I forgot to change it. I was considering \"del\" or \"trash\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T17:18:43.407", "Id": "17224", "Score": "0", "body": "This is the original script I was inspired from. Began by copy-pasting it but forgot to edit the \"usage\" part: http://snipplr.com/view/57640/" } ]
[ { "body": "<ol>\n<li>You don't need a space in the current shebang line. Anyway, <a href=\"http://mywiki.wooledge.org/BashGuide/Practices\" rel=\"nofollow noreferrer\">Greg's wiki</a> and <a href=\"https://unix.stackexchange.com/questions/32132/how-to-find-bash-in-a-portable-way\">others</a> recommend <code>#!/usr/bin/env bash</code> (for portability, but I can't find a reference at the moment).</li>\n<li><p>Any <a href=\"http://mywiki.wooledge.org/CommandSubstitution\" rel=\"nofollow noreferrer\">command substitutions</a> should use <code>\"$(foo)\"</code> rather than <code>`foo`</code>. That way, you actually get what the command returns (except for <a href=\"https://stackoverflow.com/questions/4456004/trailing-newlines-get-truncated-from-bash-subshell\">trailing newlines</a>) rather than a whitespace-clobbered version. For example, <code>CURR=\"$(pwd)\"</code>, or even better:</p>\n\n<pre><code>CURR=\"$(pwd; echo x)\"\nCURR=\"${CURR%x}\"\n</code></pre></li>\n<li><em>Don't</em> use actual opening and closing <a href=\"https://en.wikipedia.org/wiki/Quotation_mark_glyphs\" rel=\"nofollow noreferrer\">quotation marks</a> (<code>“hvnrsued:”</code>). This type of quotes are just regular characters in Bash, so it's as if you had added a <code>-“</code> and <code>-”</code> option. <a href=\"http://mywiki.wooledge.org/Quotes\" rel=\"nofollow noreferrer\">More about quotes</a>.</li>\n<li>Some lines are not indented properly. Incorrect indentation makes the code hard to read, and in the worst case can introduce errors because of misunderstandings of context.</li>\n<li><p>Use the safe version of all calls which support it: <code>command --option1 --option2 -- \"$file1\" \"$file2\"</code>. The double dashes separate options from filenames in most *nix commands, to avoid interpretation of filenames as options, or, in the worst case, acting on the wrong file. Other commands have special flags (<code>-e</code>, <code>--regex</code> in <code>grep</code>) to prefix other options to avoid treating the second option as another flag. Compare (untested)</p>\n\n<pre><code>printf %s -foo | grep -foo # No such file oo\n</code></pre>\n\n<p>with</p>\n\n<pre><code>printf %s -foo | grep -e -foo\n</code></pre></li>\n<li><p><code>echo</code> is one of those unfortunate commands which don't have such an option. Use <code>printf</code> if you don't know what the input will be. Compare (untested)</p>\n\n<pre><code>string=-escape\necho \"$string\" # No such option -s\n</code></pre>\n\n<p>with</p>\n\n<pre><code>printf %s \"$string\"\n</code></pre></li>\n<li><p>Create lots of test cases. This is such a dangerous script that you'd better have some proof that complex file names created by accident or malicious users don't have an opportunity to wreak havoc. I can thoroughly recommend <a href=\"http://code.google.com/p/shunit2/\" rel=\"nofollow noreferrer\">shunit2</a>, which is even in the Ubuntu repositories. <a href=\"https://github.com/l0b0/tilde/tree/master/tests\" rel=\"nofollow noreferrer\">Example tests</a>.</p></li>\n<li>You should add <code>set -o errexit -o noclobber -o nounset -o pipefail</code> at the beginning of the file to ensure stricter error checking. Only re-enable clobbering for the smallest possible code block (i.e., the single line where you use redirection to file) if necessary.</li>\n<li><p>Declare read-only variables as such (<code>help readonly</code>, <code>help declare</code>) to avoid accidental modification. This should be done separately from assignment - If you do it together (<code>declare -r foo=\"$(false)\"</code>), you'll find that the exit code of the command substitution is <em>lost</em>. Compare</p>\n\n<pre><code>declare -r foo=\"$(false)\"\necho $?\n</code></pre>\n\n<p>with</p>\n\n<pre><code>bar=\"$(false)\"\necho $?\ndeclare -r bar\necho $?\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T17:09:30.250", "Id": "17222", "Score": "0", "body": "Thanks for the kind comment and all the advice! I'll try to implement that, though I have no idea about how to do the safe version of calls. All the examples of getOpts used short versions. I began writing my own loop and parse but gave up. And about the indentation, that's the copy-paste from vim that messed it up...I corrected it but apparently forgot some parts." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T17:09:59.267", "Id": "17223", "Score": "0", "body": "On another note, what's the policy around here? When I update my code, should I just edit my post?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-28T07:27:32.250", "Id": "26003", "Score": "0", "body": "@Xananax You should not update the code - It would make the answers obsolete. Rather, when you feel you've got a much improved version, you could post a separate question asking for more advice." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T09:04:59.610", "Id": "10775", "ParentId": "10768", "Score": "4" } }, { "body": "<p>consider <code>set -u</code> for checking for uninitialized variables.</p>\n\n<p>The general convention is to use small letters for variables you don't export</p>\n\n<pre><code>files=\"\"\nverbose=0\ndry=0\nrestore=0\nerrorstop=0\nundo=0\nrbin=\".recycle\"\ncurr=$(pwd)\nempty=0\nundofile=\n</code></pre>\n\n<p>Why do you need this? Do you change $HOME in your script?</p>\n\n<pre><code>troot=\"$HOME\"\n</code></pre>\n\n<p>...\nAn echo that accepts a file argument too</p>\n\n<pre><code>xecho() {\n case \"$1\" in\n -f) cat;;\n *) echo $*;;\n esac\n}\n</code></pre>\n\n<p>Consider making an error function </p>\n\n<p>err() {\n xecho $@ >&amp;2\n }\n errexit() {\n local exitval=shift;\n err \"$2\" >&amp;2\n exit $exitval \n }</p>\n\n<p>I feel cat is cleaner than multiple echoes, but it is just a preference. Also consider making verbose a function</p>\n\n<pre><code>verbose() {\n [ \"$VERBOSE\" = 1 ] &amp;&amp; xecho $@\n}\nwarn() {\n verbose $@ &gt;&amp;2\n}\n\n\nverbose -f &lt;&lt;EOF\nrecycle dir: $RBIN\ncurrent dir: $CURR\nEOF\n</code></pre>\n\n<p>You could also do a general tryexec function that checks if dryrun and if so, just echos the commands and else execute them. This would be better than the current $DRY checks distributed in the code.</p>\n\n<pre><code>tryexec() {\n if [ \"$DRY\" = 0 ]\n then\n cat\n else\n bash\n fi\n}\n</code></pre>\n\n<p>You don't need to test if dir exists if you are going to use mkdir -p\nMore over, your message in that case is a bit redundant. mkdir's error message\nsays exactly the same thing.</p>\n\n<pre><code># creating the recycle bin dir if it does not exist\nmkdir -p \"$RBIN\" || exit 1\n</code></pre>\n\n<p>consider making undo_file a separate function, also it is nice to see validation of parameters in front. Removing the undo file is done after this any way in main body, so that is not needed twice.</p>\n\n<pre><code>undo_file() {\n [ -f \"$1\" ] || {echo \"no undo file found, cannot undo\" &gt;&amp;2 ; exit 1}\n source $1\n errexit 0 \"undone\"\n}\n\n# if -u was passed, undo and exit\n[ \"$UNDO\" = 1 ] &amp;&amp; undo_file $UNDOFILE\n</code></pre>\n\n<p>You can just use -f to rm rather than checking if file exists or not.</p>\n\n<pre><code># resetting undo file for changes to come\nrm -f $UNDOFILE\n</code></pre>\n\n<p>Consider doing this at the getopt stage itself. That is the right place to ensure correct number of arguments to each option. I would also consider just printing usage if the number of arguments do not match.</p>\n\n<pre><code># if -e or -u were passed, no arguments is ok\n# if not, then the used should provide at least\n# one filename\n[ \"$EMPTY\" = 0 ] &amp;&amp; [ -z \"$1\" ] &amp;&amp; errexit 1 -f &lt;&lt;EOF\nyou should pass at least one filename\nuse -h for help\nEOF\n</code></pre>\n\n<p>consider making an empty_dir function</p>\n\n<pre><code>empty_dir() { \n tryexec &lt;&lt;EOF\n rm -r \"$RBIN\"\n mkdir -p \"$RBIN\"\n EOF\n\n errexit 0 \"bin emptied\"\n}\n</code></pre>\n\n<p>Consider making restore a function. and use it this way</p>\n\n<pre><code># if -r was passed, switch\nif [ \"$RESTORE\" = 1 ]; then\n restore \"$RBIN\" \"$CURR\"\nelse\n restore \"$CURR\" \"$RBIN\"\nfi\n</code></pre>\n\n<p>This should come before the previous.</p>\n\n<pre><code>nextversion(){\n local version=2\n while [ -e \"$1$version\" ]; do\n let version=$version+1\n done\n echo $version\n}\n\nrestore() {\n local in=\"$1\"\n local out=\"$2\"\n [ \"$in\" = \"$out\" ] &amp;&amp; errexit 1 \"Error: you are trying to move files to same directory\"\n local orig=\n local dest=\n\n # preparing undo file\n touch $UNDOFILE\n\n while [ \"$1\" ]; do\n\n orig=\"$IN/$(basename $1)\"\n dest=\"$OUT/$(basename $1)\"\n\n if [ -e \"$orig\" ]; then\n # if file already exists, rename it by appending a number\n if [ -e \"$dest\" ]; then\n version=$(nextversion $dest)\n tryexec &lt;&lt;EOF\n mv \"$dest\" \"$dest$version\"\n echo \"mv $dest$version $dest\" &gt;&gt; $UNDOFILE\nEOF\n warn \"moving old existing $dest to $dest$version\"\n fi\n tryexec &lt;&lt;EOF\n mv \"$orig\" \"$dest\"\n echo \"mv $dest $orig\" &gt;&gt; $UNDOFILE\nEOF\n warn \"$orig → $dest\"\n else\n warn \"file '$(basename $1)' could not be processed\"\n [ \"$ERRORSTOP\" = 1 ] &amp;&amp; errexit 1 \"there were errors\"\n fi\n shift\n done\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-21T17:31:26.363", "Id": "11063", "ParentId": "10768", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T03:08:59.483", "Id": "10768", "Score": "4", "Tags": [ "bash" ], "Title": "Bash script to send to recycle bin or trash" }
10768
<p>I have a Java class which accepts some data and reads it in as a raster of characters x by y. The class is used then to look for occurrences of a certain word in any direction of the raster and store them in a multidimensional array.</p> <p>My code works, but I would like to see the code optimized because to me it looks too cumbersome with all the <code>if</code>-<code>else</code>'s.</p> <pre><code>... private static final int NORTH = 0; private static final int NORTH_EAST = 1; private static final int EAST = 2; private static final int SOUTH_EAST = 3; private static final int SOUTH = 4; private static final int SOUTH_WEST = 5; private static final int WEST = 6; private static final int NORTH_WEST = 7; /** The raster &lt;code&gt;char[yIndex][xIndex]&lt;/code&gt; */ private char[][] raster; /** * Starts looking through the raster to find occurrences of the given word. * @param word the word to look for */ public void searchWord(String word) { if (!searched || !this.word.equals(word)) { this.word = word; this.count = 0; int w = raster[0].length, h = raster.length; for (int y=0; y&lt;h; y++) { for (int x=0; x&lt;w; x++) { this.occurrences = (int[][][]) ArrayUtils.addAll( this.occurrences, search(x, y, w, h, toLowerCase(this.word.toCharArray()))); // toLowerCase is a helper method which converts a char array // to lower case characters this.count = this.occurrences.length; } } searched = true; } } /** * Looks at a given index in the raster for the occurrence of a word to * &lt;code&gt;lookFor&lt;/code&gt;. * The word is searched horizontally, vertically and diagonally, forward and reverse. * * @param x start looking at this x-coordinate * @param y start looking at this y-coordinate * @param w width of the raster * @param h height of the raster * @param lookFor characters of the word to look for * @return the occurrences found for this word: * int [occurrenceIndex][characterIndex][x,y coordinate] */ private int [][][] search(int x, int y, int w, int h, char [] lookFor) { int len = lookFor.length, occurrences[][][] = new int [8][len][]; for (int j=0; j&lt;8; j++) { for (int i=0; i&lt;len; i++) { if (i == 0) { occurrences[j][0] = new int [] {x, y}; } else { occurrences[j][i] = new int [] {-1, -1}; } } } boolean north = y - (len-1) &gt;= 0, east = x + len &lt;= w, west = x - (len-1) &gt;= 0, south = y + len &lt;= h, northEast = north &amp;&amp; east, northWest = north &amp;&amp; west, southEast = south &amp;&amp; east, southWest = south &amp;&amp; west; for (int i=0; i&lt;lookFor.length; i++) { if (north &amp;&amp; raster[y-i][x] == lookFor[i]) { occurrences[NORTH][i][0] = x; occurrences[NORTH][i][1] = y-i; } else { occurrences[NORTH] = null; north = false; } if (northEast &amp;&amp; raster[y-i][x+i] == lookFor[i]) { occurrences[NORTH_EAST][i][0] = x+i; occurrences[NORTH_EAST][i][1] = y-i; } else { occurrences[NORTH_EAST] = null; northEast = false; } if (east &amp;&amp; raster[y][x+i] == lookFor[i]) { occurrences[EAST][i][0] = x+i; occurrences[EAST][i][1] = y; } else { occurrences[EAST] = null; east = false; } if (southEast &amp;&amp; raster[y+i][x+i] == lookFor[i]) { occurrences[SOUTH_EAST][i][0] = x+i; occurrences[SOUTH_EAST][i][1] = y+i; } else { occurrences[SOUTH_EAST] = null; southEast = false; } if (south &amp;&amp; raster[y+i][x] == lookFor[i]) { occurrences[SOUTH][i][0] = x; occurrences[SOUTH][i][1] = y+i; } else { occurrences[SOUTH] = null; south = false; } if (southWest &amp;&amp; raster[y+i][x-i] == lookFor[i]) { occurrences[SOUTH_WEST][i][0] = x-i; occurrences[SOUTH_WEST][i][1] = y+i; } else { occurrences[SOUTH_WEST] = null; southWest = false; } if (west &amp;&amp; raster[y][x-i] == lookFor[i]) { occurrences[WEST][i][0] = x-i; occurrences[WEST][i][1] = y; } else { occurrences[WEST] = null; west = false; } if (northWest &amp;&amp; raster[y-i][x-i] == lookFor[i]) { occurrences[NORTH_WEST][i][0] = x-i; occurrences[NORTH_WEST][i][1] = y-i; } else { occurrences[NORTH_WEST] = null; northWest = false; } } int [][] compareTo = new int[lookFor.length][]; for (int i=0; i&lt;lookFor.length; i++) { compareTo[i] = new int[] {-1, -1}; } ArrayList&lt;int[][]&gt; items = new ArrayList&lt;int[][]&gt;(); for (int [][] dirArray : occurrences) { if (dirArray != null) { items.add(dirArray); } } return (int[][][]) items.toArray(new int [][][] {}); } ... </code></pre>
[]
[ { "body": "<p>You could theoretically make it nicer by introducing <code>Iterator&lt;&gt;</code> concept into the code. It would make your code more optimal from readability point of view but I doubt it would make the code more optimal from execution speed point of view. Your <code>Iterator&lt;&gt;</code> interface derivates would always move to the next character in given direction. Basically, the <code>ifs</code> would be hidden behind the iterators.</p>\n\n<p>If using <code>Iterator&lt;&gt;</code> seems too heavy, you could abstract the position increments and direction into an array of (spatial) vectors. E.g., iteration increment in the north direction could be represented by <code>i * {0, +1}</code>. This way you could transform the <code>if/else</code> chain into iteration over an array of such vectors.</p>\n\n<p>I would also introduce a class for the point/coordinate instead of using two element array.</p>\n\n<p>All of this could improve the abstraction and readability. It is up to you to decide if it is worth it though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T09:39:33.463", "Id": "17194", "Score": "0", "body": "could you give an example of how I would implement the spatial vectors, I tried this already but it didn't go as expected" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T09:26:31.013", "Id": "10777", "ParentId": "10774", "Score": "2" } } ]
{ "AcceptedAnswerId": "10777", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T07:41:35.650", "Id": "10774", "Score": "3", "Tags": [ "java", "optimization", "search", "lookup" ], "Title": "Word lookup code optimization" }
10774
<blockquote> <p><strong>Task:</strong></p> <p>On an alphabet set [a-z], a simplified regular expression is much simpler than the normal regular expression. </p> <p>It has only two meta characters: '.' and '*'.</p> <blockquote> <p>'.' -- exact one arbitrary character match.</p> <p>'*' -- zero or more arbitrary character match.</p> </blockquote> <p>Note that it is different from the normal regular expression in that '<em>' is on its own and does NOT act as a decorator on the leading character, I.e. in our simplified regular expression. "</em>" is equivalent to ".*" in regular expression. Write a parser which takes a pattern string and a candidate string as input and decides to either accept or reject the candidate string based on the pattern string. </p> <ol> <li><strong>Only</strong> the <strong>full</strong> match is acceptable. The parser rejects partial matches.</li> <li>You can safely assume all the characters in both input pattern string and candidate string are valid characters, i.e. you don't need to validate the input strings.</li> <li>Your parser need to at least pass all the following test cases.</li> <li>You can write the parser in any programing language you like. </li> <li>Write up an analysis on the run-time complexity of your code.</li> </ol> <p><strong>Example:</strong></p> <pre><code>| pattern string | candidate string | result | | abc | abc | accept | | * | abc | accept | | *abc | abc | accept | | *abc | aaabbbabc | accept | | a*bc | aaabbbabc | accept | | a*bc | abc | accept | | a* | abc | accept | | a* | a | accept | | a* | aa | accept | | a* | abcdef | accept | | *abc* | abc | accept | | ***** | abc | accept | | … | abc | accept | | .* | abc | accept | | .bc* | abc | accept | | .b*c*a | abca | accept | | * | /EMPTY STRING/ | accept | | abc | abcd | reject | | *a | abcd | reject | | a | /EMPTY STRING/ | reject | | .a*c | abc | reject | | a.*b | abc | reject | | .. | abc | reject | | /EMPTY STRING/ | /EMPTY STRING/ | reject | | /EMPTY STRING/ | abc | reject | </code></pre> </blockquote> <p><strong>My Solution:</strong></p> <pre><code>public class RegxEngine { public static boolean match(String regx, String candidate) { // Empty regx will always return false if (regx.isEmpty()) { return false; } else { if (regx.charAt(0) == '*') { // Last * matches everything if (regx.length() == 1) { return true; } else { return matchStar(regx.substring(1), candidate); } } // Return false if text is empty but pattern is not * else if (candidate.isEmpty()) { return false; } else if (regx.charAt(0) == '.' || regx.charAt(0) == candidate.charAt(0)) { // If the last regx matches the last text if (regx.length() == 1 &amp;&amp; candidate.length() == 1) { return true; } // If hasn't reached the end, try to match the rest strings else { return match(regx.substring(1), candidate.substring(1)); } } else { return false; } } } // Otherwise skip as many chars as required private static boolean matchStar(String regx, String candidate) { for (int i = 0; i &lt; candidate.length(); i++) { if (match(regx, candidate.substring(i))) { return true; } else { continue; } } return false; } } </code></pre> <p>This was an interview question and I did get through to the next round. I am asking simply looking for more ideas.</p> <p><strong>My Questions:</strong></p> <ol> <li>Is my code \$O(m*n)\$, where \$m\$ is the length of the candidate string and \$n\$ is the length of the pattern string?</li> <li>In terms of performance/time complexity, could this be done better?</li> </ol>
[]
[ { "body": "<p>In answer to 1) - No. Consider the regex <code>*********a</code> and the string <code>b</code>. Your code will have to consider all 9! (362880) cases before returning false.</p>\n\n<p>That being said, this solution seems to be going in the right direction, and for this restricted language we can stop short of actually building the <a href=\"http://en.wikipedia.org/wiki/Deterministic_finite_automaton\" rel=\"nofollow\">DFA</a> equivalent to the expression. (Which is expensive in space to create, but will be cheaper each time it is run against a candidate string).</p>\n\n<p>We acheive this by caching the result of each regex-substring for future use (the <a href=\"http://en.wikipedia.org/wiki/Dynamic_programming\" rel=\"nofollow\">dynamic programming</a> approach). This prevents the problematic recursive explosion in the original problem and will guarantee an O(n*m) runtime, but could cost up to O(n*m) space for each regex candidate pair.</p>\n\n<pre><code>static Map&lt;Pair&lt;String, String&gt;, boolean&gt; result_cache;\n\n//Assume we have a pair, as in:\n//http://stackoverflow.com/a/677248/1331457\npublic static boolean match(String regx, String candidate)\n{\n Pair&lt;String, String&gt; key = Pair(regx, candidate);\n if result_cache.containsKey(key){\n return true;\n }\n boolean result = false;\n // Empty regx will always return false\n if (regx.isEmpty())\n {\n result = false;\n }\n else\n {\n if (regx.charAt(0) == '*')\n {\n // Last * matches everything\n if (regx.length() == 1)\n {\n result = true;\n }\n else\n {\n result = matchStar(regx.substring(1), candidate);\n }\n }\n // Return false if text is empty but pattern is not *\n else if (candidate.isEmpty())\n {\n result = false;\n }\n else if (regx.charAt(0) == '.' || regx.charAt(0) == candidate.charAt(0))\n {\n // If the last regx matches the last text\n if (regx.length() == 1 &amp;&amp; candidate.length() == 1)\n {\n result = true;\n }\n // If hasn't reached the end, try to match the rest strings\n else\n {\n result = match(regx.substring(1), candidate.substring(1));\n }\n }\n else\n {\n result = false; \n }\n }\n result_cache.put(key, result);\n return result;\n}\n\n//Similarly for other methods.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T15:35:58.063", "Id": "17319", "Score": "0", "body": "Thanks for the answers. You really made me think when you mentioned `*********a`. What if we preprocess the pattern string to be `*a` which is equivalent to `*********a`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T15:48:20.583", "Id": "17320", "Score": "0", "body": "This is a good first pass optimisation. But it won't help you in cases like `*.*.*.*.*.*a`, `b`. The dynamic programming approach that I suggest above should deal with both in linear time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-23T11:06:43.177", "Id": "135615", "Score": "0", "body": "@cmh can you explain why its 9!." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-23T11:13:01.333", "Id": "135617", "Score": "0", "body": "regex *********a and string b,looks like only 10 matches." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T00:13:19.377", "Id": "10880", "ParentId": "10776", "Score": "3" } }, { "body": "<p>Can you translate the regular expression into ad-hoc Java code, compile it on the fly, and then execute it?</p>\n\n<p>After it is translated and compiled, which should take less than a second, the execution will be a couple orders of magnitude faster than any data-driven parser.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T16:32:35.580", "Id": "10957", "ParentId": "10776", "Score": "0" } } ]
{ "AcceptedAnswerId": "10880", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T09:11:27.463", "Id": "10776", "Score": "5", "Tags": [ "java", "algorithm", "performance", "regex", "interview-questions" ], "Title": "Simplified regular expression engine" }
10776
<p>Please review this implementation of thread-safe chache. </p> <pre><code>public class StaticCacheImpl&lt;T extends Entity&gt; implements StaticCache&lt;T&gt; { private boolean set = false; private List&lt;T&gt; cachedObjects = Collections.synchronizedList(new ArrayList&lt;T&gt;()); @Override public synchronized boolean isSet() { return set; } @Override public synchronized void put(List&lt;T&gt; cachedList) { if (!set) { cachedObjects.addAll(cachedList); set = true; } } @Override public synchronized List&lt;T&gt; get() { return cachedObjects; } @Override public synchronized boolean contains(UUID uuid) { if(set) { for (T t : cachedObjects) { if (ObjectUtils.equals(uuid, t.getId())) { return true; } } } return false; } @Override public synchronized T getById(UUID uuid) { if(set) { for (T t : cachedObjects) { if (ObjectUtils.equals(uuid, t.getUuid())) { return t; } } } return null; } } </code></pre>
[]
[ { "body": "<ul>\n<li>Your cache can only be initialised once with the put method (hence your <code>set</code> flag): why not use a constructor instead and get rid of the flag?</li>\n<li>If 2 items with the same UUID are identical and you only need to store one of them, using a map would simplify your design a lot</li>\n<li>The map gives you an O(1) algorithm for <code>contains</code> and <code>getById</code> instead of O(n) in your code</li>\n<li>Since the class is now immutable, you don't need to synchronize the methods any more which should result in much better result in case of heavy concurrency (no lock contention)</li>\n</ul>\n\n<p>Here is what I would propose:</p>\n\n<pre><code>public class StaticCacheImpl&lt;T extends Entity&gt; implements StaticCache&lt;T&gt; \n{\n //Assumes that 2 items with the same UUID only need to be stored once\n private final Map&lt;UUID, T&gt; cache = new HashMap&lt;UUID, T&gt;();\n\n public StaticCacheImpl(List&lt;T&gt; cachedList) {\n for (T t : cachedList) {\n cache.put(t.getUuid(), t);\n } \n }\n\n @Override\n public boolean isSet() {\n return true;\n }\n\n @Override\n public void put(List&lt;T&gt; cachedList) {\n throw new IllegalStateException(\"Cache has already been set\");\n }\n\n @Override\n public List&lt;T&gt; get() {\n return new ArrayList&lt;T&gt; (cache.values()); //defensive copy\n }\n\n @Override\n public boolean contains(UUID uuid) {\n return cache.containsKey(uuid);\n }\n\n @Override\n public T getById(UUID uuid){\n return cache.get(uuid);\n }\n}\n</code></pre>\n\n<p>If you can't use a constructor and need the <code>put</code> method to work as in your original design, then the only change I would make is to use a map, but you would still need to synchronize the methods and use the set flag.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T11:34:10.737", "Id": "17197", "Score": "0", "body": "Thanks for your review. I really need put method for adding new values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T16:02:03.623", "Id": "17594", "Score": "1", "body": "why not use ehcache?? its simple, efficient and works" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T10:35:57.930", "Id": "10780", "ParentId": "10778", "Score": "5" } } ]
{ "AcceptedAnswerId": "10780", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T09:58:19.840", "Id": "10778", "Score": "4", "Tags": [ "java", "thread-safety", "cache" ], "Title": "Thread safe cache implementation" }
10778
<p>In order for me to get better and create more desired code, I would like to find out if the following situation is bad or acceptable. </p> <p>I am creating an animation that gets triggered by two buttons, one on the left of a <code>JPanel</code> and the other on the right. Depending on which button is pressed, the animation starts from the button position. </p> <p>Now it can be quite some work working out the different calculations with a lot of internal <code>if</code> and <code>else</code> statements (to know which button is clicked) on the Method that handles the animation (I have done so). </p> <p>If I clone the method and modify it to be suitable for one button (so each button calls a different method), which saves a lot of hassle, is that good or bad practise?</p> <pre><code>private void moveImage(){ if(xpos &lt; imagewidth &amp;&amp; ypos &lt; imageheight) { if(buttonA){ image.setX(image.getX() - xmove); } else { image.setX(image.getX() + xmove); } image.setY(image.getY() + ymove); } //other codes here } </code></pre> <p>Or I could do this for button A and the same for button B:</p> <pre><code>private void moveImageA(){ if(xpos &lt; imagewidth &amp;&amp; ypos &lt; imageheight) { image.setX(image.getX() - xmove); image.setY(image.getY() + ymove); } //other codes here } </code></pre>
[]
[ { "body": "<p>Depends on application design. What is \"more important\" - image, or button?</p>\n\n<p>It could be something like <code>move(Image image)</code> method in the buttons (decalred in interface of the buttons), or it may be <code>reactOn(Button button)</code> in Image.</p>\n\n<p>It is hard to recommend something with the presented information. Generally, code reuse is always a good move.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T11:43:32.390", "Id": "17199", "Score": "0", "body": "well from what your asking, i should say the image. I use one action performed method which subsequently means one paintComponent Method which draws an image. so if i press button A and later Button B. the animation might be messed up for Button B if you know what i mean since the position of the image might have changed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T13:04:06.780", "Id": "17201", "Score": "0", "body": "Anyway, hard to recommend something certain. May be, http://en.wikipedia.org/wiki/Visitor_pattern may give you an idea." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T11:38:44.340", "Id": "10782", "ParentId": "10781", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T11:20:41.560", "Id": "10781", "Score": "1", "Tags": [ "java", "image" ], "Title": "Animation that gets triggered by two buttons" }
10781
<p>This is a short class to take screenshots on mutltiple monitor systems, I made some modifications to the solution at <a href="https://stackoverflow.com/questions/10042086/screen-capture-in-java-not-capturing-whole-screen">https://stackoverflow.com/questions/10042086/screen-capture-in-java-not-capturing-whole-screen</a> so that the code coped with monitors at different hights and so on. Any and all suggestions welcome :) </p> <pre><code>/** * Code modified from code given in http://whileonefork.blogspot.co.uk/2011/02/java-multi-monitor-screenshots.html following a SE question at * https://stackoverflow.com/questions/10042086/screen-capture-in-java-not-capturing-whole-screen */ import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; import java.awt.Robot; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; class ScreenCapture { static int numberOfMinutesToSleepBetweenScreenshots = 4; public static void main(String args[]) throws Exception { int i = 1000; while (true) { takeScreenshot("ScreenCapture" + i++); try { Thread.sleep(60 * numberOfMinutesToSleepBetweenScreenshots * 1000); } catch (Exception e) { e.printStackTrace(); } } } public static void takeScreenshot(String filename) throws Exception { // Okay so all we have to do here is find the screen with the lowest x, // the screen with the lowest y, the screen with the higtest value of X+ // width and the screen with the highest value of Y+height GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] screens = ge.getScreenDevices(); Rectangle allScreenBounds = new Rectangle(); int farx = 0; int fary = 0; for (GraphicsDevice screen : screens) { Rectangle screenBounds = screen.getDefaultConfiguration().getBounds(); //finding the one corner if (allScreenBounds.x &gt; screenBounds.x) { allScreenBounds.x = screenBounds.x; } if (allScreenBounds.y &gt; screenBounds.y) { allScreenBounds.y = screenBounds.y; } //finding the other corner if (farx &lt; (screenBounds.x + screenBounds.width)) { farx = screenBounds.x + screenBounds.width; } if (fary &lt; (screenBounds.y + screenBounds.height)) { fary = screenBounds.y + screenBounds.height; } allScreenBounds.width = farx - allScreenBounds.x; allScreenBounds.height = fary - allScreenBounds.y; } Robot robot = new Robot(); BufferedImage screenShot = robot.createScreenCapture(allScreenBounds); ImageIO.write(screenShot, "jpg", new File(filename + ".jpg")); } } </code></pre> <p>EDIT - thank you everybody, upvotes for all! </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-16T20:20:06.853", "Id": "146024", "Score": "0", "body": "Use and Area to \"add\" all the Rectangles together, it's a lot simpler and will give you the same result" } ]
[ { "body": "<p>I understand the need for descriptive variable names, but perhaps <code>numberOfMinutesToSleepBetweenScreenshots</code> is taking it a bit too far. Using something like <code>minsBetweenShots</code> or something like that is nearly as descriptive, and in the context of the other code will be clear enough for any programmer who puts forth any effort to understand the code.</p>\n\n<p>In general though, the code is organized pretty well and I would feel comfortable working with it if I had to.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T14:52:17.173", "Id": "10788", "ParentId": "10783", "Score": "3" } }, { "body": "<pre><code>public static void takeScreenshot(String filename) throws Exception {\n</code></pre>\n\n<p>Do not catch or throw generic Exceptions whenever possible. Be explicit about the possible problems.</p>\n\n<pre><code>public static void main(String args[]) throws Exception {\n</code></pre>\n\n<p>That's bad. Your main function should not throw exceptions, but rather handle them gracefully. I assume this is a off-the-shelf template, you should stop doing that (just adding <code>throws Exception</code> and being done with it).</p>\n\n<pre><code>int i = 1000;\nwhile (true) {\n takeScreenshot(\"ScreenCapture\" + i++);\n</code></pre>\n\n<p>I know it's minor, but variables with names like <code>i</code>, <code>j</code> or <code>arr</code> give me the creeps. This variable might be better named <code>counter</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T23:04:20.867", "Id": "17390", "Score": "2", "body": "+1 for exceptions / -1 for i -> counter. I'll make it an average of 1 anyway ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T06:53:43.373", "Id": "17394", "Score": "0", "body": "@assylias: I like your math. ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T08:39:13.403", "Id": "10814", "ParentId": "10783", "Score": "5" } }, { "body": "<pre><code>public static void takeScreenshot(String filename) throws Exception {\n</code></pre>\n\n<p>This method is quite long and performs several tasks. I would consider moving some parts to separate methods. For example; move all code used for calculating the <code>allScreenBounds</code> variable into a new method:</p>\n\n<pre><code>private Rectangle getAllScreenBounds() {\n ...\n}\n</code></pre>\n\n<p>Your <code>takeScreenshot</code> method would then look like</p>\n\n<pre><code>public static void takeScreenshot(String filename) throws Exception {\n Robot robot = new Robot();\n BufferedImage screenShot = robot.createScreenCapture(getAllScreenBounds());\n ImageIO.write(screenShot, \"jpg\", new File(filename + \".jpg\"));\n}\n</code></pre>\n\n<p>I would also consider creating a method called something like <code>GraphicsDevice[] getScreens()</code> containing</p>\n\n<pre><code>GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();\nGraphicsDevice[] screens = ge.getScreenDevices();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T21:07:15.850", "Id": "10835", "ParentId": "10783", "Score": "3" } }, { "body": "<p>I would start by replacing the call to <code>Thread.sleep(...);</code> with a call to <code>TimeUnit.MINUTES.sleep(...);</code> which is much easier to read, also because <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">magic numbers</a> are evil.</p>\n\n<p>You can simplify your for loop by replacing all of the corner logic with a call to <a href=\"http://docs.oracle.com/javase/6/docs/api/java/awt/Rectangle.html#add(java.awt.Rectangle)\" rel=\"nofollow noreferrer\">#add(Rectangle)</a>, e.g.</p>\n\n<pre><code>for (GraphicsDevice screen : screens) {\n Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();\n allScreenBounds.add(screenBounds);\n}\n</code></pre>\n\n<p>You should pay close attention to the documentation though, as there are some \"gotchas\" in there.</p>\n\n<p>Of course, <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#min%28int,%20int%29\" rel=\"nofollow noreferrer\">min</a> and <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#max%28int,%20int%29\" rel=\"nofollow noreferrer\">max</a> would work just as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-19T09:37:59.333", "Id": "11003", "ParentId": "10783", "Score": "3" } }, { "body": "<p>From reading <a href=\"http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html\" rel=\"nofollow\">this</a>, your code seems all wrong, I could be mistaken.</p>\n\n<p>If you want to create a screenshot for a specific Screen, then you need to create an instance of Robot with that Screen ( <code>public Robot(GraphicsDevice screen) throws AWTException</code> ) and then do the screen-capture.</p>\n\n<p>As for finding the bounds for that screen, have you empirically found that just using <code>screen.getDefaultConfiguration().getBounds();</code> is not working? It does not make sense that you derive the bounds by getting the extremes from all available screens.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T18:16:06.163", "Id": "24255", "ParentId": "10783", "Score": "0" } } ]
{ "AcceptedAnswerId": "10814", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T13:06:51.647", "Id": "10783", "Score": "6", "Tags": [ "java" ], "Title": "Java screengrab" }
10783
<p>You can see each list item has multiple attributes data-whatever. The user will choose from a dropdown box on how things should be sorted and the appropriate method is called. Is <code>eval()</code> the most appropriate choice for this or is there a better way? </p> <pre><code>$('#sort-options').change(function() { var sortType = $(this).val(); var $selectedList = $($(".drop-zone.ui-tabs-selected a").attr('href')).find('.connectedSortable'); var $listItems = $('li', $selectedList); //Sort var sortFunction = null; switch (sortType) { case 'custom': $listItems.sort(sortCustom); break; case 'breed': $listItems.sort(sortBreed); break; case 'hatch': $listItems.sort(sortHatch); break; case 'laid': $listItems.sort(sortLaid); break; default: $listItems.sort(sortCustom); } //Empty UL $selectedList.empty(); //Repopulate UL $.each($listItems, function(index, $listItem) { $selectedList.append($listItem); }); }); function sortCustom(a, b) { return $(a).attr('data-sort-order') - $(b).attr('data-sort-order'); } function sortBreed(a, b) { return $(a).attr('data-breed') - $(b).attr('data-breed'); } function sortHatch(a, b) { return $(a).attr('data-hatch') - $(b).attr('data-hatch'); } function sortLaid(a, b) { return $(a).attr('data-laid') - $(b).attr('data-laid'); } //Force initial sort $('#sort-options').trigger('change'); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T14:16:56.623", "Id": "17206", "Score": "0", "body": "as a note, avoid calling jquery in your sort method. this will greatly slow down the sort process.... `return $(a).attr('data-breed') - $(b).attr('data-breed');` can be replaced with `return a.getAttribute('data-breed') - b.getAttribute('data-breed');` which is 10X faster." } ]
[ { "body": "<pre><code>function makeSorter(sortType) {\n sortType = \"data-\"+sortType;\n return function (a, b) {\n return $(a).attr(sortType) - $(b).attr(sortType);\n };\n}\n\n$('#sort-options').change(function () {\n var sortType = $(this).val();\n var $selectedList = $($(\".drop-zone.ui-tabs-selected a\").attr('href')).find('.connectedSortable');\n var $listItems = $('li', $selectedList);\n\n $listItems.sort(makeSorter(sortType));\n</code></pre>\n\n<p>Note that if <code>val</code> is <code>\"custom\"</code> it won't work, so I recommend replacing <code>\"custom\"</code> with \"<code>sort-order</code>\".</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T16:44:24.343", "Id": "17216", "Score": "0", "body": "Ultimately used jfriend's method but this was useful to me as I didn't know you could return functions in JS. Thanks for the response!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T16:46:53.170", "Id": "17217", "Score": "0", "body": "@Omar functions behave like any other object in javascript. The only unique thing about them is that they can be called. You can return them, pass them as arguments, assign them to a variable and so on." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T15:04:33.600", "Id": "10789", "ParentId": "10786", "Score": "2" } }, { "body": "<p>If you define the sort function inline as an anonymous function, you can use a local variable to determine the attribute to sort on like this:</p>\n\n<pre><code>$('#sort-options').change(function() {\n var sortType = $(this).val(), sortAttribute;\n if (sortType == \"custom\") {\n sortAttribute = \"data-sort-order\";\n } else {\n sortAttribute = \"data-\" + sortType;\n }\n var $selectedList = $($(\".drop-zone.ui-tabs-selected a\").attr('href')).find('.connectedSortable');\n var $listItems = $('li', $selectedList);\n\n $listItems.sort(function(a, b) {\n return a.getAttribute(sortAttribute) - b.getAttribute(sortAttribute);\n });\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T15:06:06.990", "Id": "10790", "ParentId": "10786", "Score": "1" } } ]
{ "AcceptedAnswerId": "10790", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T14:10:36.087", "Id": "10786", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "Too many JavaScript sort functions to accomplish the same type of sorting" }
10786
<p>I am trying to go through the problems on CodeChef and came across this <a href="http://www.codechef.com/problems/COINS" rel="nofollow">problem</a>:</p> <blockquote> <p>In Byteland they have a very strange monetary system. Each Bytelandian gold coin has an integer number written on it. A coin n can be exchanged in a bank into three coins: n/2, n/3 and n/4. But these numbers are all rounded down (the banks have to make a profit). You can also sell Bytelandian coins for American dollars. The exchange rate is 1:1. But you can not buy Bytelandian coins. You have one gold coin. What is the maximum amount of American dollars you can get for it?</p> </blockquote> <p>I approached it using the following algorithm:</p> <ol> <li><p>Check if the total amount on gold coin is greater than (Total/2)+(Total/3)+(Total/4), return total amount on gold coin.</p></li> <li><p>Otherwise, recursively evaluate the maximum total amounts for (Total/2),(Total/3) and (Total/4) and return the sum total of these maximums.</p></li> </ol> <p>My attempt:</p> <pre><code>public class ByteLandGold{ public static void main(String[] args){ System.out.println("Printing the bytelandian equivalent for:"); int byteLandCoin = Integer.parseInt(args[0]); System.out.println(ByteLandianConversion(byteLandCoin)); } private static int ByteLandianConversion(int goldCoinAmount){ int halfValue = (goldCoinAmount/2); int thirdValue = (goldCoinAmount/3); int fourthValue = (goldCoinAmount/4); int totalIntermediate = halfValue + thirdValue + fourthValue; if(goldCoinAmount &gt; totalIntermediate) return goldCoinAmount; else{ int maxHalfPortion = ByteLandianConversion(halfValue); int maxThirdPortion = ByteLandianConversion(thirdValue); int maxFourthPortion = ByteLandianConversion(fourthValue); return maxHalfPortion+maxThirdPortion+maxFourthPortion; } } } </code></pre> <p>One thing that I see in my code is that the recursive steps are calculating the overlapping sub-problems repeatedly. What would be one way to ensure that doesn't happen? Can somebody go through my code and give me some pointers on how to optimize it further and what can I change this snippet to solve it in a better way?</p>
[]
[ { "body": "<p>If you don't want to recompute the overlapping sub-problems, you could use a cache.</p>\n\n<p>Create the cache in your class:</p>\n\n<pre><code>private HashMap&lt;int, int&gt; resultCache = new HashMap&lt;int, int&gt;();\n</code></pre>\n\n<p>Then check it at the top of the function:</p>\n\n<pre><code>if (resultCache.contains(goldCoinAmount)) return resultCache.get(goldCoinAmount);\n</code></pre>\n\n<p>And before returning a result, cache it:</p>\n\n<pre><code>if(goldCoinAmount &gt; totalIntermediate)\n resultCache.put(goldCoinAmount, goldCoinAmount);\n return goldCoinAmount;\nelse{\n int maxHalfPortion = ByteLandianConversion(halfValue);\n int maxThirdPortion = ByteLandianConversion(thirdValue);\n int maxFourthPortion = ByteLandianConversion(fourthValue);\n\n int result = maxHalfPortion+maxThirdPortion+maxFourthPortion;\n resultCache.put(goldCoinAmount, result);\n return result;\n}\n</code></pre>\n\n<p>Otherwise, your code is really fairly straightforward and thus fairly readable/maintainable. Readability is far more important than raw performance most of the time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T17:15:37.470", "Id": "10799", "ParentId": "10787", "Score": "5" } } ]
{ "AcceptedAnswerId": "10799", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T14:40:05.690", "Id": "10787", "Score": "3", "Tags": [ "java", "optimization", "algorithm", "programming-challenge" ], "Title": "ByteLandian challenge from CodeChef" }
10787
<p>I'm trying to develop an algorithm that generates a 16-digit validation number to interact with a given system.</p> <p>This is how the algorithm should be implemented:</p> <p><img src="https://i.stack.imgur.com/QKwmh.png" alt="Validation Algorithm"></p> <p>I have implemented it, and have it working with 2 of 3 test cases that I have found (I will post them below).</p> <p>The implementations goes as:</p> <pre><code>public static String Generate(byte[] _MachineId, byte[] _SN) { try { byte[] step1 = new byte[6] { _SN[2], _SN[1], _SN[0], _MachineId[2], _MachineId[1], _MachineId[0] }; byte[] step2 = new byte[6] { step1[0], step1[1], (byte)(step1[2] ^ step1[0]), (byte)(step1[3] ^ step1[1]), (byte)(step1[4] ^ step1[0]), (byte)(step1[5] ^ step1[1]) }; var crc45 = new byte[2] { step2[4], step2[5] }.GetCRCAsByteArray(0); var crc23 = new byte[2] { step2[2], step2[3] }.GetCRCAsByteArray(0); var crc01 = new byte[2] { step2[0], step2[1] }.GetCRCAsByteArray(0); byte[] step3 = new byte[6] { crc01[0], crc01[1], crc23[0], crc23[1], crc45[0], crc45[1] }; string bin_to_BCD_543 = ((uint)((((0x00 &lt;&lt; 4) | step3[5]) &lt;&lt; 16) | ((step3[4] &lt;&lt; 8) | step3[3]))).ToString().PadLeft(8, '0'); string bin_to_BCD_210 = ((uint)((((0x00 &lt;&lt; 4) | step3[2]) &lt;&lt; 16) | ((step3[1] &lt;&lt; 8) | step3[0]))).ToString().PadLeft(8, '0'); String step4pre = bin_to_BCD_543 + bin_to_BCD_210; Func&lt;String, int[]&gt; convertToIntArray = new Func&lt;string, int[]&gt;( (str) =&gt; { List&lt;int&gt; result = new List&lt;int&gt;(); foreach (var c in str.ToCharArray()) result.Add(int.Parse(c.ToString())); return result.ToArray(); } ); int[] step4 = convertToIntArray(step4pre); int[] step5 = step4.ToList().ToArray(); step5[8] = step4[8] | ((step4.ToList().GetRange(8, 8).Sum() % 5) &lt;&lt; 1); step5[0] = step4[0] | ((step4.ToList().GetRange(0, 8).Sum() % 5) &lt;&lt; 1); String validation = String.Join("", step5); return validation; } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Error generating Validation number. Error =&gt; " + exc.ToString()); } return ""; } </code></pre> <p>This, are the 2 test cases that I have working:</p> <pre><code>ID = {0x21, 0x43, 0x65}, SN = {0x01, 0x00, 0x00} -&gt; VN = "6429188185446104" ID = {0x21, 0x43, 0x65}, SN = {0x02, 0x00, 0x00} -&gt; VN = "2701773123879856" </code></pre> <p>I have found a 3rd case in another document, that should satisfy this:</p> <pre><code>ID = {0x01, 0x00, 0x10}, SN = {0x99, 0x00, 0x00} -&gt; VN = "0230633823748784" </code></pre> <p>But this one does not works for me, so my questions are:</p> <ul> <li>Is the algorithm implementation OK in terms of satisfying the requirements? </li> <li>How can this implementation be improved?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T15:12:06.977", "Id": "17210", "Score": "0", "body": "What does yours return for the last case?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-18T11:15:31.707", "Id": "171054", "Score": "0", "body": "I would say that 3rd case example is faulty since your algorith diagram and example is from official SAS documentation." } ]
[ { "body": "<p>The algorithm seems to be fine, and if it does not fail the tests it should be OK (try to get more test cases though).</p>\n\n<p>Regarding the implementation:</p>\n\n<ol>\n<li><p><strong>Indentation</strong> - not sure if it just the site or you deliberately placed your curly braces the way they are placed, but it they certainly look weird, especially with the array initialization. You should indent when there is a new block, no matter what. </p></li>\n<li><p><strong>Use <code>var</code></strong> in place of explicit types - makes reading and refactoring easier.</p></li>\n<li><p><strong>Argument names</strong> - In the C# world, the <code>_variable</code> naming conventionally means a private member variable. Even if you choose not to honor that convention, your argument names are very confusing. Instead of 1-2 letter abbreviations you should use descriptive names.</p></li>\n<li><p><strong>Too long</strong> - split into multiple methods. It doesn't matter that they are only called once: descriptive function names will give you a \"bird's view\" of the algorithm. Also, you should not use <code>Func</code> just because you can; it's cool, but code is better when not cool but clear, so turn that into a normal method.</p></li>\n<li><p><strong>Explain the padding part in a comment</strong> - it is actually a nice solution, but a bit counter-intuitive (my first thought was: why would you convert to string to just convert back?, but it's actually cleaner than filling the padding zeros by hand).</p></li>\n<li><p><strong><code>step4.ToList().ToArray()</code></strong> - is a confusing (and half as fast) way of saying <code>step4.Clone()</code>. BTW it wouldn't hurt to just use <code>List</code>s and avoid the other <code>ToList</code> calls as well.</p></li>\n<li><p>I would argue that you don't need the try-catch block around the whole method, since the only thing that looks like it could throw is your CRC calls, so you should only handle that part. If anything else throws, it's better if it's ugly and noisy (a.k.a. don't catch it; clients who call your method will get the empty string back and no other indication of failure, which is not really a good practie.</p></li>\n<li><p>Use XML documentation comments for the method to document purpose, return value, arguments.</p></li>\n<li><p>Make sure that a <code>public static</code> method is appropriate for your needs. Instead of <code>public</code>, you might want to use <code>internal</code>. And remember, you can't override static methods in derived classes, so you can't take advantage of polymorphism later.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T16:48:31.560", "Id": "17218", "Score": "0", "body": "1. the indentation was broken when it was posted, I will try to fix it here.\n7. the whole method is surrounded by try/catch, as this method is only used by us, and on a module that handles money among other things, and although I like what u suggest, in this case it's better that the method does not work, than the program crashing somewhere else!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T17:33:44.390", "Id": "17225", "Score": "1", "body": "When the program crashes somewhere else, you will have an exception object that contains the call stack. If that's still not acceptable, you should surround the call to this method and handle specialized `Exception` classes. Handling exceptions the way you do does not *prevent* them, it just makes them invisible. If something weird happens, like you run out of memory, you would not want to continue running the program anyway. The best you can do is fail gracefully." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T16:22:07.973", "Id": "10795", "ParentId": "10791", "Score": "3" } }, { "body": "<p>The following section of code can be reduced/simplified:</p>\n\n<pre><code>Func&lt;String, int[]&gt; convertToIntArray =\n new Func&lt;string, int[]&gt;(\n (str) =&gt;\n {\n List&lt;int&gt; result = new List&lt;int&gt;();\n foreach (var c in str.ToCharArray()) result.Add(int.Parse(c.ToString()));\n return result.ToArray();\n }\n );\nint[] step4 = convertToIntArray(step4pre);\n</code></pre>\n\n<p>First, I would change the body of the function to use LINQ. Then, since the function is only used in one place, I would in-line it:</p>\n\n<pre><code>var step4 = step4pre.ToCharArray().Select(c =&gt; int.Parse(c.ToString())).ToArray();\n</code></pre>\n\n<p>Next, if performance isn't a huge issue, I would drop the <code>ToCharArray</code>, as string implements <code>IEnumerable&lt;char&gt;</code> already:</p>\n\n<pre><code>var step4 = step4pre.Select(c =&gt; int.Parse(c.ToString())).ToArray();\n</code></pre>\n\n<p>Finally, as it turns out, there is a function called <a href=\"https://msdn.microsoft.com/en-us/library/e7k33ktz.aspx\" rel=\"nofollow\">Char.GetNumericValue(char)</a> which retrieves the numeric value of a character for you, so you could use the following alternative: </p>\n\n<pre><code>var step4 = step4pre.Select(c =&gt; (int) char.GetNumericValue(c)).ToArray();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-18T18:30:00.290", "Id": "94008", "ParentId": "10791", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T13:50:52.233", "Id": "10791", "Score": "2", "Tags": [ "c#", "algorithm", "bitwise" ], "Title": "Algorithm with byte shifts and BCD calculation" }
10791
<p>I'm trying to implement a function that given a data frame returns the same data frame with four columns added. These new four columns are: for each row, I get the maximum element and its index and put them as two new columns. I do the same with the second maximum element. I don't care if they are repeated.</p> <pre><code>add_2max &lt;- function(x) { max1 = max(x, na.rm=TRUE) indmax1 = which.max(x) y=x[-c(indmax1)] max2 = max(y, na.rm=TRUE) indmax2 = which(x==max2) indmax2 = ifelse(max1==max2, indmax2[2], indmax2[1]) x=c(x, max1, max2, indmax1, indmax2) return (x) } add_2max_df &lt;- function(DF) { NewDF=t(apply(DF, 1, add_2max)) return(NewDF) } </code></pre> <p>I'm sure this code can be improved. What do you recommend in order to do that? Is it fast enough?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T15:41:19.917", "Id": "17211", "Score": "0", "body": "`ifelse` is notoriously slow, but since its working on a single row it shouldn't be an issue. As far as you last question... is it fast enough for you?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T15:48:30.160", "Id": "17213", "Score": "0", "body": "That's the line I'd like to avoid @Justin, but it seems not being an issue due to the fact that it's working on a single row as you've said. Thank you!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T16:39:06.300", "Id": "17215", "Score": "0", "body": "Just goes to show we all could use a modified `which.max(x,nth_biggest)` function." } ]
[ { "body": "<p>Here's a faster way:</p>\n\n<pre><code>add_2maxFaster &lt;- function(x)\n{\n imax1 &lt;- which.max(x)\n imax2 &lt;- which.max(x[-imax1])\n if (imax2 &gt;= imax1) imax2 &lt;- imax2 + 1L\n c(x, x[imax1], x[imax2], imax1, imax2) \n}\n\nset.seed(42)\nm &lt;- matrix(runif(1e6), 1e4)\n\n# Compare speed:\nsystem.time( a1&lt;-apply(m, 1, add_2max) ) # 0.38 secs\nsystem.time( a2&lt;-apply(m, 1, add_2maxFaster) ) # 0.15 secs\n\n# ...And compare results\nall.equal(a1,a2) # TRUE\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T16:07:05.793", "Id": "10794", "ParentId": "10792", "Score": "5" } }, { "body": "<p>Here is a more compact version:</p>\n\n<pre><code>add_2maxBrian &lt;- function(x) {\n r &lt;- order(x, decreasing=TRUE)\n c(x, x[r[1:2]], r[1:2])\n}\n</code></pre>\n\n<p>With some sample data (different than Tommy's because I want the chance of ties):</p>\n\n<pre><code>set.seed(123)\nDF &lt;- as.data.frame(matrix(sample(1:20, 10000, replace=TRUE), 2500, 4))\n</code></pre>\n\n<p>It's not as fast a Tommy's solution, but still faster than the original.</p>\n\n<pre><code>library(\"rbenchmark\")\n\nbenchmark(a1 &lt;- t(apply(DF, 1, add_2max)),\n a2 &lt;- t(apply(DF, 1, add_2maxFaster)),\n a3 &lt;- t(apply(DF, 1, add_2maxBrian)),\n order = \"relative\")\n# test replications elapsed relative user.self\n#2 a2 &lt;- t(apply(DF, 1, add_2maxFaster)) 100 6.537 1.000000 6.441\n#3 a3 &lt;- t(apply(DF, 1, add_2maxBrian)) 100 8.259 1.263424 8.073\n#1 a1 &lt;- t(apply(DF, 1, add_2max)) 100 12.168 1.861404 12.038\n# sys.self user.child sys.child\n#2 0.067 0 0\n#3 0.082 0 0\n#1 0.089 0 0\nidentical(a1, a2) #TRUE\nidentical(a1, a3) #TRUE\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T17:34:03.543", "Id": "17226", "Score": "0", "body": "Great @Brian Diggs. Pretty compact and simple. I like a lot." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T17:00:29.343", "Id": "10797", "ParentId": "10792", "Score": "4" } } ]
{ "AcceptedAnswerId": "10797", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T15:32:01.997", "Id": "10792", "Score": "4", "Tags": [ "r" ], "Title": "Returning an existing data frame with four new columns" }
10792
<p>Question:</p> <blockquote> <p>You are given an array that represents bills in certain currency (for example <code>1, 2, 5, 10</code>) and an amount, for example <code>17</code>. You should output the number of possible combinations of bills that sum to the given amount.</p> </blockquote> <p>Answer: </p> <blockquote> <p><code>{2, 5, 10}</code></p> </blockquote> <p>Can I optimize/improve below code? Current complexity is: O(2<sup>(n-1)</sup>), where <code>n</code> is the bill list length.</p> <pre><code>//Returns possible Bills List public static List&lt;Set&lt;Integer&gt;&gt; possibleBills(Integer amount, int[] bills){ List&lt;Set&lt;Integer&gt;&gt; result = new ArrayList&lt;Set&lt;Integer&gt;&gt;(); if(amount &lt; 0){ return null; } if(bills.length == 0){ return null; } if(amount-bills[0] == 0){ Set&lt;Integer&gt; set = new TreeSet&lt;Integer&gt;(); set.add(bills[0]); result.add(set); return result; } //Include 0'th bill and generate possible bills List&lt;Set&lt;Integer&gt;&gt; result1 = possibleBills(amount - bills[0], Arrays.copyOfRange(bills, 1, bills.length)); if(result1 != null){ Iterator&lt;Set&lt;Integer&gt;&gt; result1Itr = result1.iterator(); while(result1Itr.hasNext()){ Set&lt;Integer&gt; set = result1Itr.next(); set.add(bills[0]); } result.addAll(result1); } //exclude 0'th bill and generate possible bills List&lt;Set&lt;Integer&gt;&gt; result2 = possibleBills(amount, Arrays.copyOfRange(bills, 1, bills.length)); if(result2 != null){ result.addAll(result2); } if(result.size() == 0){ return null; } return result; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T18:03:30.817", "Id": "22524", "Score": "0", "body": "I assume this is somewhat theoretical problem, because for anything real-world A) you could make some assumptions, B) You are not likely to have to support Zimbabwean dollars that experienced high inflation; maybe only USD, C) You can get away with giving change using only 1s, 2s, 5s, 10s, 20s, 50s, 100s, 200s, 500s, ... (some of these might not exist), so you can actually use a greedy algorithm. I just got a change of (2 $5 bills instead of a single $10) this morning from an auto-register and I did not complain. The complexity almost does not matter; with cash-back limits it is actually O(1)." } ]
[ { "body": "<p>You could do some dynamic programming solution.</p>\n\n<p>The basic idea of it in this situation would be you keep track of what you can get with just the 1 dollar bill, then figure out where you can reach with the 2 dollar bill, then the 5 dollar bill. (For the sake of example, I'll use a 7 dollar bill as well as the one's you have in you example)</p>\n\n<p>So, for example you would start with an array of size 18. Because you can reach 0 dollars, you would have</p>\n\n<pre><code>1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n</code></pre>\n\n<p>then with the 1 dollar bill you can reach 0 dollars and 1 dollar</p>\n\n<pre><code>1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n</code></pre>\n\n<p>then with the 2 dollar bill and the 1 dollar bill you can reach 0,1,2,or 3 dollars</p>\n\n<pre><code>1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n</code></pre>\n\n<p>then with the 5,2, and 1 dollar bill you can reach 0,1,2,3,5,6,7,or 8 dollars</p>\n\n<pre><code>1,1,1,1,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0\n</code></pre>\n\n<p>then, with the 7 dollar bill: you can reach 7 and 8 in two ways</p>\n\n<pre><code>1,1,1,1,0,1,1,2,2,1,1,0,1,1,1,1,0,0,0\n</code></pre>\n\n<p>10 dollar bill</p>\n\n<pre><code>1,1,1,1,0,1,1,2,2,1,2,1,2,2,1,2,1,2,2\n</code></pre>\n\n<p>So, there are two ways to reach 18</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T20:34:08.923", "Id": "17250", "Score": "0", "body": "What would be the time complexity of your algorithm?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T00:46:17.923", "Id": "17255", "Score": "0", "body": "Well, it would be, when optimized, O(n*s), where n is in the number of bills and s is the target amount. But I think you could probably optimize it to O(n^2)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T00:21:00.487", "Id": "10806", "ParentId": "10793", "Score": "2" } }, { "body": "<p>Here's a more traditional (heavyweight) OOP treatment of the problem. Note that it produces duplicates due to permutations. The fix is to change <code>BillSetList</code> into <code>BillSetSet</code> or manually remove duplicates at the end. Both classes are immutable to make the code safer. You could also clean some of it up a bit by using Guava's collection helper methods.</p>\n\n<pre><code>import java.util.*;\n\nclass BillSet\n{\n static final BillSet EMPTY = new BillSet();\n\n final Set&lt;Integer&gt; bills;\n\n BillSet() {\n this(new TreeSet&lt;Integer&gt;());\n }\n\n BillSet(int bill) {\n this(Collections.singleton(bill));\n }\n\n BillSet(int... bills) {\n this(new TreeSet&lt;Integer&gt;());\n for (int bill : bills) {\n this.bills.add(bill);\n }\n } \n\n BillSet(Set&lt;Integer&gt; bills) {\n this.bills = bills;\n }\n\n BillSet with(int bill) {\n if (bills.contains(bill)) {\n return this;\n }\n if (bills.isEmpty()) {\n return new BillSet(bill);\n }\n Set&lt;Integer&gt; newBills = new TreeSet&lt;Integer&gt;();\n newBills.addAll(bills);\n newBills.add(bill);\n return new BillSet(newBills);\n }\n\n BillSet without(int bill) {\n if (!bills.contains(bill)) {\n return this;\n }\n if (bills.size() == 1) {\n return EMPTY;\n }\n Set&lt;Integer&gt; newBills = new TreeSet&lt;Integer&gt;();\n newBills.addAll(bills);\n newBills.remove(bill);\n return new BillSet(newBills);\n }\n\n BillSetList subsetsAddingTo(int sum) {\n if (bills.isEmpty()) {\n return BillSetList.EMPTY;\n }\n BillSetList subsets = new BillSetList();\n for (int bill : bills) {\n if (bill == sum) {\n subsets = subsets.with(new BillSet(bill));\n }\n else if (bill &lt; sum) {\n subsets = subsets.with(without(bill).subsetsAddingTo(sum - bill).with(bill));\n }\n }\n return subsets;\n }\n\n void print() {\n for (int bill : bills) {\n System.out.print(bill + \" \");\n }\n System.out.println();\n }\n\n public static void main(String[] args) {\n BillSet set = new BillSet(1, 2, 5, 10);\n BillSetList subsets = set.subsetsAddingTo(17);\n subsets.print();\n }\n}\n\nclass BillSetList\n{\n static final BillSetList EMPTY = new BillSetList();\n\n final List&lt;BillSet&gt; sets;\n\n BillSetList() {\n this(new ArrayList&lt;BillSet&gt;());\n }\n\n BillSetList(List&lt;BillSet&gt; sets) {\n this.sets = sets;\n }\n\n BillSetList(BillSet... sets) {\n this();\n for (BillSet set : sets) {\n this.sets.add(set);\n }\n }\n\n BillSetList with(int bill) {\n if (sets.isEmpty()) {\n return this;\n }\n List&lt;BillSet&gt; newSets = new ArrayList&lt;BillSet&gt;(sets.size());\n for (BillSet set : sets) {\n newSets.add(set.with(bill));\n }\n return new BillSetList(newSets);\n }\n\n BillSetList with(BillSet set) {\n return with(new BillSetList(set));\n }\n\n BillSetList with(BillSetList otherSets) {\n if (sets.isEmpty()) {\n return otherSets;\n }\n if (otherSets.sets.isEmpty()) {\n return this;\n }\n List&lt;BillSet&gt; newSets = new ArrayList&lt;BillSet&gt;(sets.size() + otherSets.sets.size());\n newSets.addAll(sets);\n newSets.addAll(otherSets.sets);\n return new BillSetList(newSets);\n }\n\n void print() {\n for (BillSet set : sets) {\n set.print();\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T20:37:58.263", "Id": "17252", "Score": "0", "body": "I am not seeing any improvement in the algorithm, just better OOP. Am i missing something here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T22:18:52.590", "Id": "17254", "Score": "0", "body": "It's slightly different, but I posted it to show an OOP approach. Looking again at your algorithm, I could avoid the duplicates by using the method of including/excluding the first bill in each set and making only two recursive calls." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T03:46:39.603", "Id": "10810", "ParentId": "10793", "Score": "1" } }, { "body": "<p>Just two random notes:</p>\n\n<ol>\n<li><p>Instead of returning with null I'd throw <code>IllegalArgumentException</code> with a detailed error message when <code>amount &lt; 0</code> or <code>bills.length == 0</code>. The message would help debugging and would not cause <code>NullPointerException</code>s later when somebody try to use the returned value.</p></li>\n<li><p>You also should not return with <code>null</code> when <code>result.size()</code> is zero. From <em>Effective Java, 2nd Edition, Item 43: Return empty arrays or collections, not nulls</em>:</p>\n\n<blockquote>\n <p>In summary, <strong>there is no reason ever to return null from an array- or\n collection-valued method instead of returning an empty \n array or collection.</strong></p>\n</blockquote></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T19:45:56.130", "Id": "13946", "ParentId": "10793", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T16:01:28.870", "Id": "10793", "Score": "3", "Tags": [ "java", "algorithm", "interview-questions" ], "Title": "Possible combinations of bills that sum to the given amount" }
10793
<p>I'm new to production code. And also I'm learning how to test code, I'll use the unittest module that comes with python to do that. One more question, how can I make this code more safe?</p> <pre><code> """ Sync your iTunes files with your Android """ import os, string, re, shutil from ctypes import windll def get_drives(): drives = [] bitmask = windll.kernel32.GetLogicalDrives() for letter in string.uppercase: if bitmask &amp; 1: drives.append(letter) bitmask &gt;&gt;= 1 return drives def get_android_dir(): android_devices = [] drives = get_drives() for drive in drives: path = drive + ':\\' try: drive_dirs = os.listdir(path) for diry in drive_dirs: if re.compile('android_secure', re.IGNORECASE).search(diry) != None: android_devices.append(path) #print path, 'is an Android device' #print drive_dirs break except WindowsError: pass return android_devices def all_files_from_path_filtered(path): #files = [] files = set() #print os.listdir(itunes_dir) for dirpath, dirname, filenames in os.walk(path): for filename in filenames: if dirpath[-3:]!='tmp': # don't add files that are still been downloader files.add(Filedata(filename, dirpath)) else: print 'Not syncing', dirpath.split('\\')[-1], "it's still downloading" return files def files_to_be_uploaded(itunes_dir, android_dir): itunes_set = all_files_from_path_filtered(itunes_dir) android_set = all_files_from_path_filtered(android_dir) #print 'iTunes Set', len(itunes_set), itunes_set #print 'Android Set', len(android_set), android_set to_upload_files = list(itunes_set.difference(android_set)) return to_upload_files class Filedata(object): def __init__(self, filename, path): self.filename = filename self.path = path + '\\' + filename def __eq__(self, other): return self.filename==other.filename def __hash__(self): return self.filename.__hash__() def __repr__(self): return self.filename def only_dirs_path(path): return ''.join([dirx + '\\' for dirx in path.split('\\')[:-1]]) def file_size_appropriate(path): size = os.path.getsize(path) KBs = size / 1024 if KBs &lt;= 1024: # 1 MB return str(KBs) + ' KB' else: MBs = KBs / 1024 return str(MBs) + ' MB' def sync(): android_dir = android_dirs[0] + 'music' to_upload_files = files_to_be_uploaded(itunes_dir, android_dir) num_files = len(to_upload_files) if num_files == 0: print 'Your Android is already synced to your iTunes' return if num_files!=1: print 'Syncing', len(to_upload_files), 'files' else: print 'Syncing', 1, 'file' for filedata in to_upload_files: upload_path = android_dir + filedata.path.replace(itunes_dir, '') print filedata, file_size_appropriate(filedata.path) upload_dir = only_dirs_path(upload_path) if not os.path.exists(upload_dir): os.mkdir(upload_dir) shutil.copy2(filedata.path, upload_path) print 'Done. Your Android is Synced to your iTunes' user_dir = os.getenv('USERPROFILE') itunes_dir = user_dir + '\\Music\\iTunes\\iTunes Media' android_dirs = get_android_dir() if len(android_dirs) &gt; 0: try: sync() except WindowsError as e: ex = str(e)[:9] if ex == '[Error 3]': print e print 'iTunes Still Downloading Error, aborting. Wait your downloads in iTunes to finish before syncing' else: raise e #print to_upload_files else: print "There's no Android device connected. Exiting" </code></pre>
[]
[ { "body": "<pre><code>\"\"\"\n Sync your iTunes files with your Android\n \"\"\"\n import os, string, re, shutil\n from ctypes import windll\n\n def get_drives():\n drives = []\n bitmask = windll.kernel32.GetLogicalDrives()\n</code></pre>\n\n<p>I'd call this drives_bitmask just to be a bit clearer</p>\n\n<pre><code> for letter in string.uppercase:\n if bitmask &amp; 1:\n drives.append(letter)\n bitmask &gt;&gt;= 1\n</code></pre>\n\n<p>I think shifting the bitmaks makes it a little less clear what is going on. I'd do</p>\n\n<pre><code>for index, letter in enumerate(string.uppercase):\n if bitmask &amp; (1 &lt;&lt; index):\n drives.append(letter)\n\n\n return drives\n</code></pre>\n\n<p>This function will be somewhat difficult to test because it only ever returns the drives on your current computer. So it'll be hard to test for other computers with different drives. It might be better to pass the drive bitmask into the function.</p>\n\n<pre><code> def get_android_dir():\n android_devices = []\n drives = get_drives()\n for drive in drives:\n</code></pre>\n\n<p>You don't need to store things in local variables. Just do <code>for drive in get_drives():</code></p>\n\n<pre><code> path = drive + ':\\\\' \n try:\n drive_dirs = os.listdir(path) \n for diry in drive_dirs:\n</code></pre>\n\n<p>I'd use directory rather then diry</p>\n\n<pre><code> if re.compile('android_secure', re.IGNORECASE).search(diry) != None:\n</code></pre>\n\n<p>There isn't really any reason to be using a regular expression here. Just use <code>'android_secure' in diry.lower()</code></p>\n\n<pre><code> android_devices.append(path)\n #print path, 'is an Android device'\n #print drive_dirs\n</code></pre>\n\n<p>Don't keep old code around in comments</p>\n\n<pre><code> break \n except WindowsError: pass\n</code></pre>\n\n<p>Simply ignoring errors is almost always a bad idead</p>\n\n<pre><code> return android_devices\n</code></pre>\n\n<p>This will be painful to unit test because to checks the physical drives. </p>\n\n<pre><code> def all_files_from_path_filtered(path):\n</code></pre>\n\n<p>It'd be better if the name suggested the type of filtering</p>\n\n<pre><code> #files = []\n files = set()\n</code></pre>\n\n<p>Don't leave old code in your file</p>\n\n<pre><code> #print os.listdir(itunes_dir)\n for dirpath, dirname, filenames in os.walk(path):\n for filename in filenames: \n if dirpath[-3:]!='tmp': # don't add files that are still been downloader\n</code></pre>\n\n<p>What if the filename is shorter then three characters? Use <code>dirpath.endswith</code> instead. Also, check <code>dirpath</code> outside of this loop.</p>\n\n<pre><code> files.add(Filedata(filename, dirpath))\n else:\n print 'Not syncing', dirpath.split('\\\\')[-1], \"it's still downloading\"\n return files\n\n def files_to_be_uploaded(itunes_dir, android_dir):\n itunes_set = all_files_from_path_filtered(itunes_dir)\n android_set = all_files_from_path_filtered(android_dir)\n\n #print 'iTunes Set', len(itunes_set), itunes_set\n #print 'Android Set', len(android_set), android_set\n\n to_upload_files = list(itunes_set.difference(android_set)) \n</code></pre>\n\n<p>Why convert back to a list?</p>\n\n<pre><code> return to_upload_files\n\n class Filedata(object):\n def __init__(self, filename, path):\n self.filename = filename\n self.path = path + '\\\\' + filename\n</code></pre>\n\n<p>Use os.path.join to combine paths</p>\n\n<pre><code> def __eq__(self, other): \n return self.filename==other.filename \n def __hash__(self): \n return self.filename.__hash__()\n def __repr__(self):\n return self.filename \n</code></pre>\n\n<p>It might be an idea to move some of the logic into this class</p>\n\n<pre><code> def only_dirs_path(path):\n return ''.join([dirx + '\\\\' for dirx in path.split('\\\\')[:-1]])\n</code></pre>\n\n<p>os.path has a number of useful function including dirname which will do this for you</p>\n\n<pre><code> def file_size_appropriate(path):\n</code></pre>\n\n<p>Its not really appropriate as much as human readable</p>\n\n<pre><code> size = os.path.getsize(path)\n KBs = size / 1024\n if KBs &lt;= 1024: # 1 MB\n return str(KBs) + ' KB'\n else:\n MBs = KBs / 1024\n return str(MBs) + ' MB' \n\n def sync():\n android_dir = android_dirs[0] + 'music'\n to_upload_files = files_to_be_uploaded(itunes_dir, android_dir)\n\n num_files = len(to_upload_files)\n if num_files == 0:\n print 'Your Android is already synced to your iTunes'\n return\n</code></pre>\n\n<p>I'd use an else block rather then a return</p>\n\n<pre><code> if num_files!=1: \n print 'Syncing', len(to_upload_files), 'files'\n else:\n print 'Syncing', 1, 'file'\n for filedata in to_upload_files:\n upload_path = android_dir + filedata.path.replace(itunes_dir, '') \n</code></pre>\n\n<p>Use os.path.relpath</p>\n\n<pre><code> print filedata, file_size_appropriate(filedata.path)\n\n upload_dir = only_dirs_path(upload_path) \n if not os.path.exists(upload_dir):\n os.mkdir(upload_dir)\n shutil.copy2(filedata.path, upload_path)\n\n print 'Done. Your Android is Synced to your iTunes'\n\n user_dir = os.getenv('USERPROFILE')\n itunes_dir = user_dir + '\\\\Music\\\\iTunes\\\\iTunes Media'\n android_dirs = get_android_dir()\n</code></pre>\n\n<p>This kinda thing should really be in a main function</p>\n\n<pre><code> if len(android_dirs) &gt; 0:\n try:\n sync()\n except WindowsError as e:\n ex = str(e)[:9]\n if ex == '[Error 3]':\n</code></pre>\n\n<p>Use <code>if str(e).beginswith('[Error 3]'):</code></p>\n\n<pre><code> print e\n print 'iTunes Still Downloading Error, aborting. Wait your downloads in iTunes to finish before syncing' \n else:\n raise e\n #print to_upload_files \n else:\n print \"There's no Android device connected. Exiting\"\n</code></pre>\n\n<p>Unit testing programs to read the filesystem is one of the harder things to unit test. If you are just starting unit testing, I don't recommend starting here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T19:41:22.403", "Id": "17229", "Score": "0", "body": "You're suggesting this? upload_path = os.path.relpath(filedata.path, android_dir), if it is it throws ValueError: path is on drive C:, start on drive G:" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T20:36:06.907", "Id": "17230", "Score": "0", "body": "@Vandell, no, `os.path.relpath(filedata.path, itunes_dir)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T00:02:54.380", "Id": "17234", "Score": "0", "body": "Now I get it, I actually had to do more, os.path.join(android_dir, os.path.relpath(filedata.path, itunes_dir))" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T19:12:09.683", "Id": "10801", "ParentId": "10796", "Score": "2" } } ]
{ "AcceptedAnswerId": "10801", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T16:58:08.770", "Id": "10796", "Score": "2", "Tags": [ "python", "unit-testing" ], "Title": "Do I need to create more functions? And also, is this code difficult to unit test?" }
10796
<p>After recently reading up on and watching videos on OO PHP programming I have decided to convert my existing site into OO to gain some experience.</p> <p>I have successfully (well, I think) converted a page into OOP and would like to know whether this is considered the proper way to implement OOP and whether this should be the way I complete the webpage or whether I need to rethink my design.</p> <p>Here are the included files, a validate class file, and the "view" I guess, editedbooking.php. (In editedbooking.php a config file is included, which includes validate.php and database.php (my database connection file))</p> <p>My class file - validatetest.php</p> <pre><code>&lt;?php class Validations { public $date2; public $typeofnumber; public $phonenumber; private function validatemobile($mobnumber) { $pattern = '/^[\(]?(\d{0,4})[\)]?[\s]?[\-]?(\d{3})[\s]?[\-]?(\d{3})$/'; if (preg_match($pattern, $mobnumber, $matches)) { // we have a match, dump sub-patterns to $matches $number = $matches[0]; // original number $a_code = $matches[1]; // 4-digit area code $exchange = $matches[2]; // 3-digit exchange $ending = $matches[3]; // 3-digit number // $extension = $matches[4]; // extension $this-&gt;phonenumber = "(".$a_code.") ".$exchange." ".$ending; } else { throw new Exception("Please Enter a valid Telephone Number"); } } private function validatehome($number){ $pattern = '/^[\(]?(\d{0,2})[\)]?[\s]?[\-]?(\d{4})[\s]?[\-]?(\d{4})$/'; if (preg_match($pattern, $number, $matches)) { // we have a match, dump sub-patterns to $matches $number = $matches[0]; // original number $a_code = $matches[1]; // 2-digit area code $exchange = $matches[2]; // 4-digit exchange $ending = $matches[3]; // 4-digit number // $extension = $matches[4]; // extension $this-&gt;phonenumber = "(".$a_code.") ".$exchange." ".$ending; } else { throw new Exception("Please Enter a valid Telephone Number"); } } //method to check argument is set public function is_set($arg1) { if (!isset($arg1) &amp;&amp; ($arg1 == '')) { throw new Exception("Value {$arg1} is not set"); } } //determine whether number is mobile or home phone public function determine_number($number) { if ($number === "mobile") { $this-&gt;typeofnumber = "mobile"; } elseif ($number === "home") { $this-&gt;typeofnumber = "home"; } } //the method below validates a numbers length, length is set to 10 chars by default. public function validatelength($arg1) { if ($this-&gt;typeofnumber == "mobile") { if (strlen($arg1) != 10) { throw new Exception("Your Mobile number is not the right length!"); } } else if ($this-&gt;typeofnumber == "home"){ if ((strlen($arg1) &lt;= 7) || (strlen($arg1) &gt;= 11)) { throw new Exception("The input \"$arg1\" is not the required length!"); } } else { //error handling in here later } } //this method has to be passed after method "determinenumber" public function validatenumber($phonenumber) { if ($this-&gt;typeofnumber == "mobile") { $this-&gt;validatemobile($phonenumber); } elseif ($this-&gt;typeofnumber == "home") { $this-&gt;validatehome($phonenumber); } else { throw new Exception("Please input a number type!"); } } public function get_number() { return $this-&gt;phonenumber; } public function date_validate($date) { $fixingdate = $_REQUEST['date5']; $fixingdate = explode("-", $fixingdate); $year = $fixingdate[0]; switch ($fixingdate[1]) { case 1: $month = "Janurary"; break; case 2: $month = "Febuary"; break; case 3: $month = "March"; break; case 4: $month = "April"; break; case 5: $month = "May"; break; case 6: $month = "June"; break; case 7: $month = "July"; break; case 8: $month = "August"; break; case 9: $month = "September"; break; case 10: $month = "October"; break; case 11: $month = "November"; break; case 12: $month = "December"; break; } // end of switch $month2 = $fixingdate[1]; //for different query (bloew) $day = $fixingdate[2]; $subdate = "The ".$day."th of ".$month." ".$year; $this-&gt;date2 = "$year-$month2-$day"; return $subdate; } public function servicemethod($service) { switch ($service) { case 1: $service = "Hair Extension - Consultation"; break; case 2: $service = "Hair Extension - Application"; break; case 3: $service = "Spray Tan"; break; case 4: $service = "Eyelash Extensions"; break; } return $service; } } $validate = new Validations(); </code></pre> <p>"view" page - editedbooking.php</p> <pre><code>&lt;?php require_once('calendar/classes/tc_calendar.php'); include ('includes/headerBK.html'); require_once('classes/config.php'); if ($session-&gt;is_logged_in() == TRUE) { //main condition - if session isnt set then user isnt logged in. $name = ucfirst($_SESSION['first_name']); $userid = $_SESSION['user_id']; $vars = $_SESSION; //variables passed from login page to sesh var. if(isset($_POST['submitted'])) { try { //validate the required fields are set $validate-&gt;is_set($_POST['phone']); $validate-&gt;is_set($_POST['numtype']); $validate-&gt;is_set($_POST['date5']); $validate-&gt;is_set($_POST['optone']); $validate-&gt;is_set($_POST['opttwo']); //determine the type of number being inputted i.e home or mobile $validate-&gt;determine_number($_POST['numtype']); //check the length of the entered phone number and date (just for an extra precaution) $validate-&gt;determine_number($_POST['numtype']); $validate-&gt;validatelength($_POST['phone']); //validate number (has to run after "$validate-&gt;determinenumber")! $validate-&gt;validatenumber($_POST['phone']); //return the inputted items to a variables. $phone = $validate-&gt;get_number(); $subdate = $validate-&gt;date_validate($_POST['date5']); $service = $validate-&gt;servicemethod($_POST['optone']); $location = ($_POST['opttwo']); } catch(Exception $e) { echo output_errormsg($e-&gt;getMessage() . "\n"); } if ($location &amp;&amp; $phone &amp;&amp; $subdate) { $database-&gt;autocommit(FALSE); //turn off mysqli auto commit $query1 = $database-&gt;use_db("INSERT INTO booking_info (location, ph_number) VALUES ('$location', '$phone')"); if ($query1 == TRUE) { $query2 = $database-&gt;use_db("INSERT INTO bookings (user_id, date, pending) VALUES ($userid, '$validate-&gt;date2', 'yes')"); if ($query2 == TRUE) { $finishpage = TRUE; $database-&gt;commit(); } else { $database-&gt;rollback(); } } else { //$database-&gt;rollback(); } // first query - adding booking_info } else { echo output_errormsg("There was a problem with your request"); }//END OF LOCATION PHONE AND DATE CONDITIONAL } //END OF MAIN SUBMITTED CONDITIONAL if (isset($finishpage)) { //if this is set then user has succesffully submitted the form already echo "Thank you $name, $subdate has been submitted for approval!"; include('includes/footer.html'); die(); } } else { //redirect as not logged in - MAIN SESSION CONDITIONAL echo 'You are not logged in. Please click &lt;a href="login.php"&gt;here&lt;/a&gt;'; include('includes/footer.html'); die(); } //end of session conditional*/ ?&gt; &lt;script language="javascript"&gt; &lt;!-- function setOptions(chosen) { var selbox = document.myform.opttwo; selbox.options.length = 0; if (chosen == " ") { selbox.options[selbox.options.length] = new Option('Please select one of the options above first',' '); } if (chosen == "1") { selbox.options[selbox.options.length] = new Option('On-Site','onsite'); selbox.options[selbox.options.length] = new Option('Mobile','mobile'); } if (chosen == "2") { selbox.options[selbox.options.length] = new Option('On-Site','onsite'); selbox.options[selbox.options.length] = new Option('Mobile','mobile'); } if (chosen == "3") { selbox.options[selbox.options.length] = new Option('On-Site','onsite'); selbox.options[selbox.options.length] = new Option('Mobile','mobile'); } if (chosen == "4") { selbox.options[selbox.options.length] = new Option('On-Site','onsite'); selbox.options[selbox.options.length] = new Option('Mobile','mobile'); } } --&gt; &lt;/script&gt; &lt;img src="images/topwrapper.png" id="righttopimage"/&gt; &lt;h1&gt;Book Online&lt;/h1&gt; &lt;div id="contactform"&gt; &lt;form name="myform" action="editedbooking.php" method="post"&gt; &lt;fieldset&gt;&lt;legend&gt;Enter your information in the form below : &lt;/legend&gt; &lt;P&gt;&lt;B&gt;Contact Number:&lt;/b&gt;&lt;input type="text" name="phone" size="40" maxlength="20" /&gt;&lt;/p&gt; &lt;p&gt;&lt;b&gt;Home Phone&lt;input type="radio" name="numtype" value="home" /&gt; Mobile&lt;input type="radio" name="numtype" value="mobile" /&gt;&lt;/b&gt;&lt;/p&gt; &lt;/p&gt; &lt;table border="0"&gt;&lt;tr&gt;&lt;td&gt;&lt;p&gt;&lt;b&gt;Preferred Time : &lt;/td&gt;&lt;td&gt;&lt;?php $myCalendar = new tc_calendar("date5", true, false); $myCalendar-&gt;setIcon("calendar/images/iconCalendar.gif"); //$myCalendar-&gt;setDate(date('d'), date('m'), date('Y')); $myCalendar-&gt;setPath("calendar/"); $myCalendar-&gt;setYearInterval(2000, 2015); $myCalendar-&gt;dateAllow('2008-05-13', '2015-03-01'); $myCalendar-&gt;setDateFormat('j F Y'); //$myCalendar-&gt;setHeight(350); //$myCalendar-&gt;autoSubmit(true, "form1"); $myCalendar-&gt;setAlignment('left', 'bottom'); $myCalendar-&gt;setSpecificDate(array("2011-04-01", "2011-04-04", "2011-12-25"), 0, 'year'); $myCalendar-&gt;setSpecificDate(array("2011-04-10", "2011-04-14"), 0, 'month'); $myCalendar-&gt;setSpecificDate(array("2011-06-01"), 0, ''); $myCalendar-&gt;writeScript(); ?&gt; &lt;/b&gt;&lt;/p&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; &lt;p&gt;&lt;b&gt;Please select the service you require : &lt;/b&gt;&lt;/p&gt; &lt;select name="optone" size="1" onchange="setOptions(document.myform.optone.options[document.myform.optone.selectedIndex].v alue);"&gt; &lt;option value=" " selected="selected"&gt;&lt;/option&gt; &lt;option value="1"&gt;Hair Extension - Consultation&lt;/option&gt; &lt;option value="2"&gt;Hair Extensions - Application&lt;/option&gt; &lt;option value="3"&gt;Spray Tan&lt;/option&gt; &lt;option value="4"&gt;Eyelash Extensions&lt;/option&gt; &lt;/select&gt;&lt;br /&gt; &lt;br /&gt; &lt;select name="opttwo" size="1"&gt; &lt;option value=" " selected="selected"&gt;Please select one of the options above first&lt;/option&gt; &lt;/select&gt; &lt;input type="hidden" name="submitted" value="1"&gt; &lt;/fieldset&gt; &lt;div align="center"&gt;&lt;input type="submit" name="submit" value="Submit My Information!" \&gt;&lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php include ('includes/footer.html'); ?&gt; </code></pre>
[]
[ { "body": "<p><strong>Design and style</strong></p>\n\n<p>As a general remark - choose your naming convention and use it consistently.</p>\n\n<p><em>Validation</em></p>\n\n<p>Public properties are always a bad thing</p>\n\n<pre><code>public $date2;\npublic $typeofnumber;\npublic $phonenumber;\n</code></pre>\n\n<p>I see just three public methods in validator (see below) All others are internal details of the validator implementation. These methods should return <code>false</code> at unsuccessfull validation.</p>\n\n<pre><code>public function getValidNumber($number, $typeOfNumber='mobile')\npublic function getValidDate($date)\npublic function getValidService($service)\n</code></pre>\n\n<p><em>View page</em></p>\n\n<p>Defenetely, long way to \"view\" if you meant MVC. As for now, it has either too much PHP, or too much HTML. Depends on what it is: rather view, or may be template. It has \"model\"-related parts as well.</p>\n\n<p>It is too big to review it as it is (as volonteer)....</p>\n\n<p><strong>General notes</strong></p>\n\n<p><em>Security</em></p>\n\n<p>You trust too much to globals like <code>$_SESSION</code> and <code>$_POST</code>. I believe you should add more verifications of their content.</p>\n\n<p><em>Programming</em></p>\n\n<p>You use exceptions as message carriers. It is not common use. Exception is, well, exception from normal program flow, so it may take a lot of resources, for example, and you will have very expensive message transfer system.</p>\n\n<p>Quite contrary, <code>try catch</code> is always a good thing around DB operations, but you don't do it.</p>\n\n<p><code>swith</code> in <code>date_validate</code> - don't you think it may be converted into array with boundary validation?</p>\n\n<p><code>public function is_set($arg1)</code> - seems to be too close to <code>empty()</code>. What does this statement mean:</p>\n\n<pre><code>if (!isset($arg1) &amp;&amp; ($arg1 == ''))\n</code></pre>\n\n<p>I believe it is a bug.</p>\n\n<p><code>validatehome</code> and <code>validatemobile</code> differ in regexp only. Consider code reuse.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T05:59:45.580", "Id": "10812", "ParentId": "10800", "Score": "3" } }, { "body": "<p>Firstly, let me say, Michael made very good comments which I agree with.</p>\n\n<h2>Minor Comments</h2>\n\n<ol>\n<li><p>The first thing I want to see in a class are the important parts. private methods do not help me interact with the class, so I always write them at the end of my class definitions.</p></li>\n<li><p>Relying on user input can be dangerous:</p>\n\n<p>public function date_validate($date) {</p>\n\n<pre><code>$fixingdate = $_REQUEST['date5'];\n$fixingdate = explode(\"-\", $fixingdate);\n$year = $fixingdate[0];\nswitch ($fixingdate[1]) {\n</code></pre>\n\n<p>Someone could modify the request and you wouldn't get date5 as you expected.</p></li>\n<li><p>Creating a global object after your class definition is a bad idea.</p>\n\n<p><code>$validate = new Validations();</code></p>\n\n<p>Create the object where you are going to use it (i.e editedbooking.php)</p></li>\n</ol>\n\n<h2>Major Comment - Is this OO?</h2>\n\n<p>Unfortunately this isn't really OO. It is a good first attempt.</p>\n\n<p><strong>Why do I say that?</strong></p>\n\n<p>Can you think of what Validations represents in the real world? The closest thing I can think of is that it is a procedure for validating data. Defining an object by its procedure is a way of still thinking in procedural terms.</p>\n\n<p>You can see this in the <code>servicemethod</code> function. Your object is used as a procedure rather than a method. You pass in a value and return another one without referring to the object at all. The same happens with <code>date_validate</code>.</p>\n\n<p><strong>What real world object could have been used?</strong></p>\n\n<p>I understand you wanting to do validation, that is a good thing (though a little complicated). A booking or appointment type object might have been easier than a validation class.</p>\n\n<p><strong>How to make OO validations</strong></p>\n\n<p>I'm going to leave the implementation blank, but show you the kind of class structure I would use.</p>\n\n<p>I would normally use an interface, but I'm going to skip that considering you are just starting OO. First the base class which is abstract:</p>\n\n<pre><code>abstract class Validator\n{\n /** Basic validator.\n * @param required \\bool Whether the value must be set.\n */\n public function __construct($required = true) {};\n\n /** Return whether the data passed in is valid according to the validator.\n * @param data \\mixed The data to validate.\n */\n abstract public function isValid($data);\n}\n</code></pre>\n\n<p>Notice how a common feature is recorded in the base class (whether the value is required). This feature is shared with all derived classes.</p>\n\n<p>Now, a derived class which can do specific validation:</p>\n\n<pre><code>class PhoneValidator extends Validator\n{\n /** Return whether the data passed in is valid according to the validator.\n * @param data \\mixed The data to validate.\n */\n public function isValid($data) {}; \n}\n</code></pre>\n\n<p>By creating a number of different validation objects you could loop through all of your validations and ensure that they are all valid.</p>\n\n<pre><code>// Phone not required, Service implicity required, Date required.\n$validations = array(new PhoneValidator(false),\n new ServiceValidator(),\n new DateValidator(true));\n\nforeach ($validations as $validation)\n{\n if (!$validation-&gt;isValid())\n {\n // Code for validation failure.\n }\n}\n</code></pre>\n\n<p>The real difference is that these classes now represent real objects rather than straight method calls.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T12:16:30.423", "Id": "17404", "Score": "0", "body": "Thank for very much for the detailed answer! Sorry for the giving the answer so late, having a few PC issues lately.\nI am going to try and implement your idea, with a booking class as suggested, and then hopefully move onto the validation class. Thank you again!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T11:58:14.930", "Id": "10819", "ParentId": "10800", "Score": "2" } } ]
{ "AcceptedAnswerId": "10819", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T19:09:00.753", "Id": "10800", "Score": "2", "Tags": [ "php", "object-oriented", "validation" ], "Title": "Validating booking information" }
10800
<p>Is this best practice way to send messages to the user?</p> <p>Update: This has been changed to a simple function call.</p> <pre><code>/** *Message - Sends message to the .innerHTML of an element */ var Message = ( function () { var messages = { name: 'Please enter a valid name', email: 'Please enter a valid email', email_s: 'Please enter a valid email.', pass: 'Please enter password, 6-40 characters', url: 'Please enter a valid url', title: 'Please enter a valid title', tweet: 'Please enter a valid tweet', empty: 'Please complete all fields', same: 'Please make emails equal', taken: 'Sorry, that email is taken', validate: 'Please contact &lt;a class="d" href="mailto:foo@foo.com"&gt;support&lt;/a&gt; to reset your password', }; var MessageInternal = function (element) { this.element = element; }; MessageInternal.prototype.display = function( type ) { this.element.innerHTML = messages[ type ]; }; return MessageInternal; } () ); </code></pre>
[]
[ { "body": "<p>I don't really understand what you are asking here, but I'll give some general pointers:</p>\n\n<ul>\n<li><p>I find that you have two different variables called <code>Message</code> very confusing. </p></li>\n<li><p>It's not really a good idea to add proprietary properties to DOM elements. You should consider using the HTML5 <code>dataset</code> API instead.</p></li>\n<li><p>It seems wrong to hard code the fade effect.</p></li>\n<li><p>IMHO this seems like a lot of code and unnecessarily over-engineered for displaying a simple message. It reminds me a lot how of the <a href=\"http://twitter.github.com/bootstrap/javascript.html#alerts\" rel=\"nofollow\">Twitter bootstrap library</a> does things.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-17T21:44:44.917", "Id": "20441", "Score": "0", "body": "- decided to go with a simple function instead of module pattern." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-17T21:45:14.150", "Id": "20442", "Score": "0", "body": "- how is HTML 5 related here?...are you referring to the HTML5 data- attribute?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-18T15:02:14.870", "Id": "20505", "Score": "0", "body": "this is what you mean by dataset API methinks" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T08:48:39.163", "Id": "10850", "ParentId": "10803", "Score": "1" } } ]
{ "AcceptedAnswerId": "10850", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T22:52:18.023", "Id": "10803", "Score": "2", "Tags": [ "javascript" ], "Title": "Message Object - Best Practice? | Consider data attribute for pulling text in" }
10803
<p>I'm just getting my feet on the ground with Python (maybe 3 days now). The only issue with teaching my self is that I have no one to critique my work.</p> <p>Correct me if I'm wrong but I think my algorithm/method for solving this problem is quite promising; but, the code not so much.</p> <p>The program basically strips a web-page and puts it in to the designated directory. My favorite part is the method for deciding the image's extensions :)</p> <pre><code>import os, re, urllib def Read(url): uopen = urllib.urlopen(url) uread = '' for line in uopen: uread += line return uread def Find(what, where): found = re.findall(what, where) match = [] for i in found: i = i[9:-1] match.append(i) return match def Retrieve(urls, loc): loc = os.path.realpath(loc) os.system('mkdir ' + loc +'/picretrieved') loc += '/picretrieved' x = 0 exts = ['.jpeg', '.jpg', '.gif', '.png'] for url in urls: x += 1 for i in exts: ext = re.search(i, url) if ext != None: ext = ext.group() urllib.urlretrieve(url, loc + '/' + str(x) + ext) else: continue print 'Placed', str(x), 'pictures in:', loc def main(): url = raw_input('URL to PicRetrieve (google.com): ') url = 'http://' + url loc = raw_input('Location for PicRetrieve older ("." for here): ') html = Read(url) urls = Find('img src=".*?"', html) print urls Retrieve(urls, loc) if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<pre><code>import os, re, urllib\n\ndef Read(url):\n</code></pre>\n\n<p>Python convention is to name function lowercase_with_underscores</p>\n\n<pre><code> uopen = urllib.urlopen(url)\n</code></pre>\n\n<p>I recommend against abbreviations</p>\n\n<pre><code> uread = ''\n for line in uopen: uread += line\n return uread\n</code></pre>\n\n<p>Use <code>uopen.read()</code> it'll read the whole file</p>\n\n<pre><code>def Find(what, where):\n found = re.findall(what, where)\n match = []\n for i in found:\n</code></pre>\n\n<p>avoid single letter variable names</p>\n\n<pre><code> i = i[9:-1]\n match.append(i)\n return match \n</code></pre>\n\n<p>Combine short lines of code</p>\n\n<pre><code> for i in re.findall(what, where):\n match.append(i[9:-1])\n</code></pre>\n\n<p>I think its cleaner this way. Also use capturing groups rather then indexes.</p>\n\n<pre><code>def Retrieve(urls, loc):\n loc = os.path.realpath(loc)\n os.system('mkdir ' + loc +'/picretrieved')\n</code></pre>\n\n<p>Use <code>os.mkdir</code> rather than using system</p>\n\n<pre><code> loc += '/picretrieved'\n</code></pre>\n\n<p>Use os.path.join to construct paths</p>\n\n<pre><code> x = 0\n exts = ['.jpeg', '.jpg', '.gif', '.png']\n for url in urls:\n x += 1\n</code></pre>\n\n<p>use <code>for x, url in enumerate(urls):</code></p>\n\n<pre><code> for i in exts:\n ext = re.search(i, url)\n</code></pre>\n\n<p>Don't use regular expressions to search for simple strings. In this case I think you really want to use <code>url.endswith(i)</code>. Also, stop using <code>i</code> everywhere.</p>\n\n<pre><code> if ext != None:\n ext = ext.group()\n urllib.urlretrieve(url, loc + '/' + str(x) + ext)\n else:\n continue\n</code></pre>\n\n<p>This continue does nothing</p>\n\n<pre><code> print 'Placed', str(x), 'pictures in:', loc\n</code></pre>\n\n<p>You don't need to use str when you are using print. It does it automatically.</p>\n\n<pre><code>def main():\n url = raw_input('URL to PicRetrieve (google.com): ')\n url = 'http://' + url\n loc = raw_input('Location for PicRetrieve older (\".\" for here): ')\n html = Read(url)\n urls = Find('img src=\".*?\"', html)\n</code></pre>\n\n<p>Generally, using an html parser is preferred to using a regex on html. In this simple case you are ok.</p>\n\n<pre><code> print urls\n Retrieve(urls, loc)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T00:29:36.127", "Id": "10807", "ParentId": "10804", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T22:36:19.000", "Id": "10804", "Score": "4", "Tags": [ "python", "beginner", "web-scraping" ], "Title": "Saving images from a web page" }
10804
<p>How could I make this path-finding code dynamic? This is to allow an agent to search the path on its own (from one corner of the grid to another) while hiding it until moved to the grid.</p> <p>I am new to C++ and tried to write this program, but it appears to be static. I need to make it dynamic, or I could just have the agent do the path-searching on its own (not by assigning the path). So far, I've made 5 different paths because the agent can choose as many as needed. However, the path length should be 6 and can move only up or to the right.</p> <pre><code> #include &lt;iostream&gt; #include &lt;ctime&gt; #include &lt;cstdlib&gt; #include &lt;iomanip&gt; #include &lt;math.h&gt; #include &lt;ctime&gt; #include &lt;fstream&gt; #include &lt;vector&gt; #include &lt;iterator&gt; #include &lt;algorithm&gt; using namespace std; using namespace std; using namespace System; using namespace System::IO; /*int Grid[ 4 ][ 4 ] = { { 29, 8, 11, 9 }, { 22, 24, 3, 15 }, { 24, 26, 5, 6 }, { 33, 10, 32, 21} }; int Grid[ 4 ][ 4 ] = { { 0, 0, -5, 0.0 }, { -1, 0, 2, 2 }, { 2, 0, 0, 0 }, { 0, 2, 0, -1} }; +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ int g[16] = {33,10,32,21,24,26,5,6,22,24,3,15,29,8,11,9}; int r[16] = {0,2,0,-1,2,0,0,0,-1,0,2,2,0,0,-5,0}; #define SPACE "[ ]" bool Finished( false ); int m[4]; //int E = 6; int E, E1, E2, E3; void printmatrix(char arg[], int length) { for (int j = length; j &gt;= 0; j=-4) { cout &lt;&lt;"\n" &lt;&lt; arg[j] &lt;&lt; "\n "; } //} } void FindNextPos() { std::cout&lt;&lt;"\n"&lt;&lt;"Search Path 1"&lt;&lt;"\n"; for (int c= 1; c &lt; 5; c++) { if(r[c] != r[3]) { m[c] = 1; E = E + r[c] - 1; //std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E &lt;&lt;")"&lt;&lt;m[c]&lt;&lt; std::endl; //system("pause"); } else { Finished = true; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E &lt;&lt;")"&lt;&lt;m[c]&lt;&lt; std::endl; } } for (int c= 7; c &lt;= 16; c= c+ 4) { if(r[c] != r[16]){ m[c] = 2; E = E + r[c] - 1; //std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E &lt;&lt;")"&lt;&lt; std::endl; //system("pause"); } else { //m[c] = 2; Finished = true; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E &lt;&lt;")"&lt;&lt; std::endl; } } } //int E1 = 6; void nextpos1(){ std::cout&lt;&lt;"\n"&lt;&lt;"Search Path 2"&lt;&lt;"\n"; for (int c= 0; c &lt; 3; c++) { if(r[c] != r[3]) { m[c] = 3; E1 = E1 + r[c] - 1; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E1 &lt;&lt;")"&lt;&lt; std::endl; //system("pause"); } else { Finished = true; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E1 &lt;&lt;")"&lt;&lt; std::endl; } } for (int c= 6; c &lt; 15; c= c + 4) { if(r[c] != r[16]){ m[c] = 4; E1 = E1 + r[c] - 1; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E1 &lt;&lt;")"&lt;&lt; std::endl; //system("pause"); } else { m[c] = 4; Finished = true; std::cout&lt;&lt;"(ID,C,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E1 + r[c] - 1 &lt;&lt;")"&lt;&lt; std::endl; } } for (int c= 15; c &lt; 16; ++c) { if(r[c] != 0){ m[c] = 5; E1 = E1 + r[c] - 1; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E1 &lt;&lt;")"&lt;&lt; std::endl; //system("pause"); } else { m[c] = 5; Finished = true; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E1 &lt;&lt;")"&lt;&lt; std::endl; std::cout &lt;&lt; "\n"&lt;&lt;"finish--&gt;" &lt;&lt; r[c] &lt;&lt; "\t" &lt;&lt;"E1--&gt;"&lt;&lt; E1 &lt;&lt;"\n" ; } } } //int E2 = 6; void nextpos2(){ std::cout&lt;&lt;"\n"&lt;&lt;"Search Path 3"&lt;&lt;"\n"; for (int c= 0; c &lt; 2; c++) { if(r[c] != r[3]) { m[c] = 6; E2 = E2 + r[c] - 1; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E2 &lt;&lt;")"&lt;&lt; std::endl; //system("pause"); } else { Finished = true; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E2 &lt;&lt;")"&lt;&lt; std::endl; } } for (int c= 1; c &lt; 12; c= c + 4) { if(r[c] != r[14]){ m[c] = 7; E2 = E2 + r[c] - 1; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E2 &lt;&lt;")"&lt;&lt; std::endl; //system("pause"); } else { //m[c] = 7; Finished = true; std::cout&lt;&lt;"(C,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E2 + r[c] - 1 &lt;&lt;")"&lt;&lt; std::endl; } } for (int c= 13; c &lt; 16; ++c) { m[c] = 8; if(r[c] != r[16]){ E2 = E2 + r[c] - 1; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E2 &lt;&lt;")"&lt;&lt; std::endl; //system("pause"); } else { // m[c] = 8; Finished = true; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E2 &lt;&lt;")"&lt;&lt; std::endl; std::cout &lt;&lt; "\n"&lt;&lt;"finish--&gt;" &lt;&lt; r[c] &lt;&lt; "\t" &lt;&lt;"E--&gt;"&lt;&lt; E1 &lt;&lt;"\n" ; } } } //int E3 = 6; void nextpos3(){ std::cout&lt;&lt;"\n"&lt;&lt;"Search Path 4"&lt;&lt;"\n"; for (int c= 0; c &lt;= 12; c= c+ 4) //for (int c= 4; c &lt;= 12; c= c+ 4) { if(r[c] != r[12]) { m[c] = 11; E3 = E3 + r[c] - 1; std::cout&lt;&lt;"\n"; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E3 &lt;&lt;")"&lt;&lt; std::endl; //system("pause"); } else { m[c] = 11; Finished = true; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E3 + r[c] - 1 &lt;&lt;")"&lt;&lt; std::endl; } } E3 = E3 -1; for (int c= 13; c &lt; 16; c++) { if(r[c] != r[15]){ m[c] = 12; E3 = E3 + r[c] - 1; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E3 &lt;&lt;")"&lt;&lt; std::endl; //system("pause"); } else { m[c] = 12; Finished = true; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E3 + r[c] - 1 &lt;&lt;")"&lt;&lt; std::endl; } } } void nextpos4(){ int E4 = 6; std::cout&lt;&lt;"\n"&lt;&lt;"Search Path 5"&lt;&lt;"\n"; for (int c= 4; c &lt;= 8; c= c+ 4) //for (int c= 4; c &lt;= 12; c= c+ 4) { if(r[c] != r[8]) { cout&lt;&lt;E4; m[c] = 13; E4 = E4 + r[c] - 1; std::cout&lt;&lt;"\n"; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E4 &lt;&lt;")"&lt;&lt; std::endl; //system("pause"); } else { m[c] = 13; Finished = true; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E4 + r[c] - 1 &lt;&lt;")"&lt;&lt; std::endl; } } E4 = E4 -1; for (int c= 9; c &lt; 12; c++) { if(r[c] != r[11]){ m[c] = 14; E4 = E4 + r[c] - 1; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E4 &lt;&lt;")"&lt;&lt; std::endl; //system("pause"); } else { m[c] = 14; Finished = true; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E3 + r[c] - 1 &lt;&lt;")"&lt;&lt; std::endl; } } for (int c= 11; c &lt; 16; c = c + 4) { if(r[c] != r[15]){ //m[c] = 15; E4 = E4 + r[c] - 1; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E4 &lt;&lt;")"&lt;&lt; std::endl; //system("pause"); } else { m[c] = 15; Finished = true; std::cout&lt;&lt;"(ID,R,E)"&lt;&lt;"--&gt;"&lt;&lt;"("&lt;&lt;g[c]&lt;&lt;","&lt;&lt;r[c]&lt;&lt;","&lt;&lt;E4 + r[c] - 1 &lt;&lt;")"&lt;&lt; std::endl; } } } void PrintRoute( void ) {//std::cout &lt;&lt; "Start Node : " &lt;&lt; g[0]&lt;&lt;"\t" &lt;&lt;"Finish Node : " &lt;&lt; g[15] &lt;&lt;"\n"; std::cout &lt;&lt; "\n"&lt;&lt; "Route 1 : "&lt;&lt;"\n"; for (int c= 1; c &lt; 14; c++) { if( m[c] == 1) std::cout&lt;&lt; "[r]--&gt;"&lt;&lt;"\t"; else if (m[c] == 2) std::cout&lt;&lt; "[u]--&gt;"&lt;&lt;"\t"; else std::cout &lt;&lt;""; } std::cout &lt;&lt; "\n"; } void PrintRoute1( void ) {//std::cout &lt;&lt; "\n"&lt;&lt; "Start Node : " &lt;&lt; g[0]&lt;&lt;"\t" &lt;&lt; "Finish Node : " &lt;&lt; g[15]&lt;&lt;"\n"; std::cout &lt;&lt; "\n"&lt;&lt; "Route 2 : "&lt;&lt;"\n"; for (int c= 1; c &lt; 16; c++) { if( m[c] == 3 ) std::cout&lt;&lt; "[r]--&gt;"&lt;&lt;"\t"; else if (m[c] == 4 ) std::cout&lt;&lt; "[u]--&gt;"&lt;&lt;"\t"; else if (m[c] == 5) std::cout&lt;&lt;"[r]--&gt;"&lt;&lt;"\t"; else std::cout &lt;&lt;""; } std::cout &lt;&lt; "\n"; } void PrintRoute2( void ) {//std::cout &lt;&lt; "\n"&lt;&lt; "Start Node : " &lt;&lt; g[0] &lt;&lt;"\t"&lt;&lt; "Finish Node : " &lt;&lt; g[15]&lt;&lt;"\n"; std::cout &lt;&lt; "\n"&lt;&lt; "Route 3: "&lt;&lt;"\n"; for (int c= 0; c &lt; 15; c++) { if( m[c] == 6 || m[c] == 8 ) std::cout&lt;&lt; "[r]--&gt;"&lt;&lt;"\t"; else if (m[c] == 7 ) std::cout&lt;&lt; "[u]--&gt;"&lt;&lt;"\t"; //else if (m[c] == 8) // std::cout&lt;&lt;"[r]"&lt;&lt;"\t"; else std::cout &lt;&lt;""; } std::cout &lt;&lt; "\n"; } void PrintRoute3( void ) {//std::cout &lt;&lt; "Start Node : " &lt;&lt; g[0] &lt;&lt;"\t"&lt;&lt; "Finish Node : " &lt;&lt; g[15]&lt;&lt;"\n"; std::cout &lt;&lt; "\n"&lt;&lt; "Route 4 : "&lt;&lt;"\n"; for (int c = 0; c &lt;= 15; c++) { if( m[c] == 11) std::cout&lt;&lt; "[u]--&gt;"&lt;&lt;"\t"; else if (m[c] == 12) std::cout&lt;&lt; "[r]--&gt;"&lt;&lt;"\t"; else std::cout &lt;&lt;""; } std::cout &lt;&lt; "\n"; } void PrintRoute4( void ) {//std::cout &lt;&lt; "\n"&lt;&lt; "Start Node : " &lt;&lt; g[0]&lt;&lt;"\t" &lt;&lt; "Finish Node : " &lt;&lt; g[15]&lt;&lt;"\n"; std::cout &lt;&lt; "\n"&lt;&lt; "Route 2 : "&lt;&lt;"\n"; for (int c= 1; c &lt; 16; c++) { if( m[c] == 13 ) std::cout&lt;&lt; "[u]--&gt;"&lt;&lt;"\t"; else if (m[c] == 14 ) std::cout&lt;&lt; "[r]--&gt;"&lt;&lt;"\t"; else if (m[c] == 15) std::cout&lt;&lt;"[u]--&gt;"&lt;&lt;"\t"; else std::cout &lt;&lt;""; } } int main( ) { int E,E1,E2,E3; int a, b; int m[4][4]; ifstream in; char state1[] = {'d','p','S','1','3'}; printmatrix(state1, 4); cout&lt;&lt;"open test file : press"; in.open("C:/Users /test.txt"); if (!in) { cout &lt;&lt; "Cannot open file.\n"; system("pause"); return 0; } for (b = 1; b &lt;= 4; b++) {cout &lt;&lt; "\n"; for (a = 1; a &lt;= 4; a++) { in &gt;&gt; m[a][b]; cout &lt;&lt;"\t" &lt;&lt; "["&lt;&lt;m[a][b] &lt;&lt;"]" ; } cout &lt;&lt; "\n"; // } in.close(); std::cout &lt;&lt; "\n"; int mt[6][6]; cout&lt;&lt;"open training file : press"; ifstream i; i.open("C:/Users/training.txt"); if (!i) { cout &lt;&lt; "Cannot open file.\n"; return 0; } cout &lt;&lt; "\n"; for (b = 1; b &lt;= 6; b++) {cout &lt;&lt; "\n"; for (a = 1; a &lt;= 6; a++) { i &gt;&gt; mt[a][b]; cout &lt;&lt;"\t" &lt;&lt; "["&lt;&lt;mt[a][b] &lt;&lt;"]" ; } cout &lt;&lt; "\n"; } i.close(); std::cout &lt;&lt; "\n"; system("pause"); int F = E = E1 = E2= E3; std::cout&lt;&lt; "Enter Energy E"; //std::cin&gt;&gt;E &gt;&gt; E1 &gt;&gt; E2 &gt;&gt; E3 &gt;&gt;E4; std::cin&gt;&gt;F; std::cout &lt;&lt; "Start Node : " &lt;&lt; g[0] &lt;&lt;"\t"&lt;&lt; "Finish Node : " &lt;&lt; g[15]&lt;&lt;"\n"; while( !Finished ) FindNextPos(); PrintRoute( ); nextpos1(); PrintRoute1(); nextpos2(); PrintRoute2(); nextpos3(); PrintRoute3(); nextpos4(); PrintRoute4(); std::cin.get( ); system("pause"); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T08:28:10.530", "Id": "17237", "Score": "0", "body": "This belongs to stackoverflow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T14:34:27.337", "Id": "17241", "Score": "1", "body": "The code displaying code does not handle tabs. You should remove them before posting. And overall just tidy up your indentation. Currently it is all over the place and it makes it impossable to tell your indent and thus where you are forgetting to use {}" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-09T21:51:12.253", "Id": "46781", "Score": "0", "body": "@fish: The request itself does, yes. On the other hand, the code-styling needs improvement and that aspect does belong here. I have now addressed just that." } ]
[ { "body": "<p><em>I'm going to try to review this in spite of the lack of decent indentation and whitespace (in some places). As such, I won't mention them below. I'd recommended improving on this first, as that will help you improve everything else.</em></p>\n\n<ul>\n<li><p>The <code>#include &lt;...&gt;</code>s could be in alphabetical order for better organization. Before that's done, remove that needless whitespace before <code>#include &lt;iostream&gt;</code>.</p></li>\n<li><p><code>#include &lt;math.h&gt;</code> should be <code>#include &lt;cmath&gt;</code> instead; the former is a C library.</p></li>\n<li><p><code>#define SPACE</code> is unnecessary. It brings up another important point: <a href=\"https://stackoverflow.com/questions/1637332/static-const-vs-define\">always try to use <code>const</code>s instead of <code>#define</code>s</a>.</p></li>\n<li><p><strong><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Do not use <code>using namespace std</code> in global scope</a></strong>. If it must be used, it's best to limit the scope as much as possible (such as just putting in inside a function as needed). I have no idea why it's used twice in a row, though. What's even weirder is that you're still putting the <code>std::</code> in the right places, even with the <code>using</code>s. Just get rid of the <code>using</code>s altogether.</p></li>\n<li><p>I recommend two things for your <code>g[]</code> and <code>r[]</code> in global:</p>\n\n<ol>\n<li><p>Make them both <code>const</code> since they appear to be that way.</p></li>\n<li><p>Make them more C++-like and safer by using <code>std::array</code>s instead:</p>\n\n<pre><code>std::array&lt;int, 16&gt; g = {33,10,32,21,24,26,5,6,22,24,3,15,29,8,11,9};\nstd::array&lt;int, 16&gt; r = {0,2,0,-1,2,0,0,0,-1,0,2,2,0,0,-5,0};\n</code></pre>\n\n<p>Having such arrays will allow you to pass them around <em>safely</em> and will save you the \"size\" parameter since they already know their sizes (accessible via <code>myArray.size()</code>).</p></li>\n</ol></li>\n<li><p>The commented-out code looks very messy and confusing. Are you uncertain about using such code, or does it indicate \"work in progress\" or something? There should <em>at least</em> be comments to describe the intent.</p></li>\n<li><p>You should give your variables more descriptive names. It's not at all clear what they're supposed to do. On the other hand, your function names look okay.</p></li>\n<li><p>Your functions don't need a 'void' parameter. That's only for C programs.</p></li>\n<li><p>The <code>char []</code> in <code>main()</code> implies C and not C++. In the latter, there's a type called <code>std::string</code>. It represents a <code>char []</code>, but is instead a <code>class</code> and uses a better implementation. However, if I understand this array's purpose, it's not meant to be a string per se. If that is the case, then I recommend an <code>enum</code> instead. Otherwise, always use <code>std::string</code> instead of <code>char []</code>.</p></li>\n<li><p>Don't <code>return 0</code> when something causes an unsuccessful termination, otherwise the compiler will <em>think</em> it was successful. In this case, it's failure to open a file. Instead, use <code>return 1</code> or even <code>return EXIT_FAILURE</code> (same return value, but more readable).</p></li>\n<li><p><strong>Do not use <code>system(\"PAUSE\")</code> when trying to pause the console</strong>. Especially do not \"sprinkle\" it around your program. That just reduces readability and strains the system with each pause. Here are two alternatives:</p>\n\n<ol>\n<li><p>If you must pause in between program operations, use <code>std::cin.get()</code> instead. Unlike <code>system(\"PAUSE\")</code>, this is <em>not</em> system-specific and it's not nearly as demanding on the system. Even then, \"sprinkling\" this code does not look good.</p></li>\n<li><p>Set your IDE to pause automatically before program termination. If you're executing this in a command line instead, an explicit pause at the end is not needed.</p></li>\n</ol></li>\n<li><p><strong>Overall, your code needs <em>major refactoring</em> or at least <em>commenting</em> so that it can be understood</strong>. This is not just about the lack of indentation, though. I, as one of your readers, am having trouble understanding the processes. It may just be my lack of experience with its purpose, though. Even then, <em>proper commenting</em> and <em>good, consistent indentation</em> will move mountains.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T03:15:01.600", "Id": "57493", "Score": "0", "body": "Do you *really* sort your *includes* alphabetically? ...[OCD](http://meta.codereview.stackexchange.com/a/972/23788) right? :p +1 just for \"proper commenting and good, consistent indentation will move mountains\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T03:19:18.093", "Id": "57494", "Score": "1", "body": "@retailcoder: Another C++ reviewer has told me about that, and I agree. Also the same one who got me to use `Type const& something` instead of `const Type& something` (but the includes are more notable)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-09T20:01:44.400", "Id": "29567", "ParentId": "10805", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T00:20:22.063", "Id": "10805", "Score": "5", "Tags": [ "c++" ], "Title": "How could I make this path-finding code dynamic?" }
10805
<p><strong>library.php</strong></p> <p>My own HTML tag encoder that will print HTML codes according to the input.</p> <pre><code>&lt;?php function tag($tagname, $content = NULL, array $properties = NULL) { $html = "&lt;$tagname"; if (!($properties === NULL)) foreach ($properties as $name =&gt; $value) { $html .= " $name=\"$value\""; } $html .= ($content === NULL || $content == "") ? " /&gt;" : "&gt;$content&lt;/$tagname&gt;"; return $html; } ?&gt; </code></pre> <p><strong>index.php</strong></p> <p>The test <code>index.php</code> file that will run the HTML encoder from the library.</p> <pre><code>&lt;?php require 'library.php'; echo tag("head", tag("meta","",array("name"=&gt;"title","content"=&gt;"Test Print")) ); echo tag("body", tag("div",tag("p","test print".tag("br")."test print"),array()) ); ?&gt; </code></pre> <p><strong>Output:</strong></p> <pre><code>&lt;head&gt;&lt;meta name="title" content="Test Print" /&gt;&lt;/head&gt;&lt;body&gt;&lt;div&gt;&lt;p&gt;test print&lt;br /&gt;test print&lt;/p&gt;&lt;/div&gt;&lt;/body&gt; </code></pre> <p><strong>Question:</strong></p> <p>Using this library will make my code more readable when adding more PHP code. Instead of this <code>&lt;div&gt;&lt;?php $variable ?&gt;&lt;/div&gt;</code>, I can use this <code>echo tag("div",$variable);</code>, but the latter will definitely be longer compared to just typing HTML code.</p> <p>Should I not create such function and stay with coding HTML?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T19:40:16.077", "Id": "17288", "Score": "0", "body": "I would just use the more readable one and put in a comment the smaller one, then on production versions I will uncomment them and minify the whole thing. And when tracking bugs or updating, I would use the original and after the changes, repeat the uncomment+minifing process" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T09:53:33.123", "Id": "17401", "Score": "0", "body": "I'd say you've written yourself a macro." } ]
[ { "body": "<p>There are several advantages to sticking with HTML and embedded PHP:</p>\n\n<ul>\n<li>You get appropriate syntax highlighting.</li>\n<li>You can take advantage of code-completion.</li>\n<li>The all-PHP method lacks proper indentation of HTML elements in the code and when rendered.</li>\n<li>The file can be viewed (sort of) in a browser.</li>\n<li>A designer can modify the HTML as long as they know how to recognize the embedded PHP tags.</li>\n</ul>\n\n<p>That being said, using the PHP approach you can take care of proper HTML-escaping attribute values (though you didn't) in one place to enforce correct rules.</p>\n\n<p>I built a few helper classes for generating image and article link elements for my current project from <code>Image</code> and <code>ContentItem</code> model objects. These classes have setter methods named for the attributes and pull reasonable values from the underlying model objects all while performing correct HTML-escaping. The majority of the page is HTML plus PHP, but these classes make embedding a link or image very easy:</p>\n\n<pre><code>&lt;div&gt;\n Here is a picture of the car:\n &lt;br/&gt;\n &lt;?= $this-&gt;img($car-&gt;getImage())-&gt;alt($car-&gt;getDescription()) ?&gt;\n&lt;/div&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T03:59:59.680", "Id": "10811", "ParentId": "10809", "Score": "13" } }, { "body": "<p>You are on the right track, but echo is not the right tool for the job IMO.</p>\n\n<p>Thinking about XML generally we can represent the data like this:</p>\n\n<p><code>array('tag', $attributes, $children);</code></p>\n\n<p>The nesting of child elements allows us to do this (children is either an array for a nested element, or a string for a simple text child).</p>\n\n<pre><code>array('div',\n array('class' =&gt; 'container'),\n array(array('span', array(), 'One'),\n array('span', array(), 'Two')));\n</code></pre>\n\n<p>Which represents: </p>\n\n<pre><code>&lt;div class=\"container\"&gt;\n &lt;span&gt;One&lt;/span&gt;\n &lt;span&gt;Two&lt;/span&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Using <a href=\"http://php.net/manual/en/book.xmlwriter.php\" rel=\"nofollow\">XMLWriter</a> we can write this structure without too much trouble. I do that <a href=\"https://github.com/Evoke-PHP/Evoke-PHP/blob/bcf3dc976a4f2f6e4443d2eabce45ed444dcf61b/src/Evoke/Writer/XML.php#L103-193\" rel=\"nofollow\">here</a> in my library. The output from XMLWriter is always indented correctly, regardless of the context a template should appear in.</p>\n\n<p>This is a classic example of matching your data structure to the problem you are solving. By creating a tree to represent the X(HT)ML we can build components of the structure where they belong in our code, rather than being forced to get all of our echo statements in the correct order.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T06:19:12.607", "Id": "10813", "ParentId": "10809", "Score": "16" } }, { "body": "<p>If you want readable and easier code, consider using HAML. You don't have to close tags there and it will still be single presentation file, not in chunks as you suggest</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T09:56:43.000", "Id": "10953", "ParentId": "10809", "Score": "4" } }, { "body": "<p>It is <strong>absolutely critical</strong> that you <strong>escape</strong> your content and property values using <code>htmlentities()</code>. Otherwise, you could end up with invalid output, or possibly an HTML injection vulnerability in the worst case. (You <em>might</em> be able to trust that the tag names and attribute names contain no special characters.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T22:27:15.447", "Id": "40640", "ParentId": "10809", "Score": "7" } } ]
{ "AcceptedAnswerId": "10813", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T03:10:50.323", "Id": "10809", "Score": "22", "Tags": [ "php", "html" ], "Title": "HTML tag encoder" }
10809
<p>I've written a package manager for OS X in order to improve my Python skills. This is the second programming project I've ever worked on, so I do not expect it to be great, or anything, but I would like to get some input on the code and overall design.</p> <p>I store the package info inside a SQLite database, which I've written a class to work with. The main file contains another class which is supposed to be a library, so a working program would interact with it.</p> <p>This is the first time I've used a VCS, so I chose git, and <a href="https://github.com/caen1/lazy" rel="nofollow">I uploaded the repo to github</a>.</p> <p>And here is the code</p> <p><strong>lazy.py</strong></p> <pre><code>#!/usr/bin/env python3 """ This is the main class for Lazy. It provides all the basic operations the package manager should support in the forms of class methods. If you want to actually use Lazy, you need to write an interface for it. Lazy was written with Python 3 in mind, but it should work with Python 2 with minimal modification. """ import os import os.path import tarfile import hashlib import urllib.request import subprocess import shutil import lazy_db class Lazy(lazy_db.LazyDB): prefix = os.path.join("/usr", "local", "lazy") bindir = os.path.join(prefix, "bin") log_path = os.path.join(prefix, "logs") patch_path = 'patch' autoconf_ext = '.autoconf' patch_ext = '.patch' automake_ext = '.make' def install(self, pkg_id): """ This method takes a package id and installs the associated package. It does so by getting all the information from the database and calling different methods to perform the installation steps. """ self.resolve_dependencies(pkg_id) (self.pkg_id, self.name, self.download_url, self.md5, self.srcdir, self.objdir, self.args, self.installed_version, self.latest_version) = self.get_all_package_info(pkg_id) self.filename = self.download_package() self.extract_package() self.autoconf() self.automake() self.symlink() self.cleanup() def uninstall(self, pkg_id): """ This method takes a package id and uninstalls the associated package. """ pkg_name = self.get_package_name(pkg_id) install_path = os.path.join(self.prefix, pkg_name) bin_list = os.listdir(os.path.join(install_path, 'bin')) self.unlink_binaries(bin_list) self.remove_package_dir(install_path) self.update_installed_version(0, pkg_id) def search(self, pkg_name=None): """ This method takes a package name and returns a list of all related packages. If no name is given as argument, it returns all the packages. """ if not pkg_name: packages = self.get_all_packages() else: packages = self.get_packages_by_name(pkg_name) return packages def resolve_dependencies(self, pkg_id): """ This method takes a package id and installs all the dependencies of that package. There's an indirect recursion between this method and the `install` method. """ dependencies = self.get_dependencies(pkg_id) for dep_id in dependencies: if not self.is_installed(dep_id): self.install(dep_id) def download_package(self): """ This method downloads the archive for the package to be installed. It also performs a sanity check by comparing the md5 hash of the downloaded file against the hash available in the database. """ filename = self.download_url.split('/')[-1] with open(filename, "wb") as archive: data = urllib.request.urlopen(self.download_url) archive.write(data.read()) if not self.check_md5(filename): pass return filename def check_md5(self, filename): """ This method takes a filename and checks whether the file's md5 matches the one in the database. It is used for verifying the integrity of a downloaded package. """ with open(filename, "rb") as fh: file_md5 = hashlib.md5(fh.read()).hexdigest() return file_md5 == self.md5 def extract_package(self): """ This method decompresses a downloaded package. """ if tarfile.is_tarfile(self.filename): with tarfile.open(self.filename) as archive: archive.extractall() def autoconf(self): """ This method applies the required patches to a package and runs autoconf. The output of autoconf is logged under {lazy_logs}. autoconf always runs './configure --prefix={lazy_prefix}/{name}' additional flags might be used from the database """ basedir = os.getcwd() autoconf_script = os.path.join(basedir, self.srcdir, 'configure') autoconf_prefix = '--prefix=' + os.path.join(self.prefix, self.name) configure = [autoconf_script, autoconf_prefix] autoconf_db_args = self.args.split() configure.extend(autoconf_db_args) log_file = os.path.join(self.log_path, self.name + self.autoconf_ext) self.apply_patch(basedir) if not os.path.isdir(self.objdir): os.mkdir(self.objdir) os.chdir(self.objdir) with open(log_file, 'w') as log_fh: subprocess.call(configure, stdout=log_fh, stderr=log_fh) os.chdir(basedir) def apply_patch(self, basedir): """ This method goes into the source code directory and applies the patches from there. It logs the operation in {lazy_logs}. """ patches = self.get_patches(self.pkg_id) log_file = os.path.join(self.log_path, self.name + self.patch_ext) patch = ['patch', '-p0'] os.chdir(self.srcdir) with open(log_file, 'w') as log_fh: for patch_file in patches: patch_file = os.path.join(basedir, self.patch_path, patch_file) with open(patch_file) as patch_fh: subprocess.call(patch, stdin=patch_fh, stdout=log_fh, stderr=log_fh) os.chdir(basedir) def automake(self): """ This method runs automake inside the object directory. If successful, it also updates the installed version of the package. All operations are logged under {lazy_logs}. """ basedir = os.getcwd() log_file = os.path.join(self.log_path, self.name + self.automake_ext) make = ['make'] install = ['make', 'install'] os.chdir(self.objdir) with open(log_file, 'w') as log_fh: rvalue = subprocess.call(make, stdout=log_fh, stderr=log_fh) if rvalue == 0: rvalue = subprocess.call(install, stdout=log_fh, stderr=log_fh) os.chdir(basedir) if rvalue == 0: self.update_installed_version(self.latest_version, self.pkg_id) def cleanup(self): """ This method removes the files that were created during installation. """ shutil.rmtree(self.srcdir) if os.path.isdir(self.objdir): shutil.rmtree(self.objdir) os.remove(self.filename) def remove_package_dir(self, install_path): """ This method takes an installation path and removes it, effectively removing the package. """ shutil.rmtree(install_path) def symlink(self): """ This method creates symlinks for every binary of a package inside {bindir}. """ for binary in os.listdir(os.path.join(self.prefix, self.name, 'bin')): os.symlink(binary, os.path.join(self.bindir, binary)) def unlink_binaries(self, bin_list): """ This method takes a list of binaries and removes the symlinks in {bindir}. """ for binary in bin_list: os.unlink(os.path.join(self.bindir, binary)) </code></pre> <p><strong>lazy_db.py</strong></p> <pre><code>""" This file is an interface to the database for Lazy. All the methods dealing with the database are stored here. """ import sqlite3 class LazyDB: db_name = "lazy.sqlite" db_init_file = "lazy.sql" def __init__(self): """ When an instance of this class is created, it establishes a database connection. """ self.start_db_conn() def __del__(self): """ When an object is destroyed, the changes are committed, and the database connection is closed. """ self.db_conn.commit() self.close_db_conn() def start_db_conn(self): """ This method simply starts a database connection and creates a cursor for it. """ self.db_conn = sqlite3.connect(self.db_name) self.db_crsr = self.db_conn.cursor() def close_db_conn(self): """ This method simply closes a database connection. """ self.db_crsr.close() def get_package_info(self, col_list, pkg_id): """ This method takes a list of column names and a package id as arguments and returns the contents of the columns in the respective row. """ db_data = (pkg_id, ) columns = ", ".join(col_list) db_query = "SELECT " + columns + " FROM packages WHERE package_id = ?" self.db_crsr.execute(db_query, db_data) db_result = self.db_crsr.fetchall() return db_result def get_package_name(self, pkg_id): """ This method takes a package id and returns the name of the package. """ return self.get_package_info(["name"], pkg_id)[0][0] def get_package_download_url(self, pkg_id): """ This method takes a package id and returns the download url of the package. """ return self.get_package_info(["download_url"], pkg_id)[0][0] def get_package_md5(self, pkg_id): """ This method takes a package id and returns the md5 of the package. """ return self.get_package_info(["md5"], pkg_id)[0][0] def get_package_srcdir(self, pkg_id): """ This method takes a package id and returns the srcdir of the package. """ return self.get_package_info(["srcdir"], pkg_id)[0][0] def get_package_objdir(self, pkg_id): """ This method takes a package id and returns the objdir of the package. """ return self.get_package_info(["objdir"], pkg_id)[0][0] def get_package_args(self, pkg_id): """ This method takes a package id and returns the autoconf arguments of the package. """ return self.get_package_info(["args"], pkg_id)[0][0] def get_installed_version(self, pkg_id): """ This method takes a package id and returns whether the installed version of the package. """ return self.get_package_info(["installed_version"], pkg_id)[0][0] def get_latest_version(self, pkg_id): """ This method takes a package id and returns the latest version of the package. """ return self.get_package_info(["latest_version"], pkg_id)[0][0] def get_package_id(self, pkg_name): """ This method takes the name of a package and returns its id. """ db_data = (pkg_name, ) db_query = "SELECT package_id FROM packages WHERE name = ? LIMIT 1" self.db_crsr.execute(db_query, db_data) return self.db_crsr.fetchone()[0] def update_package_info(self, col_name, col_value, pkg_id): """ This method takes a column name and a new value for that column, and updates the database row accordingly. """ data = (col_value, pkg_id, ) db_query = "UPDATE packages SET " + col_name + " = ? " db_query += "WHERE package_id = ?" self.db_crsr.execute(db_query, data) def update_name(self, new_name, pkg_id): """ This method takes a package id and a new name for that package and modifies the database records accordingly. """ self.update_package_info("name", new_name, pkg_id) def update_download_url(self, new_url, pkg_id): """ This method takes a package id and a new download url for that package and modifies the database records accordingly. """ self.update_package_info("download_url", new_url, pkg_id) def update_md5(self, new_md5, pkg_id): """ This method takes a package id and a new md5 hash for that package and modifies the database records accordingly. """ self.update_package_info("md5", new_md5, pkg_id) def update_srcdir(self, new_srcdir, pkg_id): """ This method takes a package id and a new srcdir for that package and modifies the database records accordingly. """ self.update_package_info("srcdir", new_srcdir, pkg_id) def update_objdir(self, new_objdir, pkg_id): """ This method takes a package id and a new objdir for that package and modifies the database records accordingly. """ self.update_package_info("objdir", new_objdir, pkg_id) def update_args(self, new_args, pkg_id): """ This method takes a package id and a new set of autoconf arguments for that package and modifies the database records accordingly. """ self.update_package_info("args", new_args, pkg_id) def update_installed_version(self, new_version, pkg_id): """ This method takes a package id and updates the installed version of the package accordingly. """ self.update_package_info("installed_version", new_version, pkg_id) def update_latest_version(self, new_version, pkg_id): """ This method updates the latest available version of a given package. """ self.update_package_info("latest_version", new_version, pkg_id) def init_db(self): """ This method initiates the database by running the .sql file bundled with the application. """ with open(self.db_init_file) as init_fh: self.db_crsr.executescript(init_fh.read()) def add_package(self, package_info): """ This method inserts a package into the database. It takes a dictionary of (column_name:value) pairs and creates a new package based on those. """ p = package_info db_data = (p['name'], p['download_url'], p['md5'], p['srcdir'], p['objdir'], p['args'], p['latest_version']) db_query = """ INSERT INTO packages (name, download_url, md5, srcdir, objdir, args, latest_version) VALUES(?, ?, ?, ?, ?, ?, ?) """ self.db_crsr.execute(db_query, db_data) def remove_package(self, pkg_id): """ This method takes a package id and removes the respective package. """ db_data = (pkg_id, ) db_query = "DELETE FROM packages WHERE package_id = ? LIMIT 1" self.db_crsr.execute(db_query, db_data) def get_dependencies(self, pkg_id): """ This method returns a list of dependencies for a given package. """ db_data = (pkg_id, ) db_query = "SELECT package_dep_id FROM dependencies " db_query += "WHERE package_id = ?" self.db_crsr.execute(db_query, db_data) db_result = self.db_crsr.fetchall() deps = [result[0] for result in db_result] return deps def add_dependency(self, dep_id, pkg_id): """ This method takes a dependency and associates it to a given package. """ db_data = (pkg_id, dep_id, ) db_query = """ INSERT INTO dependencies(package_id, package_dep_id) VALUES(?, ?) """ self.db_crsr.execute(db_query, db_data) def remove_dependency(self, dep_id, pkg_id): """ This method takes a dependency and removes it from the database. """ db_data = (dep_id, pkg_id) db_query = "DELETE FROM dependencies WHERE package_dep_id = ? " db_query += "AND package_id = ? LIMIT 1" self.db_crsr.execute(db_query, db_data) def get_patches(self, pkg_id): """ This method takes a package id and returns the patch file(s) of the package. """ db_data = (pkg_id, ) db_query = "SELECT patch_file FROM patches WHERE package_id = ?" self.db_crsr.execute(db_query, db_data) db_result = self.db_crsr.fetchall() patches = [result[0] for result in db_result] return patches def add_patch(self, patch_file, pkg_id): """ This method takes the name of a patch file and a package id and associates the patch file to its package. """ db_data = (patch_file, pkg_id, ) db_query = "INSERT INTO patches(patch_file, package_id) VALUES(?, ?)" self.db_crsr.execute(db_query, db_data) def remove_patch(self, patch_file, pkg_id): """ This method takes a patch file and a package id and removes the patch from the database. """ db_data = (patch_file, pkg_id, ) db_query = """ DELETE FROM patches WHERE patch_file = ? AND package_id = ? """ self.db_crsr.execute(db_query, db_data) def is_installed(self, pkg_id): """ This method takes a package id and determines whether it is installed or not. """ return self.get_installed_version(pkg_id) != 0 def get_all_packages(self): """ This method returns the names of all the available packages. """ db_query = "SELECT name FROM packages" self.db_crsr.execute(db_query) db_result = self.db_crsr.fetchall() return [result[0] for result in db_result] def get_packages_by_name(self, pkg_name): """ This method takes a package name and returns all the related packages. """ db_data = ("%" + pkg_name + "%", ) db_query = "SELECT name FROM packages WHERE name LIKE ?" self.db_crsr.execute(db_query, db_data) db_result = self.db_crsr.fetchall() return [result[0] for result in db_result] def get_all_package_info(self, pkg_id): """ This method takes a package id and returns all the package info associated with it. """ db_data = (pkg_id, ) db_query = "SELECT * FROM packages WHERE package_id = ? LIMIT 1" self.db_crsr.execute(db_query, db_data) db_result = self.db_crsr.fetchone() return db_result </code></pre> <p><strong>lazy.sql</strong></p> <pre><code>/* This is the file which lays down the database structure of the Lazy package manager. Although Lazy uses SQLite, the file should be kept as portable as possible, so it should work with other SQL implementations with close to no modification. It includes a sample package `splint`, a linter for C. It was chosen because it requires a patch in order to compile under OS X. */ -- Let's drop any existing tables DROP TABLE IF EXISTS packages; DROP TABLE IF EXISTS dependencies; DROP TABLE IF EXISTS patches; -- This table contains info about the packages CREATE TABLE IF NOT EXISTS packages ( package_id INTEGER PRIMARY KEY, name TEXT NOT NULL, download_url TEXT NOT NULL, md5 TEXT NOT NULL, srcdir TEXT NOT NULL, objdir TEXT NOT NULL, args TEXT NOT NULL DEFAULT '', installed_version INTEGER NOT NULL DEFAULT 0, latest_version INTEGER NOT NULL ); -- This table contains dependencies info CREATE TABLE IF NOT EXISTS dependencies ( dep_id INTEGER PRIMARY KEY, package_id INTEGER NOT NULL REFERENCES packages(package_id), package_dep_id INTEGER NOT NULL REFERENCES package(package_id) ); -- This table contains info about patches to be applied to files CREATE TABLE IF NOT EXISTS patches ( patch_id INTEGER PRIMARY KEY, package_id INTEGER NOT NULL REFERENCES packages(package_id), patch_file TEXT NOT NULL ); -- Add `splint` INSERT INTO packages(name, download_url, md5, srcdir, objdir, latest_version) VALUES( 'splint', 'http://www.splint.org/downloads/splint-3.1.2.src.tgz', '25f47d70bd9c8bdddf6b03de5949c4fd', 'splint-3.1.2', 'splint-3.1.2', 312); INSERT INTO patches(package_id, patch_file) VALUES(1, 'splint.diff'); </code></pre>
[]
[ { "body": "<pre><code>def install(self, pkg_id):\n \"\"\"\n This method takes a package id and installs the associated package. It\n does so by getting all the information from the database and calling\n different methods to perform the installation steps.\n \"\"\"\n self.resolve_dependencies(pkg_id)\n\n (self.pkg_id, self.name, self.download_url, self.md5,\n self.srcdir, self.objdir, self.args, self.installed_version,\n self.latest_version) = self.get_all_package_info(pkg_id)\n</code></pre>\n\n<p>That's a lot of data to be fetching. What if you want to add or remove or change the order of some of that? Instead, put all of that information into a <code>Package</code> class and return that. </p>\n\n<p>Don't store temporary state on self. If you need to pass temporary information use parameters.</p>\n\n<p><code>get_all_package_info</code> is from LazyDB. But Lazy <em>uses</em> LazyDB it is not a specialization of <em>LazyDB</em>. So you shouldn't inherit from LazyDB, instead you should store a refence to LazyDB as <code>self.db</code>.</p>\n\n<pre><code> self.filename = self.download_package()\n self.extract_package()\n self.autoconf()\n self.automake()\n self.symlink()\n self.cleanup()\n</code></pre>\n\n<p>All of this relates specifically to the package, it should all really be done by calling <code>package.install()</code> where <code>package</code> is the package object you should return.</p>\n\n<p>Overall, this function should look like</p>\n\n<pre><code>def install(self, pkg_id):\n package = self.db.load(pkg_id)\n self.resolve_dependencies(package)\n package.install()\n</code></pre>\n\n<p>You've got functions to manipulate pretty much every possible field you might want to change in the database. Instead, I'd suggest having a few functions, that work with <code>Package</code> objects. </p>\n\n<p>The thing with package managers is that you typically want to update the package details without changing the information about what the user has installed. But you've got that data in the same table. What you probably want to do is actually have two databases. One database has the package information, and you update it by downloading a new copy to replace the old one. The other package has the installation information.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T19:05:34.387", "Id": "17246", "Score": "0", "body": "Hmm... so what you're saying is that I should write a third class with attributes such as \"name\" and \"download_url\", and methods such as \"install\" and \"download_package\"? So in a MVC analogy, LazyDB and Package would be the Models, Lazy the Controller, and the eventual CLI program the View (the View is kind of a stretch)? Also, thanks for the input, it's greatly valued!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T19:21:03.473", "Id": "17248", "Score": "0", "body": "@GreweKokkor, yes that's a good description of what I'm suggesting" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T18:44:18.453", "Id": "10827", "ParentId": "10816", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T10:19:19.573", "Id": "10816", "Score": "1", "Tags": [ "python" ], "Title": "Package Manager in Python" }
10816
<p>I have written the following get/set for a username which is stored in local Storage. Do you think this "buys" me anything or even perhaps has major disadvantages? I have never liked relying on global variables so I figured the getter and setter would be tidier and more maintainable. </p> <pre><code>var namespace = {}; namespace.username = { key: "Username", get: function() { return localStorage.getItem(this.key)}, set: function(value) {localStorage.setItem(this.key, value)} }; </code></pre> <p>before the code had "constants" (I know they arent real in JS)</p> <pre><code>LOCAL_STORAGE = { USERNAME: "Username" } </code></pre> <p>and everywhere I need access to the username I would write:</p> <pre><code>localStorage.getItem(LOCAL_STORAGE.USERNAME); </code></pre>
[]
[ { "body": "<p>I think this is a matter of taste, I don't see any major disadvantages but no major advantages either. In these cases I would err on the side of simplicity and go with querying localStorage directly.</p>\n\n<p>Now to fully whet my morning CR.SE appetite let's get really nitpicky:</p>\n\n<ul>\n<li><p>Pros</p>\n\n<ul>\n<li>It will make it marginally easier to change your code if you some day decide to use a different storage mechanism (for example a fallback mechanism if localStorage doesn't exist). This is only marginally easier unless your code is partitioned in such a way that a global search for LOCAL_STORAGE.USERNAME won't work</li>\n<li>From the standpoint of coding practice, it IS generally considered better to hide all your external dependencies, and a good argument can be made that localStorage is one </li>\n<li>Gets rid of your LOCAL_STORAGE keys object</li>\n<li>Getters and setters are familiar to people coming from a java background</li>\n</ul></li>\n<li><p>Cons</p>\n\n<ul>\n<li>You actually have more global objects now, as window.namespace.username and all it's children are now effectively global (though namespaced)</li>\n<li>If someone picks up your code they might not see the localStorage references and assume that you don't depend on it. They might therefore make decisions (for example to deploy to an old IE) that might damage stability. (this is the counterpoint to abstracting away external dependencies).</li>\n<li>Getters and setters are icky and anti-intuitive for someone not coming from the java world</li>\n<li>Someone has to learn your api to use it the way you want it to be used. While your code makes the assumption that they are accessing username through your object, someone could very reasonably pick up the code, open up devtools, see that there is a Username key in localStorage, and start querying it directly thereby breaking your expectation. In short, it's so easy to access localstorage, there's no reason for them to expect that you abstracted it.</li>\n<li>Are you going to follow the same pattern for other objects too? You really should pick one pattern and stick to it and only make exceptions when there is a good reason to.</li>\n<li>Because you're using <code>this</code> someone can use new, or call, or apply and break your username functions</li>\n</ul></li>\n<li><p>General Notes</p>\n\n<ul>\n<li><code>localStorage.getItem('Username')</code> is in no way worse than <code>localStorage.getItem(LOCAL_STORAGE.USERNAME)</code>. I would wager it's better because it is less typing and more obvious. <strong>Butbutbut it's a magic string!</strong> This is javascript, not java, <a href=\"http://wekeroad.com/2010/05/04/do-androids-dream-of-vim/\" rel=\"nofollow\">it's all magic strings</a>. Note that my own personal preference is to use <code>'</code> to differentiate a token (similar to ruby's :token) from text for which I use <code>\"</code>.</li>\n<li>LOCAL_STORAGE - I really dislike that naming convention. Whatever works for you I guess, but what is the semantic meaning of all-caps? How is it semantically different than namespace.localStorageKeys?</li>\n<li>Do you really need a setter? I image that you're only going to be setting Username in one place - why make a global method then?</li>\n<li><p>So you still want to abstract away localStorage? How about a more javascript-y approach? </p>\n\n<pre><code>myNamespace.storage = function(key, val) {\n return val === undefined ? \n localStorage.getItem(key) : localStorage.setItem(key, val);\n}\n</code></pre>\n\n<p>then:</p>\n\n<pre><code>myNamespace.storage('Username', \"George\");\nmyNamespace.storage('Username') == \"George\";\n</code></pre>\n\n<p>This is of course a very naive implementation, you could probably add some more logic handling serializing/deserializing objects from json and fallback mechanisms.</p></li>\n</ul></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T14:51:14.997", "Id": "17243", "Score": "0", "body": "You always offer such detailed/valuable answers! Thanks. I think you may well be right about leaving the abstraction and the CAPS const' convention. I used caps to define a constant (even though they don't really exist in JS) and I store them in an object to prevent type errors." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T14:39:49.870", "Id": "10822", "ParentId": "10820", "Score": "7" } }, { "body": "<p>George Mauer already provided a wonderful answer I totally agree with him. I have only one focus in this review and that is speed.</p>\n\n<hr>\n\n<p>Your code is very slow/not very efficient right now, even though it may not totally seem like it. This is because you are interacting with <code>localStorage</code> too much, and interacting with <code>localStorage</code> can be slow (I mean, you are accessing this external memory bank for data perhaps many times).</p>\n\n<p>An easy way to speed this up would be to store the local storage in this object itself. To do this, you could create an init method that simply copies local storage into the object:</p>\n\n<pre><code>init: function() {\n for(var key in localStorage) {\n if(localStorage.hasOwnProperty(key)) {\n this.storage[key] = localStorage[key];\n }\n }\n}\n</code></pre>\n\n<p>Then, when called, will go through local storage, taking all of it's data and copying it into this <code>storage</code> object (you can call it something else). Now, instead of accessing localStorage when looking for and setting data, we can use <code>this.storage</code>:</p>\n\n<pre><code>get: function(key) { return this.storage[key]; }\nset: function(key, val) { this.storage[key] = val; }\n</code></pre>\n\n<p>This code will be much faster now because rather than constantly accessing local storage, you can access this local object instead.</p>\n\n<p>Of course, this data will not be stored when the browser closes, so another method is needed to save this data back to local storage. You can call this <code>save</code>:</p>\n\n<pre><code>save: function() {\n ... copy this.storage data into localStorage ...\n}\n</code></pre>\n\n<hr>\n\n<p>As was pointed out to me, this could potentially slow the heck out of a program when first initialized if the storage contains a lot of data.</p>\n\n<p>As a simple fix, you can have have the <code>init</code> method take an optional parameter of which data to take over in the form of keys:</p>\n\n<pre><code>init: function(keys) {\n ...\n // if keys was supplied and this current key is in the list of keys to take\n if(keys !== undefined &amp;&amp; keys.indexOf(key) !== -1) {\n this.storage[key] = localStorage[key];\n }\n}\n</code></pre>\n\n<p>This should be good enough. However, if you want to go a step further, you can also have another optional parameter for specifying how much data to read in. Ex: 1500 bytes.</p>\n\n<p>This would be much more complicated. For every piece of data you read in, you would have to read how big that data is and add it to a total data size counter. Then, once you read too much, you'll have to trim down data from the last read you just did.</p>\n\n<p>I don't have time to cook up an example now, but you might be able to come up with this on your own.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-01T18:30:11.700", "Id": "121592", "ParentId": "10820", "Score": "1" } } ]
{ "AcceptedAnswerId": "10822", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T13:35:47.110", "Id": "10820", "Score": "4", "Tags": [ "javascript", "html5", "browser-storage" ], "Title": "Getters and Setters for localStorage" }
10820
<p>The question asked to find all the prime numbers within a particular range. The way I approached this was to loop through each of the numbers within the range and for each number check whether it's a prime. My method for checking prime is to start at 3 and loop till number/2 in hops of 2 (essentially excluding all the even numbers).</p> <p>Can somebody take a look at the code an tell me how I might be able to better this snippet and what are some of the aspects that I am missing?</p> <pre><code>public class PrimeBetween{ public static void main(String[] args){ printAllPrimes(Integer.parseInt(args[0]),Integer.parseInt(args[1])); } public static void printAllPrimes(int start,int end){ for(int i = start;i &lt;= end;i++){ if(isPrime(i)) System.out.println("Print prime:"+i); } } private static boolean isPrime(int i){ if(i%2 == 0 &amp;&amp; i!=2) return false; else{ if(i == 1) return false; for(int p=3;p&lt;=i/2;p+=2){ if(i%p == 0) return false; } return true; } } } </code></pre>
[]
[ { "body": "<p>Well, for starters, it is a proven mathematical fact that if a number is prime, it is not divisible by any prime number that is less than its square root. In your inner loop you go up to <code>i/2</code> and you can change this to <code>Math.floor(Math.sqrt(i))</code>.</p>\n\n<p>Because you are checking for a range of numbers, you would probably benefit from a cache of primes, rather than testing every odd number less than the square root.</p>\n\n<p>Something like this:</p>\n\n<pre><code>package mypackage;\n\nimport java.util.ArrayList;\n\n/**\n * Checks for primeness using a cache.\n */\npublic class PrimeCache {\n\n private static ArrayList&lt;Integer&gt; cache = null;\n\n static {\n cache = new ArrayList&lt;Integer&gt;();\n cache.add(2);\n }\n\n public static boolean isPrime(int i) {\n if (i == 1) return false; // by definition\n\n int limit = (int) Math.floor(Math.sqrt(i));\n populateCache(limit);\n\n return doTest(i, limit);\n }\n\n private static void populateCache(int limit) {\n int start = cache.get(cache.size() - 1) + 1;\n for (int i = start; i &lt;= limit; i++) {\n if (simpleTest(i)) cache.add(i);\n }\n }\n\n private static boolean simpleTest(int i) {\n int limit = (int) Math.floor(Math.sqrt(i));\n\n return doTest(i, limit);\n }\n\n private static boolean doTest(int i, int limit) {\n int counter = 0;\n while (counter &lt; cache.size() &amp;&amp; cache.get(counter) &lt;= limit) {\n if (i % cache.get(counter) == 0) return false;\n counter++;\n }\n\n return true;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-22T20:03:49.540", "Id": "96129", "Score": "0", "body": "It is dangerous to use an `ArrayList` as a cache, as soon as the cache gets used by more than one thread." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T15:20:34.960", "Id": "10824", "ParentId": "10823", "Score": "11" } }, { "body": "<p>You could also use the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_eratosthenes\" rel=\"nofollow\">sieve of Eratosthenes</a> so as to improve time complexity. It has a lot of optimizations, you can even reduce the memory footprint by using bit operations, and many others, if you're into maths.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T19:19:38.080", "Id": "10829", "ParentId": "10823", "Score": "3" } }, { "body": "<p>I just realized that - well, by definition - you only need to check a number against the primes smaller than the number - not every smaller number. This is the siev of Eratosthenes in the form of an array but not only for 2, 3 and five, but every prime number. In fact you only need to check against primes smaller than the numbers square root. So if you are looking for a table of say the first 40000 prime numbers, you could do this: </p>\n\n<pre><code>public int[] nPrimes(int targetNumberOfPrimes) {\n\n int index, candidate;\n\n int[] primes = new int[targetNumberOfPrimes];\n\n while (index &lt; targetNumberOfPrimes) {\n if (candidate &lt; 2) {\n candidate++;\n continue;\n }\n if (isPrime(index, candidate, primes)){\n primes[index] = candidate;\n index++;\n }\n candidate++;\n }\n return primes;\n}\n\nprivate static boolean isPrime(int current, int candidate, int[] primes){\n for (int i = 0; i &lt; current &amp;&amp; primes[i] &lt; Math.floor(Math.sqrt(candidate)); i++){\n if (candidate % primes[i] == 0) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>It took my computer about 0.7 seconds for 40000 prime numbers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-04T19:49:05.593", "Id": "52462", "ParentId": "10823", "Score": "1" } }, { "body": "<p>Using a <code>BitSet</code> to hold the numbers is pretty efficient. I've been able to find the primes up to about 2 billion using one. This finds almost 100 million primes in well under a minute.</p>\n\n<p>I can post the code if there is any interest, but I make NO claims for its quality. I also don't claim to be a good object-oriented programmer.</p>\n\n<p>Using Sieve of Eratosthenes logic, you don't have to do ANY dividing. It just isn't required. I also used a <code>BitSet</code> to maximize how many numbers I could check.</p>\n\n<p>I found that I needed a separate loop to 'sieve' out the even numbers higher than 2. The main logic just didn't work for 2.</p>\n\n<p>Also, when marking out the non-primes, you only need to start at the square of the prime you just found. This is because any smaller non-prime will have already been 'sieved' out because it is divisible by a smaller prime, which you will have already found and processed. Also, your increment for the 'sieve' can be 2 times the prime you're sieving for (because the others would be even numbers, so no need to check them).</p>\n\n<p>Here's my implementation:</p>\n\n<pre><code>//package Eratosthenes5;\n\nimport java.io.IOException;\n\nimport java.io.*;\nimport java.util.*;\n//import java.lang.Math.*;\n//import java.text.DecimalFormat;\n//import java.awt.*;\n//import javax.swing.*;\n\npublic class Eratosthenes5 {\n\n\n// This uses a BitSet instead of a boolean array to see\n// if this saves any memory. It enables me to test approx.\n// 8x as many numbers. 109905151 is no longer my max.\n// The highest number I've reached, so far, is around 879,400,000.\n//\n// After giving more memory to the app, I can check for primes up\n// to around 2 billion. I've not determined the upper limit, but\n// I suspect it is the java max integer size. It finds almost \n// 100 million primes in under a minute.\n// 2^31 = 2,147,483,648 \n\n\n /**\n * @param args\n * @throws IOException\n */\n public static void main(String[] args) throws IOException \n {\n int maxSize = 1;\n int maxNumber;\n int maxSearch;\n int primeCount;\n int maxPrime;\n String name;\n name = getTheMaxNumber();\n while (name.compareTo(\"1\") != 0) \n { \n long startTime = System.currentTimeMillis();\n maxSize = Integer.parseInt(name);\n maxNumber = maxSize + 1; \n maxSearch = (int) java.lang.Math.sqrt(maxNumber);\n primeCount = 1; //Start the count at 1 because 2 is prime and we'll start at 3\n maxPrime = -1;\n //use a BitSet array to maximize how many primes can be found\n BitSet numbList = new BitSet( maxNumber );\n\n numbList.set(0, maxNumber-1, true); //set all bits to true\n\n numbList.clear(0);\n numbList.clear(1);\n\n //clear the even numbers (except 2, it's prime)\n for (long k = 4; k &lt;= maxSize; k+=2)\n {\n numbList.clear((int)k);\n }\n\n // sieve out the non-primes\n for (int k = 3; k &lt; maxSearch; k+=2)\n { \n if (numbList.get(k))\n { \n sieveTheRest(k, numbList, maxSize);\n }\n } \n\n //Count the primes\n for (int k = 3; k &lt;= maxSize; k+=2)\n { \n if (numbList.get(k))\n { \n maxPrime = k;\n primeCount +=1;\n if (primeCount % 1000000 == 0)\n {\n System.out.format(\"the \" + ((primeCount/1000000 &lt; 100) ? \" \" : \"\") \n + ((primeCount/1000000 &lt; 10) ? \" \" : \"\")\n + primeCount/1000000 + \" millionth prime is: %,11d%n\",maxPrime);\n }\n }\n }\n\n //we're done\n System.out.format(\"\\nMy integer from beg: %,11d%n\", Integer.parseInt(name));\n System.out.format(\"array size : %,11d%n\", maxNumber);\n // System.out.format(\"prime count : %,11d%n\", primeCount);\n System.out.format(\"prime count : %,11d%n\", numbList.cardinality());\n System.out.format(\"largest prime found: %,11d%n\", maxPrime);\n System.out.format(\"max factor : %,11d%n \\n\", maxSearch);\n\n long stopTime = System.currentTimeMillis();\n System.out.println(\"That took \" + (stopTime - startTime)/1000.0 + \" seconds\");\n\n name = getTheMaxNumber();\n }//end of while \n System.out.println(\"\\nEnd of program\");\n\n\n }//End of method Main\n /**\n * \n * @return Passes back a string holding the maximum number to check \n */\n static String getTheMaxNumber()\n {\n BufferedReader dataIn = new BufferedReader(new\n InputStreamReader( System.in) );\n String bigNumber = \"\";\n System.out.print(\"Please enter an integer value (1 to quit): \");\n try\n {\n bigNumber = dataIn.readLine();\n }\n catch( IOException e )\n {\n System.out.println(\"Error!\");\n } \n return bigNumber;\n\n }\n /**\n * @param myPrime The latest prime to be found.\n * @param theBitSet The BitSet holding the prime flags\n * @param maxSize The largest index in the BitSet\n */ \n static void sieveTheRest(int myPrime, BitSet theBitSet, int maxSize)\n {\n for (long k = myPrime*myPrime; k &lt;= maxSize; k+=2*myPrime)\n {\n theBitSet.clear((int) k);\n }\n }\n\n}//End of Class eratosthenes5\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-22T14:09:04.767", "Id": "96078", "Score": "3", "body": "Hi, and welcome to code review. You should consider posting your code as a question, and get it reviewed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-22T15:18:35.910", "Id": "96090", "Score": "0", "body": "Well, here is my code, but I don't really have any questions about it. It works for me and I've been able to verify my results with some on-line lists of prime numbers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-24T02:38:47.677", "Id": "96409", "Score": "0", "body": "Thank you for the help, Jamal. I'm very new to posting and I struggle trying to figure out how to do things right. I appreciate your help and I would welcome any comments on the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-24T02:42:05.010", "Id": "96411", "Score": "0", "body": "What We meant is that you should [ask the code as a new question ;-)](http://codereview.stackexchange.com/questions/ask) (Which I still think you should consider)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-24T06:48:39.957", "Id": "96429", "Score": "0", "body": "Ok, I posted the code under a separate question. Feels a bit redundant, though." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-22T13:49:58.693", "Id": "54942", "ParentId": "10823", "Score": "2" } } ]
{ "AcceptedAnswerId": "10824", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T15:01:03.957", "Id": "10823", "Score": "8", "Tags": [ "java", "optimization", "algorithm", "primes" ], "Title": "Yet another prime number generator" }
10823
<p>For various reasons, I'm parsing a string, this code will explain what I'm after:</p> <pre><code>string baseString = "This is a \"Very Long Test\""; string[] strings = baseString.Split(' '); List&lt;String&gt; stringList = new List&lt;string&gt;(); string temp = String.Empty; foreach (var s in strings) { if (!String.IsNullOrWhiteSpace(temp)) { if (s.EndsWith("\"")) { string item = temp + " " + s; stringList.Add(item.Substring(1,item.Length - 2)); temp = string.Empty; } temp = temp + " " + s; } else if (s.StartsWith("\"")) { temp = s; } else { stringList.Add(s); } } stringList.ForEach(Console.WriteLine); </code></pre> <p>The output should be:</p> <pre><code>This is a Very Long Test </code></pre> <p>Basically, given a string, it will split it on spaces, unless its grouped into speech marks, the same way the command line does it.</p> <p>Any better way to do this code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T19:06:26.127", "Id": "17247", "Score": "2", "body": "It's usually a bad idea to concatenate strings in a loop. If performance matters to you, you should probably use `StringBuilder` instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T04:37:11.247", "Id": "17260", "Score": "0", "body": "What about something like \"This is a \\\"Very Long\\\" Test\\\"\" ? Is there a guarantee that the \\\" 's will come in pairs? other wise the problem is too ill defined for a proper solution" } ]
[ { "body": "<p>Seems like a job for a regular expression:</p>\n\n<pre><code>string baseString = \"This is a \\\"Very Long Test\\\"\";\nvar re = new Regex(\"(?&lt;=\\\")[^\\\"]*(?=\\\")|[^\\\" ]+\");\nvar strings = re.Matches(baseString).Cast&lt;Match&gt;().Select(m =&gt; m.Value).ToArray();\n</code></pre>\n\n<p>What the regular expression <code>(?&lt;=\")[^\"]*(?=\")|[^\" ]+</code> does is that it either finds a sequence of zero or more characters that are not <code>\"</code> (<code>[^\"]*</code>) preceded by a <code>\"</code> (<code>(?&lt;=\")</code>) and followed by a <code>\"</code> (<code>(?=\")</code>) or a sequence of one or more character that are not <code>\"</code> or a space (<code>[^\" ]+</code>).</p>\n\n<p>For the sample input, it gives the same output as your version. The code itself is much simpler, but the regular expression might be hard to understand, especially if you're not used to them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T19:42:06.223", "Id": "17249", "Score": "0", "body": "A header comment could easily resolve the hard to understand part? Other than that I don't think it's any harder to understand than the original Q." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T02:37:36.850", "Id": "17256", "Score": "0", "body": "Looks cool. Could you elaborate on why you need `(?<=)` and `(?=\")` as opposed to just `(\")[^\"](\")`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T06:21:37.850", "Id": "17262", "Score": "0", "body": "@Leonid, the difference is that if you did it your way, the quotation marks would be part of the match, so you would need to remove them later, for example by using `Select(m => m.Value.Trim('\"'))`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T19:03:32.373", "Id": "10828", "ParentId": "10826", "Score": "8" } }, { "body": "<pre><code> string baseString = \"This is a \\\"Very Long Test\\\"... not so long actually, eh?\";\n string[] aux = baseString.Split('\"');\n List&lt;string&gt; tokens = new List&lt;string&gt;();\n for (int i = 0; i &lt; aux.Length; ++i)\n if (i % 2 == 0)\n tokens.AddRange(aux[i].Split(' '));\n else\n tokens.Add(aux[i]);\n</code></pre>\n\n<p>Notice that if there is a double quote in the middle of a word it will be split (a\"ctuall\"y would be a, ctuall, y in the final result). If the last double quote is unmatch it won't split from its position to the end of the string.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T01:31:16.080", "Id": "10841", "ParentId": "10826", "Score": "3" } }, { "body": "<p>The usual approach to this kind of tokenising is to count the number of markers (it shares the same idea as hit scanning a polygon). </p>\n\n<p>Scan the string one character at a time, checking if the character is a space or a quote mark, or any other character. If it's quote mark, toggle your quote flag indicating you are within a delimited string and output the current scanned token if transitioning from 'in delimited string' to 'not in delimited string'. If it's a space and you're 'not in a delimited string', output the currently scanned token. All other characters get added to the currently scanned token.</p>\n\n<p>After the final character has been processed, if output the currently scanned token if there are any remaining characters that have been scanned but not output.</p>\n\n<p>Untested, but the general approach:</p>\n\n<pre><code>StringBuilder currentToken = new StringBuilder();\nbool inDelimitedString = false;\nList&lt;string&gt; scannedTokens = new List&lt;string&gt;();\nforeach (char c in source)\n{\n switch(c)\n {\n case '\"':\n if (inDelimitedString)\n {\n if (currentToken.Length &gt; 0)\n {\n scannedTokens.Add(currentToken.ToString());\n currentToken.Clear();\n }\n }\n inDelimitedString = !inDelimitedString;\n break;\n case ' ':\n if (!inDelimitedString)\n {\n if (currentToken.Length &gt; 0)\n {\n scannedTokens.Add(currentToken.ToString());\n currentToken.Clear();\n }\n }\n else\n {\n currentToken.Append(c);\n }\n break;\n default:\n currentToken.Append(c);\n break;\n }\n}\nif (currentToken.Length &gt; 0)\n{\n scannedTokens.Add(currentToken.ToString());\n currentToken.Clear();\n}\n</code></pre>\n\n<p>You can extend the same idea to counting braces (e.g. '(' matching to ')', '[' to ']') which allow nesting, and your performance costs remain O(n). </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-24T00:17:36.677", "Id": "111657", "ParentId": "10826", "Score": "0" } } ]
{ "AcceptedAnswerId": "10828", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T18:08:23.033", "Id": "10826", "Score": "3", "Tags": [ "c#", "strings", "parsing" ], "Title": "Splitting a string into words or double-quoted substrings" }
10826
<p>Can anyone suggest any improvements to this <code>RangeFinder</code> class?</p> <pre><code>import serial from collections import deque def str2int(x): try: return int(x) except ValueError: pass class RangeFinder(object): def __init__(self, mem=3) : self.mem = deque(maxlen=mem) self.absmax = -10**10 self.absmin = 10**10 self.relmax = None self.relmin = None def __call__(self, input) : try: self.mem.append(input) if len(self.mem) == self.mem.maxlen : self.relmax = max(self.mem) if self.relmax &gt; self.absmax : self.absmax = max(self.mem) self.relmin = min(self.mem) if self.relmin &lt; self.absmin : self.absmin = self.relmin except TypeError: pass dev = '/dev/tty.usbserial-A60085VG' baud = 9600 serial_reader = serial.Serial(dev,baud) rf = RangeFinder(5) for data in serial_reader: rf(str2int(data)) print( rf.mem ) </code></pre> <p>I have printed the output of the short term memory used to give a relative max / min and test for absolute max and min:</p> <blockquote> <pre><code>sh &gt; python3 serial_helper2.py deque([877], maxlen=5) deque([877, 877], maxlen=5) deque([877, 877, 877], maxlen=5) deque([877, 877, 877, 877], maxlen=5) deque([877, 877, 877, 877, 877], maxlen=5) deque([877, 877, 877, 877, 877], maxlen=5) deque([877, 877, 877, 877, 877], maxlen=5) deque([877, 877, 877, 877, 876], maxlen=5) deque([877, 877, 877, 876, 876], maxlen=5) deque([877, 877, 876, 876, 876], maxlen=5) deque([877, 876, 876, 876, 875], maxlen=5) deque([876, 876, 876, 875, 875], maxlen=5) </code></pre> </blockquote>
[]
[ { "body": "<pre><code>import serial\nfrom collections import deque\n\ndef str2int(x):\n try: \n return int(x)\n except ValueError:\n pass\n</code></pre>\n\n<p>returning <code>None</code> is rarely more useful then throwing the exception. Learn to love exceptions, and don't write functions like this that just turn them into <code>None</code></p>\n\n<pre><code>class RangeFinder(object):\n\n def __init__(self, mem=3) :\n self.mem = deque(maxlen=mem)\n self.absmax = -10**10\n self.absmin = 10**10\n self.relmax = None\n self.relmin = None\n\n def __call__(self, input) :\n</code></pre>\n\n<p>callable objects are rarely the right thing. Its usually clearer to just use a regular method</p>\n\n<pre><code> try:\n self.mem.append(input)\n</code></pre>\n\n<p>So you pass None in here and then stick in on the queue. That doesn't seem like a good idea. Probably, you should avoid calling this when the data was invalid</p>\n\n<pre><code> if len(self.mem) == self.mem.maxlen : \n self.relmax = max(self.mem)\n if self.relmax &gt; self.absmax :\n self.absmax = max(self.mem) \n</code></pre>\n\n<p>You can write this as <code>self.absmax = max(self.absmax, self.relmax)</code></p>\n\n<pre><code> self.relmin = min(self.mem) \n if self.relmin &lt; self.absmin :\n self.absmin = self.relmin\n except TypeError:\n pass\n</code></pre>\n\n<p>Presumably you've done this to handle the None that you introduced because you used str2int. See how you only made things worse? Because a lot of things in Python throw TypeError, this is a really bad idea because you could catch a lot of errors you didn't mean to catch.</p>\n\n<p>Here's how I would structure your main loop to handle the invalid data</p>\n\n<pre><code>for data in serial_reader:\n try:\n value = int(data)\n except ValueError:\n pass # ignore invalid data\n else:\n rf(value)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T21:11:54.523", "Id": "17253", "Score": "0", "body": "I have been re-writing it and am trying out just using `if input != None:` which gets me out of using the `try / except` condition. - and also stops None going into the queue. (im also thinking about using deques (maxlen=2) for the min/max. To be honest I don't know how to `handle exceptions` - all I need is for it to keep running - which is why I thought letting it pass (and handling any `None`'s when they came along) would be the easiest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T03:57:30.717", "Id": "17257", "Score": "1", "body": "@user969617, I've added a bit at the end to show how I'd handle the reading loop." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T20:42:55.903", "Id": "10833", "ParentId": "10830", "Score": "2" } } ]
{ "AcceptedAnswerId": "10833", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T20:01:40.853", "Id": "10830", "Score": "1", "Tags": [ "python", "interval" ], "Title": "RangeFinder class" }
10830
<p>I need help refactoring the javascript. <a href="http://jsfiddle.net/BDLYP/" rel="nofollow">http://jsfiddle.net/BDLYP/</a></p> <p>I was able to hide and show fields, but I know this can be improved upon.</p> <p>If #state is empty, hide #high-schools and #other_high_schools</p> <p>If #state is picked, show #high-schools and show #other_high_schools (if #high-schools is empty)</p> <p>I imagine the multiple .live can be cut down. I am fairly new to javascript/jQuery</p> <pre><code>&lt;select name="state" id="state"&gt; &lt;option value=""&gt;&lt;/option&gt; &lt;option value="NY"&gt;NY&lt;/option&gt; &lt;option value="CA"&gt;CA&lt;/option&gt; &lt;/select&gt; &lt;div id="high-schools"&gt; &lt;select name="high_school_id" id="high_school"&gt; &lt;option value=""&gt;&lt;/option&gt; &lt;option value="1"&gt;Degrassi High&lt;/option&gt; &lt;option value="2"&gt;Bayside High&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div id="other_high_school"&gt; &lt;p&gt;Enter hs if your school is not listed above &lt;input type="text" name="other_high_school" id="other-hs-field" /&gt;&lt;/p&gt; &lt;/div&gt; ​ $(document).ready(function() { checkHighSchool(); $('#high_school').live('change', function() { checkHighSchool(); }); $('#state').live('change', function() { checkHighSchool(); }); }); function checkHighSchool() { var state = $("#state").val(); var high_school = $("#high_school").val(); if(state) { $("#high-schools").show(); } if(!state) { $("#other_high_school").hide(); $("#high-schools").hide(); $("#other-hs-field").val(''); //alert('no state selected'); } if(high_school &amp;&amp; state) { $("#other_high_school").hide(); $("#other-hs-field").val(''); } if(!high_school &amp;&amp; state) { $("#other_high_school").show(); } } </code></pre>
[]
[ { "body": "<p>I will give you a sample which is very simplified. I hope you can understand what I am doing here. </p>\n\n<p>HTML</p>\n\n<pre><code>&lt;select class=\"toggle-data\"&gt;\n &lt;option&gt;&lt;/option&gt;\n &lt;option value=\"1\" data-toggle=\"#foo-one\"&gt;foo one&lt;/option&gt;\n &lt;option value=\"2\" data-toggle=\"#foo-two\"&gt;foo two&lt;/option&gt;\n&lt;/select&gt;\n\n&lt;div id=\"foo-one\" style=\"display: none;\"&gt;\n foo one\n&lt;/div&gt;\n\n&lt;div id=\"foo-two\" style=\"display: none;\"&gt;\n foo two\n&lt;/div&gt;\n</code></pre>\n\n<p>​\nJS/jQuery</p>\n\n<pre><code>$('.toggle-data').on('change', function() {\n var toggle = this.options[this.selectedIndex].getAttribute('data-toggle'),\n toggle_class = 'unique_classname';\n $('.'+toggle_class+', '+toggle).toggle().removeClass(toggle_class);\n $(toggle).addClass(toggle_class);\n});\n​\n</code></pre>\n\n<p>Now you have a single function to do all of your show/hiding and you would just format you html accordingly. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T20:44:09.037", "Id": "10834", "ParentId": "10831", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T20:22:34.803", "Id": "10831", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "refactor javascript - show and hide fields based on current selection" }
10831
<p>I've decided to write a Chess engine in Ruby. The first step (before any move generation, AI, search trees, etc.) is to get a solid board representation so the computer and I can effectively communicate the game state to one another. The board representation I am using here is of the 64-bitstring variety. (I implemented one using 0x88 board rep'n too, but that isn't here. From what I understand, having a several representations on hand in memory will be most useful to solve various number-crunching issues that will appear along the way.)</p> <p>Please offer any advice on the beginnings of this Chess engine.</p> <pre><code>#!/usr/bin/env ruby ################################################# =begin A game of chess can be played in the terminal! User(s) must know the rules because the program knows none. Moves must be entered as "initial_square-terminal_square", where the squares must be given in algebraic chess notation and any whitespace is ok in that entered string. The program checks if initial square contains a piece of your color and if the termnal square does not. There are no other restrictions on piece movement. No saving, loading, undoing, etc. Game runs in an infinite loop, so quit with Ctrl-C. =end ################################################# class Integer # out: String = standard chessboard coordinates (e.g., "D4") # in: Fixnum = coordinates on the 8x16 board in memory def to_square if (0..63).to_a.include?(self) then square = String.new square &lt;&lt; ((self.to_i % 8) + "A".ord).chr square &lt;&lt; ((self.to_i/8).floor + 1).to_s end return square end # out: move "1" from init to term position and change init position to "0" # in: two cells def move(initial_cell,terminal_cell) return self - 2**initial_cell + 2**terminal_cell end # out: change "1" from given cell position to "0" # in: cell def remove(cell) return self - 2**cell end # convert 64bitstring to array of cells def to_cells cells_array = Array.new 0.upto(63) do |i| cells_array &lt;&lt; i if 2**i &amp; self &gt; 0 end return cells_array end end ################################################# class String # out: String = standard chessboard coordinates (e.g., "A3", "D4") # in: Fixnum = virtual cell location (e.g., 0,19,51,... ) def to_cell # check if in standard form return nil if self.length!= 2 rank = self[0].upcase file = self[1] cell = file.to_i*8 + (rank.ord - 65) - 8 return cell end end ################################################# class Game # setup the game. its attributes are the pieces in game, access white pawns with "&lt;game_name&gt;.whitePawns" attr_accessor :whitePawns, :whiteKnights, :whiteBishops, :whiteRooks, :whiteQueens, :whiteKing, :blackPawns, :blackKnights, :blackBishops, :blackRooks, :blackQueens, :blackKing, :whitePieces, :blackPieces, :whiteCastled, :blackCastled, :whitesMove # initialize game, i.e., define initial piece locations def initialize # assign white pieces' cells @whitePawns = 0b0000000000000000000000000000000000000000000000001111111100000000 @whiteKnights = 0b0000000000000000000000000000000000000000000000000000000001000010 @whiteBishops = 0b0000000000000000000000000000000000000000000000000000000000100100 @whiteRooks = 0b0000000000000000000000000000000000000000000000000000000010000001 @whiteQueens = 0b0000000000000000000000000000000000000000000000000000000000010000 @whiteKing = 0b0000000000000000000000000000000000000000000000000000000000001000 # assign black pieces' cells @blackPawns = 0b0000000011111111000000000000000000000000000000000000000000000000 @blackKnights = 0b0100001000000000000000000000000000000000000000000000000000000000 @blackBishops = 0b0010010000000000000000000000000000000000000000000000000000000000 @blackRooks = 0b1000000100000000000000000000000000000000000000000000000000000000 @blackQueens = 0b0001000000000000000000000000000000000000000000000000000000000000 @blackKing = 0b0000100000000000000000000000000000000000000000000000000000000000 # game control flags @whitesMove = true @whiteCastled = false @blackCastles = false end def board @board = Array.new 0.upto(63) do |i| @board[i] = nil end 0.upto(63) do |i| bit_compare = 2**i @board[i] = "P" if @whitePawns &amp; bit_compare != 0 @board[i] = "N" if @whiteKnights &amp; bit_compare != 0 @board[i] = "B" if @whiteBishops &amp; bit_compare != 0 @board[i] = "R" if @whiteRooks &amp; bit_compare != 0 @board[i] = "Q" if @whiteQueens &amp; bit_compare != 0 @board[i] = "K" if @whiteKing &amp; bit_compare != 0 @board[i] = "p" if @blackPawns &amp; bit_compare != 0 @board[i] = "n" if @blackKnights &amp; bit_compare != 0 @board[i] = "b" if @blackBishops &amp; bit_compare != 0 @board[i] = "r" if @blackRooks &amp; bit_compare != 0 @board[i] = "q" if @blackQueens &amp; bit_compare != 0 @board[i] = "k" if @blackKing &amp; bit_compare != 0 end return @board end # change: piece bitstrings according to move # in: String, String = squares to move from and to def make_move(initial_cell,terminal_cell) # find and alter captured piece's (if any) bitstring instance_variables.select{ |var| var =~ /Pawns|Knights|Bishops|Rooks|Queens|King/ }.each do |var| if opponentsPieces &amp; 2**terminal_cell &gt; 0 then instance_variables.select{ |var2| var2 =~ /Pawns|Knights|Bishops|Rooks|Queens|King/ }.each do |opp_var| if 2**terminal_cell &amp; instance_variable_get(opp_var) &gt; 0 instance_variable_set(opp_var,instance_variable_get(opp_var).remove(terminal_cell)) end end end end # find and alter moving piece's bitstring instance_variables.select{ |var| var =~ /Pawns|Knights|Bishops|Rooks|Queens|King/ }.each do |var| if 2**initial_cell &amp; instance_variable_get(var) &gt; 0 instance_variable_set(var,instance_variable_get(var).move(initial_cell,terminal_cell)) end end end # out; bitstring of white piece locations def whitePieces return @whitePawns | @whiteKnights | @whiteBishops | @whiteRooks | @whiteQueens | @whiteKing end # out; bitstring of black piece locations def blackPieces return @blackPawns | @blackKnights | @blackBishops | @blackRooks | @blackQueens | @blackKing end # out: bitstring of pieces belonging to the moving color def moversPieces case @whitesMove when true then return whitePieces when false then return blackPieces end end # out: bitstring of pieces belonging to not the moving color def opponentsPieces case @whitesMove when true then return blackPieces when false then return whitePieces end end # heyy, can i move a piece to this terminal cell? # out: Boolean = true if mover's play terminates in a cell not containing a friendly piece # in: Fixnum = terminal cell in 0..63 def legal_move?(terminal_cell) return 2**terminal_cell &amp; movers_pieces == 0 end def save_state end # output current state or game board to terminal def display system('clear') puts # show board with pieces print "\t\tA\tB\tC\tD\tE\tF\tG\tH\n\n" print "\t +", " ----- +"*8,"\n\n" 8.downto(1) do |rank| print "\t#{rank} |\t" 'A'.upto('H') do |file| if board["#{file}#{rank}".to_cell] then piece = board["#{file}#{rank}".to_cell] else piece = " " end print "#{piece} |\t" end print "#{rank}\n\n\t +", " ----- +"*8,"\n\n" end print "\t\tA\tB\tC\tD\tE\tF\tG\tH" puts "\n\n" # show occupancy print " White occupancy: " puts whitePieces.to_cells.map{ |cell| cell.to_square}.join(", ") print " Black occupancy: " puts blackPieces.to_cells.map{ |cell| cell.to_square}.join(", ") puts # show whose move it is case @whitesMove when true puts " WHITE to move." when false puts " BLACK to move." end puts end def play until false do # show board display # request move initial_cell, terminal_cell = nil until !initial_cell.nil? &amp; !terminal_cell.nil? do print " enter move : " # get move in D2-D4 format; break apart into array by "-" and remove any whitespace in each piece user_input = gets.strip.upcase.delete(' ') # if string entered is something like "A4-C5" or " a4 -C5 " etc if user_input =~ /[A-H][1-8]-[A-H][1-8]/ user_move = user_input.split("-").map { |cell| cell.strip } # if initial square contains one of your pieces &amp; terminal square does not if ((2**user_move[0].to_cell &amp; moversPieces) &gt; 0) &amp; ((2**user_move[1].to_cell &amp; ~moversPieces) &gt; 0) then initial_cell, terminal_cell = user_move[0].to_cell, user_move[1].to_cell end end end make_move(initial_cell,terminal_cell) @whitesMove = !@whitesMove end end end ################################################# ################################################# ################################################# game = Game.new game.play ################################################# #################### fin ######################## ################################################# </code></pre>
[]
[ { "body": "<p>I would separate logic from presentation and I would write unit tests from begin on.</p>\n\n<p>I would split <code>display</code> in two methods:</p>\n\n<ul>\n<li><code>build_board</code> is creating a String or an Array</li>\n<li><code>display</code> writes the result of <code>build_board</code></li>\n</ul>\n\n<p>Advantage:\nYou can write unit tests: </p>\n\n<ul>\n<li>Check the result of <code>build_board</code></li>\n<li>make a move</li>\n<li>check again the result of <code>build_board</code>.</li>\n</ul>\n\n<p>I made a modified version of <code>play</code>:</p>\n\n<pre><code>def play\n\n user_input = nil\n while true do\n # show board\n display\n # request move\n initial_cell, terminal_cell = nil\n until ! initial_cell.nil? &amp; !terminal_cell.nil? do\n print \" enter move : \"\n # get move in D2-D4 format; break apart into array by \"-\" and remove any whitespace in each piece\n user_input = gets.strip.upcase.delete(' ')\n #Check user input\n case user_input \n # if string entered is something like \"A4-C5\" or \" a4 -C5 \" etc\n when /[A-H][1-8]-[A-H][1-8]/\n user_move = user_input.split(\"-\").map { |cell| cell.strip }\n # if initial square contains one of your pieces &amp; terminal square does not\n if ((2**user_move[0].to_cell &amp; moversPieces) &gt; 0) &amp; ((2**user_move[1].to_cell &amp; ~moversPieces) &gt; 0)\n initial_cell, terminal_cell = user_move[0].to_cell, user_move[1].to_cell\n end\n when 'SAVE' #store\n puts \"Store not implemented yet\"\n next\n when 'END' #stop the game\n puts \"Thanks for playing\"\n exit\n else\n puts 'Invalid move. Please use ...' ##Add short description of usage ###\n next\n end #case user_input\n end\n case make_move(initial_cell,terminal_cell)\n when true\n @whitesMove = !@whitesMove\n when :empty_field\n puts \"Start field was empty - please redo\"\n else\n puts \"Move not done - please redo\"\n end\n end\nend\n</code></pre>\n\n<p>This <code>play</code> offers the possibility to add more commands (I prepared END and SAVE).</p>\n\n<p>Very important: Give a response if there is a problem</p>\n\n<p><code>make_move</code> should return a result. <code>true</code>if it is ok, in other cases provide an error code.\nSo the player can get a response and you have the possibility to test the function in your unittest (make an invalid move and check if the error code is correct).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T15:34:01.670", "Id": "17272", "Score": "0", "body": "great, thanks for the advice. i have begun separating logic from presentation. i am realizing now that this has always been something i've struggled with.\n\nquestion: i am not familiar with using :empty_field, when would that last case statement evaluate to :empty_field?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T17:54:39.513", "Id": "17279", "Score": "0", "body": "Never ;) It was just a idea, what you could do. Imagine you call `make_move` and the method detect, that you start from an empty field, then you could `return :empty_field`. When you detect, that the figure has the wrong color, you may return `:wrong_color`... Depending on the return code, you can inform the player, why the move is invalid." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T18:07:28.483", "Id": "17280", "Score": "0", "body": "ohh, i see what you're saying now. good idea, thank you." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T21:21:43.247", "Id": "10836", "ParentId": "10832", "Score": "4" } }, { "body": "<p>I don't think using bit arithmetic will give you any performance advantages in ruby in the long run (still <code>1&lt;&lt;i</code> will be faster than <code>2**i</code> though). Just compare</p>\n\n<pre><code>0b0000000000000000000000000000000000000000000000001111111100000000.class\n</code></pre>\n\n<p>with</p>\n\n<pre><code>0b1000000100000000000000000000000000000000000000000000000000000000.class\n</code></pre>\n\n<p>While the former is a Fixnum, the latter is a Bignum. So in the end Ruby can't use primitive types for these arithmetics anyway and has to do all kinds of conversions in the background. It's probably best to store all pieces in a simple 64 field Array.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T09:21:26.940", "Id": "30424", "ParentId": "10832", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T20:36:20.057", "Id": "10832", "Score": "4", "Tags": [ "beginner", "ruby", "chess" ], "Title": "Chess engine in Ruby" }
10832
<p>I have this search script on my page which search through the displayed table. The table is displayed with PHP from a database. It is actually a list, and this list is sorted out alphabetically with the help of hyperlinks of A to Z. Now I need to search the whole database instead of displayed ones. Any helps or resources would be helpful. :)</p> <pre><code>$(document).ready(function() { $("#search").keyup(function() { if($(this).val() != "") { $("#some_table tbody&gt;tr").hide(); $("#some_table td:contains-ci('" + $(this).val() + "')").parent("tr").show(); } else { $("#some_table tbody&gt;tr").show(); } }); }); $.extend($.expr[":"], { "contains-ci" : function(elem, i, match, array) { return (elem.textContent || elem.innerText || $(elem).text() || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) &gt;= 0; } }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T04:12:35.173", "Id": "17259", "Score": "0", "body": "It seems like you are looking for someone to write some code for you rather than receive a review of what you have written. Code Review is for working code (it is not the right place for this sort of question). Also, your question is vague and unanswerable in its current form regardless of where it is posted." } ]
[ { "body": "<p>I am doing a review of the code, not answering your question which should be on stackoverflow and not codereview.</p>\n\n<pre><code>//$( function(){} ) is a short cut for ready!\n$(function() {\n //No reason to keep looking this up on every keypress, store it once and reuse\n var tableRows = $(\"#some_table tbody&gt;tr\");\n $(\"#search\").keyup(\n function() { \n //Grab the value and remember it so we do not have to look up again\n var value = $(this).value; \n if ( value.length &gt; 0) {\n //Chain the selectors, the tds live inside the rows so just do a find based on that starting point\n tableRows.hide().find(\"td:contains-ci('\" + value + \"')\").parent(\"tr\").show();\n } else {\n tableRows.show();\n }\n }\n );\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T19:00:52.143", "Id": "10874", "ParentId": "10837", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T21:29:40.660", "Id": "10837", "Score": "-2", "Tags": [ "javascript", "php", "jquery", "mysql" ], "Title": "How can I improve my search script?" }
10837
<p>I have a model that I've created in Codeigniter to represent a vote. The purpose of the site that it's a part of is to allow users to vote on their preferred pronunciation for a given word.</p> <p>The routine first checks to see if a user has registered a vote for the given pronunciation and if so, whether it was up or down. Just like the stackexchange network sites, you can only vote either up or down for a given entry and you can only vote once in either direction. Am I doing this wrong? Is there a simpler way to accomplish what I'm trying to do here (such as adding a method or two)? If there's anything else that you'd like to see that I haven't posted, let me know.</p> <pre><code>public function vote($pronun_id, $user_id, $direction) { $data = array( 'pronun_id' =&gt; $pronun_id, 'user_id' =&gt; $user_id, 'direction' =&gt; $direction ); $already_voted = $this-&gt;_vote_exists($pronun_id, $user_id); if($already_voted == 'up') { if($direction == 'up') { return false; } else { $this-&gt;db-&gt;where(array('user_id' =&gt; $user_id, 'pronun_id' =&gt; $pronun_id)); $this-&gt;db-&gt;update('vote', array('direction' =&gt; $direction)); return true; } } elseif($already_voted == 'down') { if($direction == 'down') { return false; } else { $this-&gt;db-&gt;where(array('user_id' =&gt; $user_id, 'pronun_id' =&gt; $pronun_id)); $this-&gt;db-&gt;update('vote', array('direction' =&gt; $direction)); return true; } } else { $this-&gt;db-&gt;insert('vote', $data); return true; } } private function _vote_exists($pronun_id, $user_id) { $data = $data = array( 'pronun_id' =&gt; $pronun_id, 'user_id' =&gt; $user_id ); $query = $this-&gt;db-&gt;get_where('vote', $data); if($query-&gt;num_rows() &gt; 0) { $row = $query-&gt;row_array(); return $row['direction']; } else { return false; } } </code></pre> <p><strong>Update:</strong> Also, I'm very new to Codeigniter, so please feel free to be brutal about anything here. I'm not the best programmer and I also just don't know Codeigniter "style" yet, so either of those may be issues here.</p>
[]
[ { "body": "<p>You have some cut and pasted code which can be re-factored by comparing already_voted with the direction rather than with 'up' and 'down' specifically.</p>\n\n<pre><code>if ($already_voted === false) {\n $this-&gt;db-&gt;insert('vote', $data);\n return true;\n}\nelseif ($already_voted == $direction) {\n return false;\n}\nelse {\n $this-&gt;db-&gt;where(array('user_id' =&gt; $user_id, 'pronun_id' =&gt; $pronun_id));\n $this-&gt;db-&gt;update('vote', array('direction' =&gt; $direction));\n return true;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T16:05:19.620", "Id": "17273", "Score": "0", "body": "Thanks. I knew that was kind of clunky but I can't believe I didn't think of this solution." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T04:05:17.273", "Id": "10845", "ParentId": "10840", "Score": "1" } } ]
{ "AcceptedAnswerId": "10845", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T01:22:27.560", "Id": "10840", "Score": "1", "Tags": [ "php", "codeigniter" ], "Title": "Codeigniter vote routine review" }
10840
<p>I am trying to learn <a href="http://en.wikipedia.org/wiki/Prolog" rel="nofollow">Prolog</a>, and wrote a bibtex reader using GNU Prolog. </p> <p>I would like some feedback on my code in terms of: the way I write Prolog, and how it can be improved. </p> <p><a href="https://gist.github.com/2357257" rel="nofollow">Gist</a></p> <pre><code>% CLI for interacting with a bibtex db. % Enter your bibtex file to .bib.db % i.e cat wang.bib &gt; .db.bib % -------------------------------------------- i(K,V, bibentry(Type, Key, Entries)):- bibentry(Type, Key, Entries), member(i(K,V), Entries). read_txt(FName, Txt) :- open(FName, read, File), read_file(File, Txt), close(File). read_file(Stream, []) :- at_end_of_stream(Stream). read_file(Stream, [X|L]) :- \+ at_end_of_stream(Stream), get_code(Stream, X), read_file(Stream, L). % ============================================================ % DCG support. % ============================================================ isalpha(Ch) :- Ch &gt;= 0'a, Ch =&lt; 0'z -&gt; true ; Ch &gt;= 0'A, Ch =&lt; 0'Z -&gt; true. isdigit(Ch) :- 0'0 =&lt; Ch, Ch =&lt; 0'9. ispunct(Ch) :- Ch &gt;= 0'!, Ch =&lt; 0'@ -&gt; true ; Ch &gt;= 0'{, Ch =&lt; 0'~ -&gt; true. islchar(Ch) :- Ch = 0'_ ; Ch = 0'. ; Ch = 0'- ; Ch = 0'+ . not_brace(Ch) :- Ch =\= 0'{, Ch =\= 0'}. not_quote(Ch) :- Ch =\= 0'". tilleol(L) --&gt; tilleol([], L). tilleol(L0, L) --&gt; [Char], { Char =\= 13 ; Char =\= 10 }, { L1 = [Char|L0] }, (tilleol(L1, L) ; {reverse(L1, L)}). % TODO : Collapse all the three into a single function digits(N) --&gt; digits(0, N). digits(N0, N) --&gt; % N0 is number already read [Char], {isdigit(Char)}, { N1 is N0 * 10 + (Char - 0'0) }, ( digits(N1, N) ; { N = N1 }). letters(L) --&gt; letters([], L). letters(L0, L) --&gt; [Char], { isalpha(Char) }, {L1 = [Char|L0] }, (letters(L1, L) ; {reverse(L1, L)}). alphanum(L) --&gt; alphanum([], L). alphanum(L0, L) --&gt; [Char], {isalpha(Char) ; isdigit(Char)}, {L1 = [Char|L0] }, (alphanum(L1, L) ; {reverse(L1, L) }). alphanum_a(L) --&gt; alphanum(LC),{atom_codes(L, LC)}. punctanum(L) --&gt; punctanum([], L). punctanum(L0, L) --&gt; [Char], {isalpha(Char) ; isdigit(Char) ; ispunct(Char)}, {L1 = [Char|L0] }, (punctanum(L1, L) ; {reverse(L1, L) }). wordanum(L) --&gt; wordanum([], L). wordanum(L0, L) --&gt; [Char], {isalpha(Char) ; isdigit(Char) ; islchar(Char)}, {L1 = [Char|L0] }, (wordanum(L1, L) ; {reverse(L1, L) }). % Just consume spaces s1_ --&gt; (" ";"\n" ; "\t"), s_. s_ --&gt; s1_ ; "". any_case(XX) --&gt; [X], { char_code(C, X), lower_upper(CC, C), char_code(CC, XX)}. i_([]) --&gt; []. i_([C|Cs]) --&gt; any_case(C), i_(Cs). % ============================================================ % Now the bibtex parser. % ============================================================ parse_txt([]). parse_txt(Txt) :- phrase(bibs(Bibs), Txt), apply(Bibs). apply([Bib|Bibs]) :- asserta(Bib), apply(Bibs). apply([]). bibs([Bib | Bibs]) --&gt; s_, bib(Bib), s_, bibs(Bibs). bibs([]) --&gt; []. bib(Bib) --&gt; ( bib_comment(Bib) ; bib_preamble(Bib) ; bib_string(Bib) ; bib_entry(Bib) ). bib_entry(bibentry(Type, Name, Keys)) --&gt; "@", bib_type(Type), "{", s_, bib_name(Name), s_, ",", {!}, s_, bib_keys(Keys), s_, "}", s_. bib_comment(bibentry(comment,comment, [i(key,Val)])) --&gt; "@", i_("comment"), bib_braces(Val), s_. bib_preamble(bibentry(preamble,preamble, [i(key,Val)])) --&gt; "@", i_("preamble"), bib_braces(Val), s_. bib_string(bibentry(string, K, [i(key,K),i(val,V)])) --&gt; "@", i_("string"), ("{", s_, bib_keys([i(K,V)]), s_, "}" ; "(", s_, bib_keys([i(K,V)]), s_, ")"), s_. bib_type(Type) --&gt; wordanum(TypeC), {atom_codes(Type, TypeC)}. bib_name(Name) --&gt; wordanum(NameC), {atom_codes(Name, NameC)}. bib_keys([Pair | Rest]) --&gt; bib_kv(Pair), s_, bib_keys(Rest). bib_keys([]) --&gt; []. bib_kv(i(Key,Val)) --&gt; bib_key(Key), s_, "=", s_, bib_value(Val), s_, ((",",{!}) ; ""). % we have a !cut here so that once a pair is parsed, we should not go back % there are no possible circumstances in bibtex which would require it. bib_key(Key) --&gt; wordanum(KeyC), {atom_codes(Key, KeyC)}. bib_value(Val) --&gt;(bib_braces(V1) ; bib_quotes(V1) ; bib_word(V1)), s_, "#", s_, bib_value(V2), {list(V2) -&gt; Val = [V1|V2] ; [V1,V2] = Val}. % TODO, fetch from string db bib_value(Val) --&gt; bib_word(Val). bib_value(Val) --&gt; bib_braces(Val). bib_value(Val) --&gt; bib_quotes(Val). bib_word(word(Val)) --&gt; wordanum(ValC), {atom_codes(Val, ValC)}. bib_braces(Val) --&gt; parse_brace(ValC), {atom_codes(Val, ValC)}. bib_quotes(Val) --&gt; parse_quote(ValC), {atom_codes(Val, ValC)}. % Use the below if the string parens are required (to know what kind of string it was) % parse_brace(Val) --&gt; "{", parse_bstring(ValS), "}", {append( [0'{| ValS], "}", Val)}. parse_brace(Val) --&gt; "{", parse_bstring(Val), "}". parse_bstring([0'\\| [Char|Val]] ) --&gt; "\\", [Char], parse_bstring(Val). parse_bstring([Char|Val]) --&gt; [Char], {not_brace(Char)}, parse_bstring(Val). parse_bstring(Val) --&gt; parse_brace(ValA), parse_bstring(ValB), {append(ValA, ValB, Val)}. parse_bstring([]) --&gt; []. % Use the below if the string parens are required (to know what kind of string it was) % parse_quote(Val) --&gt; "\"", parse_qstring(ValS), "\"", {append( [0'"| ValS], "\"", Val)}. parse_quote(Val) --&gt; "\"", parse_qstring(Val), "\"". % Warning escaped Quote parse_qstring([0'\\| [Char|Val]] ) --&gt; "\\", [Char], parse_qstring(Val). parse_qstring(Val) --&gt; parse_brace(V), parse_qstring(U), {append(V, U, Val)}. parse_qstring([Char|Val]) --&gt; [Char], {not_quote(Char)}, parse_qstring(Val). parse_qstring([]) --&gt; []. %-------------------------------------------------------- % Some colour %-------------------------------------------------------- c_red(Str) :- write('[0;31m'), write(Str),write('[0m'). c_green(Str) :- write('[0;32m'), write(Str),write('[0m'). c_yellow(Str) :- write('[0;33m'), write(Str),write('[0m'). c_byellow(Str):- write('[1;33m'), write(Str),write('[0m'). c_blue(Str) :- write('[0;34m'), write(Str),write('[0m'). c_magenta(Str):- write('[0;35m'), write(Str),write('[0m'). c_cyan(Str) :- write('[0;36m'), write(Str),write('[0m'). c_white(Str) :- write('[0;37m'), write(Str),write('[0m'). c_start(red) :- write('[0;31m'). c_start(green) :- write('[0;32m'). c_start(yellow):- write('[0;33m'). c_start(byellow):- write('[1;33m'). c_start(blue):- write('[0;34m'). c_start(magenta):- write('[0;35m'). c_start(cyan):- write('[0;36m'). c_start(_):- write('[0;37m'). c_end :- write('[0m'). %-------------------------------------------------------- % Load bibtex files %-------------------------------------------------------- load_bib(File) :- read_txt(File, Txt), parse_txt(Txt). %-------------------------------------------------------- read_line(Codes) :- get0(Code), ( Code &lt; 0 /* end of file */ -&gt; Codes = "exit" ; Code =:= 10 /* end of line */ -&gt; Codes = [] ; Codes = [Code|Codes1], read_line(Codes1) ). %-------------------------------------------------------- % Read User Commands %-------------------------------------------------------- parse_line(Line, Cmd) :- phrase(read_command(Cmd), Line) ; Cmd = unknown. read_kv(pair(Key, Value)) --&gt; alphanum_a(Key), s_, ":", s_, alphanum_a(Value). read_kv(pair(Key, Value)) --&gt; alphanum_a(Key), s_, ":", s_, {atom_codes(Value,"")}. read_kv(has(Key, Value)) --&gt; alphanum_a(Key), s_, "~", s_, alphanum_a(Value). read_kv(has(Key, Value)) --&gt; alphanum_a(Key), s_, "~", s_, {atom_codes(Value,"")}. read_kv(ne(Key, Value)) --&gt; alphanum_a(Key), s_, "!", s_, alphanum_a(Value). read_kv(gt(Key, Value)) --&gt; alphanum_a(Key), s_, "&gt;", s_, alphanum_a(Value). read_kv(lt(Key, Value)) --&gt; alphanum_a(Key), s_, "&lt;", s_, alphanum_a(Value). read_kv(ge(Key, Value)) --&gt; alphanum_a(Key), s_, "&gt;=", s_, alphanum_a(Value). read_kv(le(Key, Value)) --&gt; alphanum_a(Key), s_, "&lt;=", s_, alphanum_a(Value). read_command(exit) --&gt; "exit". read_command(help) --&gt; "help". read_command(show(V)) --&gt; "show", s_, alphanum_a(V), s_. read_command(colour(K,V)) --&gt; ("colour" ; "color"), s_, alphanum_a(K), s_, alphanum_a(V), s_. read_command(no) --&gt; s_. read_command(or(P1, P2)) --&gt; s_, read_expr(P1), s_, ";", s_, read_command(P2), s_. read_command(and(P1, P2)) --&gt; s_, read_expr(P1), s_, ",", s_, read_command(P2), s_. read_command(P) --&gt; s_, read_expr(P), s_. read_command(no) --&gt; []. read_expr(Pair) --&gt; read_kv(Pair). read_expr(E) --&gt; "(", read_command(E), ")". read_expr(all(V)) --&gt; s_, "*", alphanum_a(V), s_. read_expr(all('')) --&gt; s_, "*", s_. %-------------------------------------------------------- % Some libraries %-------------------------------------------------------- awrite([L|Ls]) :- print(L), nl, awrite(Ls). awrite([]). portray(bibentry(comment,Key,[i(key, Entry)])) :- c_green('&gt;'), write(' '), c_green(Entry). portray(bibentry(preamble,Key,[i(key,Key),i(val,Entry)])):- c_blue('*&gt;'), write(' '), c_yellow(Entry). portray(bibentry(string,Key,[i(key,Key), i(val,Entry)])):- c_yellow(Key), write(' = '), print(Entry). portray(bibentry(Type,Key,Entries)) :- opt(show,prolog), write('bibentry('), c_blue(Type), write(', '), c_yellow(Key),write(','), nl, write('['),nl, awrite(Entries), write(']'),nl, write(')'), nl. portray(bibentry(Type,Key,Entries)) :- opt(show,bib), write('@'),c_blue(Type), write('{'), c_yellow(Key),write(','), nl, awrite(Entries), write('}'), nl. portray(bibentry(Type,Key,Entries)) :- c_blue(Type), write(' '), c_yellow(Key), nl, awrite(Entries), nl. portray(i(K,V)) :- opt(show,prolog), write(' '),write('i('), print(key(K)), write(', '), wvals(V), write('),'). portray(i(K,V)) :- opt(show,bib), write(' '), print(key(K)), c_blue('= '), write('{'), wvals(V), write('},'). portray(i(K,V)) :- write(' '), print(key(K)), c_blue(': '), wvals(V). portray(key(K)) :- mycolour(K,V), c_start(V), (opt(show,prolog) -&gt; write(K) ; format('~15a', [K])), c_end. portray(key(K)) :- (opt(show,prolog) -&gt; write(K) ; format('~15a', [K])). portray(word(K)) :- opt(show,prolog), write('word('),print(K),write(')'). % String substitution happens here. portray(word(K)) :- bibentry(string, K, [_,i(val,V)]), print(V). wvals([V|Vs]) :- print(V), wvals(Vs). wvals([]). wvals(V) :- opt(show,prolog),write('\''), print(V), write('\''). wvals(V) :- print(V). ulcaseatom(L, U) :- atom_chars(L, Ls), ulcase(Ls, Us), atom_chars(U, Us). % !!!! this is dependent on sequence. ulcase([L|Ls], [U|Us]) :- lower_upper(L, U), ulcase(Ls, Us). ulcase([], []). %-------------------------------------------------------- find_num(K,V, N, V1, N1, Res) :- atom_codes(V, V1), phrase(digits(N), V1), i(K,Vi, Res), atom_codes(Vi, Vi1), phrase(digits(N1), Vi1). process_cmd(unknown) :- write('*'), nl. process_cmd(help) :- write('COMMANDS'),nl, tab(1),write('help'),nl, tab(1),write('colour &lt;key&gt; &lt;value&gt;'),nl, tab(2),write(' e.g: colour title red'),nl, tab(1),write('*'),nl, tab(1),write('*&lt;type&gt;'),nl, tab(2),write(' e.g: *article'),nl, tab(1),write('*show &lt;bib|prolog|format&gt;'),nl, tab(2),write(' e.g: show bib'),nl. process_cmd(show(V)) :- retractall(opt(show,_)), assertz(opt(show,V)). process_cmd(colour(K,V)) :- assertz(mycolour(K,V)). process_cmd(E) :- setof(Res, process_expr(E, Res), ResL), awrite(ResL), nl. process_expr(all(V), Res) :- (V = '' -&gt; (bibentry(X,Key,R), Res = bibentry(X, Key, R)) ; (bibentry(V,Key,R), Res = bibentry(V, Key, R)) ). process_expr(pair(K,V), Res) :- i(K,V, Res). process_expr(gt(K,V), Res) :- find_num(K,V,N,V1,N1, Res), N1 #&gt;# N, fd_domain([N,N1],1,10000). process_expr(lt(K,V), Res) :- find_num(K,V,N,V1,N1, Res), N1 #&lt;# N, fd_domain([N,N1],1,10000). process_expr(ge(K,V), Res) :- find_num(K,V,N,V1,N1, Res), N1 #&gt;=# N, fd_domain([N,N1],1,10000). process_expr(le(K,V), Res) :- find_num(K,V,N,V1,N1, Res), N1 #=&lt;# N, fd_domain([N,N1],1,10000). process_expr(ne(K,V), Res) :- i(K,V1, Res), V \= V1. process_expr(has(K,V), Res) :- i(K,V1, Res), ulcaseatom(V1, V2), ulcaseatom(V, Vi), sub_atom(V2, _, _, _, Vi). process_expr(or(E1,E2), Res) :- process_expr(E1, Res) ; process_expr(E2, Res). process_expr(and(E1,E2), Res) :- process_expr(E1, Res), process_expr(E2, Res). %-------------------------------------------------------- % Standard Incantation for a REPL %-------------------------------------------------------- do_command :- write('bib&gt; '), read_line(Line),!, parse_line(Line, Cmd), ( Cmd = exit; %halt ; Cmd = no, do_command ; process_cmd(Cmd), do_command ). main :- load_bib('.db.bib'), do_command. :- dynamic([bibentry/3, opt/2, mycolour/2]). :- initialization(main). </code></pre>
[]
[ { "body": "<p>Quite nice! A few comments: First of all, consider using SWI-Prolog because it has more extensive libraries that you can use. In particular, consider using SWI's <a href=\"http://www.swi-prolog.org/pldoc/doc_for?object=section%282,%27A.19%27,swi%28%27/doc/Manual/pio.html%27%29%29\" rel=\"nofollow\">library(pio)</a> to process files. Pure input lets you write DCGs and then transparently apply them to files, which leads to more declarative and more convenient solutions. Instead of isalpha/1 etc., consider using SWI's <code>code_type/2</code>. Also consider using <code>format/2</code> for output. For example, instead of:</p>\n\n<pre><code>c_red(Str) :- write('[0;31m'), write(Str), write('[0m').\n</code></pre>\n\n<p>You can write:</p>\n\n<pre><code>c_red(Str) :- format(\"[0;31m~w[0m\", [Str]).\n</code></pre>\n\n<p>Finite domain constraints are available in SWI-Prolog with library(clpfd).</p>\n\n<p><strong>Edit</strong>:</p>\n\n<p>In addition, consider using DCGs also for string generation. This could be useful for your portray/1 predicate: You could describe the output string with a DCG, and use a single format/2 or write/1 call to print the resulting string instead of using several intermixed write calls. The advantage is that it is much easier to test pure predicates than predicates involving low-level output. You can easily write test cases for them etc. The code would also be shorter. In general, it is good practice to separate pure code from impure code. DCGs are often a good fit when describing lists also in other cases.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T18:34:10.113", "Id": "17417", "Score": "0", "body": "I was able to use your suggestion and reduce the duplication in coloring code. \n\n color(red, '[0;31m'). \n c_show(C,Str) :- color(C,Col), color(end,End), format(\"~w~w~w\", [Col,Str,End]). \n c_start(C) :- color(C,Col), write(Col). \n\nI will check out SWI Prolog (Help, my markdown is not working as I expected.)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T08:59:26.950", "Id": "10950", "ParentId": "10842", "Score": "2" } } ]
{ "AcceptedAnswerId": "10950", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T01:39:04.260", "Id": "10842", "Score": "1", "Tags": [ "parsing", "prolog" ], "Title": "Bibtex reader using Prolog" }
10842
<p>Take 4 (alteration based on feedback from Rainer Joswig):</p> <pre><code>(defmacro with-gensyms ((&amp;rest names) &amp;body body) `(let ,(loop for n in names collect `(,n (gensym))) ,@body)) (defmacro let-alist ((&amp;rest lookups) alist &amp;body body) (with-gensyms (alist-form) `(let ((,alist-form ,alist)) (let ,(loop for l in lookups if (keywordp l) collect `(,(intern (symbol-name l)) (cdr (assoc ,l ,alist-form))) else collect `(,l (cdr (assoc ',l ,alist-form)))) ,@body)))) </code></pre> <p>This revision can still be used the same way</p> <pre><code>&gt; (defparameter test '((|foo| . 1) (:bar . 2) (baz . 3))) TEST &gt; (let-alist (:bar |foo| baz) test (list |foo| bar baz)) (1 2 3) </code></pre> <p>but the macro only expands the passed-in <code>alist</code> form once. The following is the output of <code>slime-macroexpand-1</code>:</p> <pre><code>(LET ((#:G1299 TEST)) (LET ((BAR (CDR (ASSOC :BAR #:G1299))) (|foo| (CDR (ASSOC '|foo| #:G1299))) (BAZ (CDR (ASSOC 'BAZ #:G1299)))) (LIST |foo| BAR BAZ))) </code></pre> <p>All comments welcome, but specifically (in order of descending importance),</p> <ul> <li>Can you think of a good docstring?</li> <li>Can you think of a situation wherein this would explode?</li> <li>Is there a built-in macro that does the same thing, or close to it?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T04:00:10.607", "Id": "17258", "Score": "0", "body": "Wow, that is remarkably similar (in concept, not in implementation) to [my `let-with` macro](http://codereview.stackexchange.com/questions/1398/is-this-a-good-way-to-implement-let-with). :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T06:01:23.243", "Id": "17261", "Score": "0", "body": "@ChrisJester-Young - Quite similar. The difference is that this is CL rather than Scheme (though I can't see that a lack of hygienic macros would kneecap me in this situation), and I have to cover one case other than a symbol key. Any idea for how I would effectively document this then, or are you of the mind that it's self-explanatory?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T06:08:21.133", "Id": "17303", "Score": "0", "body": "I prefer the let-alist style syntax, because it has similar syntactic structure to with-slots. Here, the alist is the object, and the keys are the slots. One addition I'd suggest: Make it so that (let-alist (sym1 sym2 sym3) alist ...) compiles. That is, if an element in the symbol/lookup pairs list isn't a list, use the same symbol for the let binding and the alist lookup. This would be the standard more common case I would think; then you can add the paired list if you want to make those two values different. Basically, give it a with-slots syntax and feel." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T06:12:58.303", "Id": "17304", "Score": "0", "body": "Oh, and another way to implement the binding is with macrolet. This would mean that the lookup is done separately every time the binding is found in body, and that may or may not be what you really want; just wanted to mention that this is another option." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T06:44:31.760", "Id": "17305", "Score": "0", "body": "And if you use macrolet instead of let, you may also get the ability to setf the binding for free (i.e., read and write on the binding). If not for free, you'll probably just have to write a single defsetf function. Generalized variables; macrolet; IMO all worthwhile things to look into." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T06:52:12.903", "Id": "17306", "Score": "0", "body": "My mistake; by macrolet, I meant symbol-macrolet. That one should be more appropriate for this situation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T13:26:03.530", "Id": "17318", "Score": "0", "body": "@claytontstanley - you sure you don't want to submit an answer with that insight? :) The reason I didn't just do the single flat-list style of binding (as in `with-slots` is that I want to cover the case where the alist key is a `keyword` symbol. In that case, the lookup symbol and the binding symbol must be different. I suppose what I could do is just ask for the lookup symbols and have the macro bind to `(intern (symbol-name [keyword]))` ..." } ]
[ { "body": "<p>The main problem with it is <code>alist</code>- the variable of the macro.</p>\n\n<pre><code>CL-USER &gt; (pprint (macroexpand-1 '(let-alist (:bar |foo| baz)\n (this-function-takes-a-long-time-or-has-side-effects)\n (list |foo| bar baz))))\n\n(LET ((BAR (CDR (ASSOC :BAR (THIS-FUNCTION-TAKES-A-LONG-TIME-OR-HAS-SIDE-EFFECTS))))\n (|foo|\n (CDR (ASSOC '|foo| (THIS-FUNCTION-TAKES-A-LONG-TIME-OR-HAS-SIDE-EFFECTS))))\n (BAZ\n (CDR (ASSOC 'BAZ (THIS-FUNCTION-TAKES-A-LONG-TIME-OR-HAS-SIDE-EFFECTS)))))\n (LIST |foo| BAR BAZ))\n</code></pre>\n\n<p>As you can see the function is expanded multiple times into the code.</p>\n\n<p><strong>Rule 1</strong>: Always check the expansion for problems.</p>\n\n<p><strong>Rule 2</strong>: Do not expand the same code multiple times into the code.</p>\n\n<p>Read 'On Lisp' by Paul Graham (free download available) for the various pitfalls of macros in Common Lisp and how to deal with those.</p>\n\n<p>For above you need to generate a new unique variable and bind the value once.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T17:33:32.013", "Id": "17323", "Score": "0", "body": "Good point. Revised. I was really only expecting to have to pass this thing raw `alist`s, but it can't hurt to be prepared. What's your take on nested `let`s vs. a single `let*` in a situation like the above?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T13:53:07.217", "Id": "10890", "ParentId": "10843", "Score": "2" } }, { "body": "<p>Here's an implementation that gives read and write access to the values in the alist.</p>\n\n<p>To start, define a macro using symbol-macrolet, where a bound symbol in the body expands to code that accesses that symbol's value in the alist:</p>\n\n<pre><code>(defmacro with-alist% (alist-entries instance-form &amp;body body)\n `(symbol-macrolet \n ,(loop for (alist-binding alist-entry) in alist-entries\n collect `(,alist-binding (cdr (assoc ',alist-entry ,instance-form))))\n ,@body))\n</code></pre>\n\n<p>And test it:</p>\n\n<pre><code>(defparameter *al* (list (cons 'foo 5) (cons 'bar 'a) (cons 'baz \"z\")))\n*AL*\nCL-USER&gt; \n(print *al*)\n\n((FOO . 5) (BAR . A) (BAZ . \"z\")) \n((FOO . 5) (BAR . A) (BAZ . \"z\"))\nCL-USER&gt; \n(with-alist% ((foo foo) (bar bar)) *al*\n (format t \"foo=~a, bar=~a~%\" foo bar)\n (setf foo 1)\n (setf bar \"a\") ...)\nfoo=5, bar=A\nfoo=1, bar=a \nNIL\nCL-USER&gt; \n(print *al*)\n\n((FOO . 1) (BAR . \"a\") (BAZ . \"z\")) \n((FOO . 1) (BAR . \"a\") (BAZ . \"z\"))\nCL-USER&gt; \n</code></pre>\n\n<p>Note that not only can you use the bound symbol for printing, you can also setf the symbol, which maps to changing the value associated with that symbol in the alist. This is what using symbol-macrolet (instead of let) provides. Also, if you read the source code for with-slots, at least for CCL, symbol-macrolet is how that macro is implemented. Again, I'm working towards a similar syntactic feel of with-slots.</p>\n\n<p>with-alist% works well enough when you have an alist of mixed keywords and symbols, but I would think that most often you'll have just symbols, which means that there will be a lot of code duplication when using that function, for example:</p>\n\n<pre><code>(with-alist% ((foo foo) (bar bar)) *al*\n</code></pre>\n\n<p>Note how each alist entry is listed twice. What if you want the bound symbol and alist entry to always be the same? It would be nice if you could do this:</p>\n\n<pre><code>(with-alist (foo bar) *al*\n</code></pre>\n\n<p>And that macro:</p>\n\n<pre><code>(defmacro with-alist (alist-entries instance-form &amp;body body)\n `(with-alist% ,(mapcar (lambda (alist-entry)\n (if (consp alist-entry)\n `,alist-entry\n `,(list alist-entry alist-entry)))\n alist-entries)\n ,instance-form\n ,@body))\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>(print *al*)\nCL-USER&gt; \n((FOO . 1) (BAR . \"a\") (BAZ . \"z\")) \n((FOO . 1) (BAR . \"a\") (BAZ . \"z\"))\nCL-USER&gt; \n(with-alist (foo (bar% bar)) *al*\n (format t \"foo=~a, bar=~a~%\" foo bar%)\n (setf foo 5)\n (setf bar% 'a) ...)\nfoo=1, bar=a\nfoo=5, bar=A\nNIL\nCL-USER&gt; \n(print *al*) \n\n((FOO . 5) (BAR . A) (BAZ . \"z\")) \n((FOO . 5) (BAR . A) (BAZ . \"z\"))\nCL-USER&gt; \nREPL \n</code></pre>\n\n<p>I agree with Rainer's comment about only evaling instance-form once, when you only want read access. However, if you want read/write access, then instance-form will need to be expanded every time that a bound symbol is found in body. Otherwise, you'll be writing to an let binding of instance-form; not instance-form; and therefore instance-form won't be changed. </p>\n\n<p>A good read for common-lisp macro programming is definitely On Lisp, and also Let Over Lambda. Getting through LOL is IME a serious time investment, but well worth it if you want to improve your common lisp macro programming skills.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T18:02:54.753", "Id": "10893", "ParentId": "10843", "Score": "2" } } ]
{ "AcceptedAnswerId": "10890", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T03:19:32.010", "Id": "10843", "Score": "2", "Tags": [ "lisp", "common-lisp", "macros" ], "Title": "with-alist-bind" }
10843
<p>I'm VERY new to error/exception handling, previously just echoing everything to screen, and am trying to really clean up my code. My goal was to log everything but only show the user a friendly "oops" page if something was seriously broken. How does what I have below look?</p> <p>Any best practice advice is appreciated.</p> <pre><code>&lt;?php error_reporting(~0); ini_set('display_errors', 0); ini_set('log_errors', 1); /* Set the error handler. */ set_error_handler(function ($errno, $errstr, $errfile, $errline) { /* Ignore @-suppressed errors */ if (!($errno &amp; error_reporting())) return; $e = array('type'=&gt;$errno, 'message'=&gt;$errstr, 'file'=&gt;$errfile, 'line'=&gt;$errline); redirect($e); }); /* Set the exception handler. */ set_exception_handler(function ($e) { $e = array('type'=&gt;$e-&gt;getCode(), 'message'=&gt;$e-&gt;getMessage(), 'file'=&gt;$e-&gt;getFile(), 'line'=&gt;$e-&gt;getLine()); redirect($e); }); /* Check if there were any errors on shutdown. */ register_shutdown_function(function () { if (!is_null($e = error_get_last())) { redirect($e); } }); function redirect($e) { $now = date('d-M-Y H:i:s'); $type = format_error_type($e['type']); $message = "[$now] $type: {$e['message']} in {$e['file']} on line {$e['line']}\n"; $error_log_name = ini_get('error_log'); error_log($message, 3, $error_log_name); switch ($e['type']) { /* We'll ignore these errors. They're only here for reference. */ case E_WARNING: case E_NOTICE: case E_CORE_WARNING: case E_COMPILE_WARNING: case E_USER_WARNING: case E_USER_NOTICE: case E_STRICT: case E_RECOVERABLE_ERROR: case E_DEPRECATED: case E_USER_DEPRECATED: case E_ALL: break; /* Redirect to "oops" page on the following errors. */ case 0: /* Exceptions return zero for type */ case E_ERROR: case E_PARSE: case E_CORE_ERROR: case E_COMPILE_ERROR: case E_USER_ERROR: return header('Location: /oops_page.htm'); } } function format_error_type($type) { switch($type) { case 0: return 'Uncaught exception'; case E_ERROR: /* 1 */ return 'E_ERROR'; case E_WARNING: /* 2 */ return 'E_WARNING'; case E_PARSE: /* 4 */ return 'E_PARSE'; case E_NOTICE: /* 8 */ return 'E_NOTICE'; case E_CORE_ERROR: /* 16 */ return 'E_CORE_ERROR'; case E_CORE_WARNING: /* 32 */ return 'E_CORE_WARNING'; case E_CORE_ERROR: /* 64 */ return 'E_COMPILE_ERROR'; case E_CORE_WARNING: /* 128 */ return 'E_COMPILE_WARNING'; case E_USER_ERROR: /* 256 */ return 'E_USER_ERROR'; case E_USER_WARNING: /* 512 */ return 'E_USER_WARNING'; case E_USER_NOTICE: /* 1024 */ return 'E_USER_NOTICE'; case E_STRICT: /* 2048 */ return 'E_STRICT'; case E_RECOVERABLE_ERROR: /* 4096 */ return 'E_RECOVERABLE_ERROR'; case E_DEPRECATED: /* 8192 */ return 'E_DEPRECATED'; case E_USER_DEPRECATED: /* 16384 */ return 'E_USER_DEPRECATED'; } return $type; } ?&gt; </code></pre>
[]
[ { "body": "<p>A few things jump out at me:</p>\n\n<ul>\n<li><p>The redirect of $e['type'] == 0:\nFor exceptions the default code is 0. Another code could be used and if the exception is not catched, it will throw a fatal error. Your handler does watch for fatal errors, so this may be a non-issue. The exception condition will just be logged twice.</p></li>\n<li><p>For the actual header redirect:\nSome browsers are slow on the header redirect (I'm not sure why). If you allow the rest of your code to continue executing, it could cause an ugly screen flicker. Again, since you are only redirecting fatal errors, probably a non-issue.</p></li>\n<li><p>The logging functionality:\nYou may want to consider moving this out into another function. Some day you may decide to log the errors to a database, send emails, or even a text message. You could add these to that redirect method, but that would start to get pretty messy. If each piece were a separate method that was called from a generic log method, that would be easier to read and change as needed.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T12:49:49.857", "Id": "10861", "ParentId": "10846", "Score": "1" } } ]
{ "AcceptedAnswerId": "10861", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T04:12:29.573", "Id": "10846", "Score": "3", "Tags": [ "php", "error-handling" ], "Title": "PHP error handling: log everything, and redirect critical errors to an \"oops\" page" }
10846
<p>I'm looking for a better implementation of the algorithm.</p> <pre><code>/* * You have an ordered array X of n integers. Find the array M containing * elements where Mi is the product of all integers in X except for Xi. * You may not use division. You can use extra memory. */ #include &lt;iostream&gt; #include &lt;stack&gt; #include &lt;queue&gt; #include &lt;vector&gt; /*! * Class used to generate sequences with helper function */ template &lt;class T&gt; class sequence : public std::iterator&lt;std::forward_iterator_tag, T&gt; { T val; public: sequence(T init) : val(init) {} T operator *() { return val; } sequence &amp;operator++() { ++val; return *this; } bool operator!=(sequence const &amp;other) { return val != other.val; } }; template &lt;class T&gt; sequence&lt;T&gt; gen_seq(T const &amp;val) { return sequence&lt;T&gt;(val); } static const int N = 3; std::stack&lt;int&gt; stk; std::queue&lt;int&gt; que; int main(int argc, char *argv[]) { std::vector&lt;int&gt; seq(gen_seq(1), gen_seq(N + 1)); for (int x = 0, y = N - 1; x &lt; N &amp;&amp; y &gt;= 0; ++x, --y) { if (x == 0 &amp;&amp; y == N - 1) { stk.push(1); que.push(1); } else { stk.push(stk.top() * seq[x - 1]); que.push(que.back() * seq[y + 1]); } } for (int x = 0; x &lt; N; ++x) { std::cout &lt;&lt; (stk.top() * que.front()) &lt;&lt; std::endl; stk.pop(); que.pop(); } } </code></pre>
[]
[ { "body": "<p>First, some comments on the existing code:</p>\n\n<pre><code>/*\n * You have an ordered array X of n integers. Find the array M containing\n * elements where Mi is the product of all integers in X except for Xi.\n * You may not use division. You can use extra memory\n */\n</code></pre>\n\n<p>You don't have anything called <code>X</code> in the code, or generate <code>M</code>, so this comment could be better</p>\n\n<pre><code>static const int N = 3;\nstd::stack&lt;int&gt; stk;\nstd::queue&lt;int&gt; que;\n</code></pre>\n\n<p>Why use globals? Also, try to name variables by what they <em>do</em> or <em>represent</em>, rather than their type.</p>\n\n<pre><code>int main(int argc, char *argv[]) {\n</code></pre>\n\n<p>For that matter, why put the logic in <code>main</code> where you can't test it?\nI would hope to see something structured like:</p>\n\n<pre><code>std::vector&lt;int&gt; products(std::vector&lt;int&gt; const &amp;X)\n{\n auto n = X.size();\n std::vector&lt;int&gt; M(n, 1);\n\n // ... algorithm ...\n\n return M;\n}\n\nint main()\n{\n static const int N = 3;\n std::vector&lt;int&gt; seq(gen_seq(1), gen_seq(N + 1))\n std::vector&lt;int&gt; result = products(seq);\n // print the result\n // or assert correctness\n}\n</code></pre>\n\n<p>Or possibly several test functions, each called from <code>main</code>.</p>\n\n<p>As for the algorithm itself, its working isn't really clear, and that's where comments would be useful. I'm sure <em>you</em> have a deep intuitive understanding of why your nameless stack and queue generate the right results, but without a lot of effort I don't. In six months' time, you may not either.</p>\n\n<p>Your loop can be cleaner anyway; instead of:</p>\n\n<pre><code> for (int x = 0, y = N - 1; x &lt; N &amp;&amp; y &gt;= 0; ++x, --y) {\n if (x == 0 &amp;&amp; y == N - 1) {\n stk.push(1);\n que.push(1);\n } else {\n stk.push(stk.top() * seq[x - 1]);\n que.push(que.back() * seq[y + 1]);\n }\n }\n</code></pre>\n\n<p>we can:</p>\n\n<ol>\n<li>move the special case <code>if (x == 0 ...</code> outside</li>\n<li>then, you only have to iterate over the values used in the second branch (so <code>1 &lt;= x &lt; N</code>, <code>N-2 &gt;= y &gt;= 0</code>)</li>\n<li>but we only use <code>x-1</code> and <code>y+1</code> in the body of the loop, so simplify this to <code>0 &lt;= x &lt; N-1</code> and <code>N-1 &gt;= y &gt;= 0</code> and just use <code>x</code> and <code>y</code> in the body</li>\n<li>notice that the two conditions (<code>x &lt; N-1 &amp;&amp; y &gt;= 0</code>) will always agree, so we don't have to test both</li>\n</ol>\n\n<p>to get:</p>\n\n<pre><code> stk.push(1);\n que.push(1);\n for (int x = 0, y = N-1; x &lt; N-1; ++x, --y)\n {\n stk.push(stk.top() * seq[x]);\n que.push(que.back() * seq[y]);\n }\n</code></pre>\n\n<hr>\n\n<p>and a simpler implementation:</p>\n\n<pre><code>std::vector&lt;int&gt; products(std::vector&lt;int&gt; const &amp;X)\n{\n auto n = X.size();\n std::vector&lt;int&gt; M(n, 1); // initialise all values to 1\n\n for (int i = 0; i &lt; n; ++i)\n {\n // set Mj &lt;= Mj * Xi for all j != i\n for (int j = 0; j &lt; n; ++j)\n if (j != i) M[j] *= X[i];\n }\n return M;\n}\n</code></pre>\n\n<p>This one uses no extra memory but is <code>O(n^2)</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T20:08:28.897", "Id": "17291", "Score": "0", "body": "Thanks for the tips. Though the O(n^2) algorithm is what I was trying to get away from. It is clear, but for very large data sets it is not efficient." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T11:41:05.433", "Id": "10859", "ParentId": "10848", "Score": "6" } }, { "body": "<p>At least IMO, this can be solved quite a bit more cleanly than the examples above show. The \"trick\" to solving the problem efficiently is to produce running products, starting from both the left <em>and</em> the right side of the input array. To keep some of the later code simple, it's easiest to append a <code>1</code> to the beginning of one of those, and the end of the other.</p>\n\n<p>For example, given an input like: [2, 3, 5, 7] we'd produce intermediate results like:</p>\n\n<pre><code>X 2 3 5 7\nleft 1 2 6 30 210\nright 210 105 35 7 1\n</code></pre>\n\n<p>Just to be sure we're clear, the <code>left</code> holds running products starting from the left--the first item is a <code>1</code> we put there \"artificially\". The second is 1*2. The third is 1*2*3. The fourth is 1*2*3*5, and the last is 1*2*3*5*7.</p>\n\n<p>In <code>right</code> is pretty much the same, <em>except</em> that it's starting from the right instead of the left. So, the first item (starting from the right) is (again) the 1 we insert. Then 1*7, 1*7*5, 1*7*5*3, and 1*7*5*3*2.</p>\n\n<p>Now, to compute each result, we multiply an item in <code>left</code> by an item in <code>right</code>. As I've lined things up in the table above, the items from <code>left</code> and <code>right</code> that are verticall aligned are multiplied to produce each result (and the last item of <code>left</code> and first item of <code>right</code> are simply ignored).</p>\n\n<p>Translating that into C++, we get something like this:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;deque&gt;\n#include &lt;algorithm&gt;\n#include &lt;iterator&gt;\n\nint main() {\n std::deque&lt;int&gt; X{2, 3, 5, 7};\n\n std::deque&lt;int&gt; left;\n std::deque&lt;int&gt; right;\n\n left.push_back(1);\n\n int temp = 1;\n\n std::transform(X.begin(), X.end(), std::back_inserter(left),\n [&amp;temp](int i) { temp *= i; return temp; });\n\n temp = 1;\n\n std::transform(X.rbegin(), X.rend(), std::front_inserter(right),\n [&amp;temp](int i) { temp *= i; return temp; });\n\n right.push_back(1);\n\n std::transform(left.begin(), left.end()-1,\n right.begin()+1,\n std::ostream_iterator&lt;int&gt;(std::cout, \"\\t\"),\n [](int i, int j) { return i * j; });\n}\n</code></pre>\n\n<p>That produces the following result:</p>\n\n<pre><code>105 70 42 30\n</code></pre>\n\n<p>Given \\$N\\$ inputs, this uses \\$O(N)\\$ extra space for <code>right</code> and <code>left</code>, and \\$O(N)\\$ time complexity (three traversals of \\$N\\$ items each).</p>\n\n<p>Right now, this code uses <code>+</code> on one of the iterators and <code>-</code> on another, limiting the iterators to random access. If desired, it would be fairly trivial to use <code>std::advance</code> (or just <code>++</code> and <code>--</code>) to increment the iterators without the requirement for random access. On the other hand, there seems to be little gain from doing so--in theory it would allow us to use (for example) linked lists instead of <code>deque</code>s, but that seems unlikely to provide any real advantage.</p>\n\n<p>If you were going to process large collections, you'd have another serious problem: the numbers involved would quick grow much larger than a <code>long</code> or even <code>long long</code> could accommodate. If the collection was very large at all, you'd probably need to use some sort of big integer type to represent the product.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-28T08:08:05.453", "Id": "55542", "ParentId": "10848", "Score": "5" } } ]
{ "AcceptedAnswerId": "10859", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T05:43:31.347", "Id": "10848", "Score": "3", "Tags": [ "c++", "algorithm", "programming-challenge" ], "Title": "Product of all ints in array besides that an index i" }
10848
<p>Two words are anagrams of each other if they contain the same letters, such as "pots == stop".</p> <p>The easiest way to check is to sort both words, then compare. But that's an \$O(n*log(n))\$ solution and I'd like to find an \$O(n)\$ one.</p> <ol> <li><p>Is this code \$O(n)\$? I only make one pass per string, but I use a hash Remove which is \$O(n)\$ by itself.</p></li> <li><p>Is there a completely better way? Or can my code be optimized to run faster/cleaner?</p></li> </ol> <p></p> <pre><code>public static bool AreAnagrams(string str1, string str2) { //lucky cases if(str1 == str2) return true; if(str1.Length != str2.Length) return false; Dictionary&lt;char, int&gt; letters = new Dictionary&lt;char, int&gt;(); //put all the letters for str1 and their occurance in dictionary foreach(char c in str1.AsEnumerable&lt;char&gt;()) { if(letters.ContainsKey(c)) letters[c]++; else letters[c] = 1; } //remove matched letters foreach(char c in str2.AsEnumerable&lt;char&gt;()) { if(letters.ContainsKey(c)) { letters[c]--; if(letters[c] == 0) letters.Remove(c); } //found a letter that wasn't in str1 else return false; } //true if we added all the letters and removed them all return letters.Values.Count == 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T06:54:48.433", "Id": "17263", "Score": "0", "body": "`Dictionary.Remove()` is O(1), in the average case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T07:14:39.960", "Id": "17264", "Score": "0", "body": "that's what I get for skimming wikipedia. So then my code is O(n) and as fast as it's going to get?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T13:00:49.833", "Id": "17579", "Score": "0", "body": "For this kind of algorithms I find big O notation misleading. The algorithm is not going to escalate to large N's so, who cares for asymptotic complexity? O(2N) and O(10N) are both O(N), but for n < 10, O(N^2) beats O(10N) Are you going to check anagrams on long words? Don't think so... Bear in mind I'm not saying O(N^2) is not bad, I'm saying that for low N's, the linear factor actually matters because N's order is not that important, so big O is misleading. Correct me if I'm wrong!" } ]
[ { "body": "<p>Yes, it's probably as fast as it gets (apart from a possible mistake that I'll explain). The <strong>average-case complexity</strong> of Remove is O(1), and it seems unlikely to me that you could skip any characters in a string since string comparison is O(n) and anagram checking is likely more complex than that. As a first guess, the asymptotic complexity of this algorithm is probably O(n)+O(n^2)=O(n^2) (n^2 because you are doing an O(n) operation for O(n) characters when calling Remove). </p>\n\n<p>The average-case complexity of you algorithm is O(2n)=O(n), which is not bad at all for this problem. I think your implementation is likely to outperform the sorting one because the hash tables behave very well with a low amount of elements (if you mean anagrams in the sense of real words, you will have relatively small inputs).</p>\n\n<p>Now, this line might not do what you intended:</p>\n\n<pre><code>if(str1 == str2)\n</code></pre>\n\n<p>According to the <a href=\"http://msdn.microsoft.com/en-us/library/53k8ybth.aspx\" rel=\"nofollow\">MSDN</a>, this will compare the values of the strings, not their references, which is already an O(n) operation in itself:</p>\n\n<blockquote>\n <p>For the string type, == compares the values of the strings.</p>\n</blockquote>\n\n<p>If your intention was to compare the references (as an easy case), you must cast the strings to <code>object</code> and compare those:</p>\n\n<pre><code>if ((object)str1 == (object)str2)\n</code></pre>\n\n<p>It's important to note that it doesn't matter from the viewpoint of asymptotic complexity if you are doing an O(n) comparison here, since the O(n^2) later will dominate the complexity anyway. But for amortized complexity it matters, and that is important if you are dealing with small inputs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T16:37:10.043", "Id": "17276", "Score": "2", "body": "Better yet: `object.ReferenceEquals(str1, str2)`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T11:00:48.830", "Id": "10854", "ParentId": "10849", "Score": "4" } }, { "body": "<p>The use of Remove is not needed though. </p>\n\n<p>You can have something like </p>\n\n<pre><code>if(letters.ContainsKey(c) || letters[c] &gt; 0)\n letters[c]--;\nelse //found a letter that wasn't in str1\n return false;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T16:39:22.613", "Id": "17277", "Score": "0", "body": "Hmm, one extra unnecessary access. Perhaps `if(!letters.ContainsKey(c) || letters[c]-- <= 0) { return false }`? But this starts to get a bit criptic." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T11:16:51.943", "Id": "10856", "ParentId": "10849", "Score": "1" } }, { "body": "<p>The Remove call is not necessary - in python:</p>\n\n<pre><code>def anagram(w1, w2):\n from collections import Counter\n counter = Counter()\n for c in w1:\n counter[c] += 1\n for c in w2:\n counter[c] -= 1\n for count in counter.values():\n if count != 0:\n return False\n return True\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T11:31:35.163", "Id": "10857", "ParentId": "10849", "Score": "5" } }, { "body": "<pre><code>Dictionary&lt;char, int&gt; letters = new Dictionary&lt;char, int&gt;();\n</code></pre>\n\n<p>If you only need to support the 26 English letters, then using int array of size 26 will be more efficient and produce cleaner code. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T00:05:31.210", "Id": "17369", "Score": "0", "body": "This is a great idea, I suggest you add the full solution I suspect the entire code will be very short and easy." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T19:20:11.213", "Id": "17418", "Score": "1", "body": "@Leonid, I'm hesitant to do that because I don't code in C#. The whole thing would be a one liner in my favored language, python. `return Counter(w1) == Counter(w2)`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T13:55:04.790", "Id": "10864", "ParentId": "10849", "Score": "2" } } ]
{ "AcceptedAnswerId": "10857", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T06:36:52.300", "Id": "10849", "Score": "5", "Tags": [ "c#", "interview-questions" ], "Title": "Anagram Checker" }
10849
<p>I've written a small markov chain monte carlo function that takes samples from a posterior distribution, based on a prior and a binomial (Bin(N, Z)) distribution.</p> <p>I'd be happy to have it reviewed, especially perhaps, regarding how to properly pass functions as arguments to functions (as the function <code>prior_dist()</code> in my code). In this case, I'm passing the function <code>uniform_prior_distribution()</code> showed below, but it's quite likely I'd like to pass other functions, that accept slightly different arguments, in the future. This would require me to rewrite <code>mcmc()</code>, unless there's some smart way around it...</p> <pre><code>def mcmc(prior_dist, size=100000, burn=1000, thin=10, Z=3, N=10): import random from scipy.stats import binom #Make Markov chain (Monte Carlo) mc = [0] #Initialize markov chain while len(mc) &lt; thin*size + burn: cand = random.gauss(mc[-1], 1) #Propose candidate ratio = (binom.pmf(Z, N, cand)*prior_dist(cand, size)) / (binom.pmf(Z, N, mc[-1])*prior_dist(mc[-1], size)) if ratio &gt; random.random(): #Acceptence criteria mc.append(cand) else: mc.append(mc[-1]) #Take sample sample = [] for i in range(len(mc)): if i &gt;= burn and (i-burn)%thin == 0: sample.append(mc[i]) sample = sorted(sample) #Estimate posterior probability post = [] for p in sample: post.append(binom.pmf(Z, N, p) * prior_dist(p, size)) return sample, post, mc def uniform_prior_distribution(p, size): prior = 1.0/size return prior </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-27T04:41:55.547", "Id": "179822", "Score": "0", "body": "is it possible to replace `binom.pmf` with some more simple implementation" } ]
[ { "body": "<h2>Function Passing</h2>\n\n<p>To pass functions with possibly varying argument lists consider using <a href=\"http://docs.python.org/release/2.5.2/tut/node6.html#SECTION006740000000000000000\" rel=\"nofollow\">argument unpacking</a>.</p>\n\n<p>By using a dictionary at the call site, we can use the arguments that are relevant to the chosen function whilst discarding those which aren't.</p>\n\n<pre><code>def uniform_prior_distribution(p, size, **args): #this args is neccesary to discard parameters not intended for this function\n prior = 1.0/size\n return prior\n\ndef foo_prior_distribution(p, q, size, **args):\n return do_something_with(p, q, size)\n\ndef mcmc(prior_dist, size=100000, burn=1000, thin=10, Z=3, N=10):\n import random\n from scipy.stats import binom\n #Make Markov chain (Monte Carlo)\n mc = [0] #Initialize markov chain\n while len(mc) &lt; thin*size + burn:\n cand = random.gauss(mc[-1], 1) #Propose candidate\n args1 = {\"p\": cand, \"q\": 0.2, \"size\": size}\n args2 = {\"p\": mc[-1], \"q\": 0.2, \"size\": size}\n ratio = (binom.pmf(Z, N, cand)*prior_dist(**args1)) / (binom.pmf(Z, N, mc[-1])*prior_dist(**args2))\n</code></pre>\n\n<p>Depending on how you use the mcmc function you may want to pass the args1 and args2 dicts directly as parameters to mcmc.</p>\n\n<p>However, this approach with only work if the common parameters (in this case p and size) can remain constant between different functions. Unfortunately I don't know enough about prior distributions to know if this is the case.</p>\n\n<h2>Other points of note</h2>\n\n<p>Use </p>\n\n<pre><code>sample.sort()\n</code></pre>\n\n<p>Instead of</p>\n\n<pre><code>sample = sorted(sample)\n</code></pre>\n\n<p>It's clearer and slightly more efficient (it saves a copy).</p>\n\n<p>Instead of:</p>\n\n<pre><code>for i in range(len(mc)):\n if i &gt;= burn and (i-burn)%thin == 0:\n sample.append(mc[i])\n</code></pre>\n\n<p>Use the more pythonic:</p>\n\n<pre><code>for i,s in enumerate(mc):\n if i &gt;= burn and (i-burn)%thin == 0:\n sample.append(s)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T11:03:29.420", "Id": "10855", "ParentId": "10851", "Score": "1" } }, { "body": "<pre><code>def mcmc(prior_dist, size=100000, burn=1000, thin=10, Z=3, N=10):\n import random\n from scipy.stats import binom\n</code></pre>\n\n<p>Don't import inside functions. It goes against python convention and is inefficient</p>\n\n<pre><code> #Make Markov chain (Monte Carlo)\n mc = [0] #Initialize markov chain\n while len(mc) &lt; thin*size + burn:\n cand = random.gauss(mc[-1], 1) #Propose candidate\n ratio = (binom.pmf(Z, N, cand)*prior_dist(cand, size)) / (binom.pmf(Z, N, mc[-1])*prior_dist(mc[-1], size))\n if ratio &gt; random.random(): #Acceptence criteria\n mc.append(cand)\n else:\n mc.append(mc[-1])\n</code></pre>\n\n<p>Why is this in else clause? It only make sense to use else clauses if you are using break.</p>\n\n<pre><code> #Take sample\n sample = []\n for i in range(len(mc)):\n if i &gt;= burn and (i-burn)%thin == 0:\n sample.append(mc[i])\n</code></pre>\n\n<p>Actually something like <code>sample = mc[burn::thin]</code> will have the same effect as this loop</p>\n\n<pre><code> sample = sorted(sample)\n #Estimate posterior probability\n post = []\n for p in sample:\n post.append(binom.pmf(Z, N, p) * prior_dist(p, size))\n</code></pre>\n\n<p>I'd suggest <code>post = [binom.pmf(Z, N, p) * prior_dist(p, size) for p in sample]</code></p>\n\n<pre><code> return sample, post, mc\n\ndef uniform_prior_distribution(p, size):\n prior = 1.0/size\n return prior\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T13:33:37.217", "Id": "10863", "ParentId": "10851", "Score": "2" } } ]
{ "AcceptedAnswerId": "10855", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T09:02:04.380", "Id": "10851", "Score": "3", "Tags": [ "python", "performance", "markov-chain" ], "Title": "Small Markov chain Monte Carlo implementation" }
10851
<p>I recently graduated from college and applied for a position with a company. I was sent a coding exercise as part of the process. After completing the exercise and submitting it I was told that the code provided the correct solution but was too hard to follow, the logic should be in the Course class, and "..due to refactoring requirements." (I'm not sure what that means).</p> <p>I know that I have a lot to learn and that I am still a novice programmer, but I was wondering if I could get some constructive suggestions from more experienced developers as to what needs to be changed in my code?</p> <p>The basic requirements are: Takes a String[] that contains the courses you must take and returns a String[] of courses in the order the courses should be taken so that all prerequisites are met. Validation is to be done on each course description and course names. Return an empty string[] if an error occurs.</p> <p>Examples of valid input Strings are: "CSE111: CSE110 MATH101" "CSE110:"</p> <pre><code>public class Course { private String courseName; private List prerequisites; public Course() { this.prerequisites = new ArrayList(); } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseName() { return courseName; } public List getPrerequisites() { return prerequisites; } public void addPrerequisite(String prerequisite) { prerequisites.add(prerequisite); } public int getCourseNumber() throws InvalidCourseNameException { int courseNumber = -1; try { if (courseName != null &amp;&amp; courseName.length() &gt; 3) { courseNumber = Integer.parseInt(courseName.substring(courseName.length() - 3)); } } catch (NumberFormatException e) { throw new InvalidCourseNameException(e.getMessage()); } return courseNumber; } } public class CourseScheduler { private Map availableCourses; private List schedule; private static final int COURSE_NUMBER_LENGTH = 3; public CourseScheduler() { // use a treemap to attempt to order classes by course number, in ascending order // or if courses have the same course number, order alphabetically by course name this.availableCourses = new TreeMap(new Comparator() { public int compare(Object courseNameOne, Object courseNameTwo) { String courseOneNumber = ((String) courseNameOne).substring(((String) courseNameOne).length() - COURSE_NUMBER_LENGTH); String courseTwoNumber = ((String) courseNameTwo).substring(((String) courseNameTwo).length() - COURSE_NUMBER_LENGTH); int comparison = courseOneNumber.compareTo(courseTwoNumber); if (comparison == 0) { return ((String) courseNameOne).compareTo((String) courseNameTwo); } else { return comparison; } } }); } /** * Create a schedule from the courses provided. * @param param0 The courses and there prerequisites that are required to be taken * @return an empty String array if an error occurs or a schedule can not be created, * a String array beginning with the first class to be taken and ending with the last class */ public String[] scheduleCourses(String[] param0) { schedule = new ArrayList(); if (param0 != null) { try { for (int i = 0; i &lt; param0.length; i++) { if (isValidCourseDescription(param0[i])) { addCourseToAvailableCourses(param0[i]); } else { throw new InvalidCourseDescriptionException("Invalid course description: " + param0[i]); } } buildSchedule(); } catch (InvalidCourseNameException e) { System.out.println(e.getMessage()); } catch (InvalidCourseDescriptionException e) { System.out.println(e.getMessage()); } } String[] classes = new String[schedule.size()]; classes = (String[]) schedule.toArray(classes); return classes; } /////////////////////// // private functions // /////////////////////// /** * Builds the class schedule from the available courses. * @throws InvalidCourseNameException if an invalid course name is found */ private void buildSchedule() throws InvalidCourseNameException{ Map temp = new TreeMap(availableCourses); int numberOfAvailableCourses = availableCourses.size(); while (schedule.size() &lt; numberOfAvailableCourses) { Course courseToAdd = null; Iterator it = temp.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); Course course = (Course) temp.get(key); // the course has already been added to the schedule if (schedule.contains(course.getCourseName())) { continue; } if (havePrerequisitesBeenTaken(course)) { if (courseToAdd == null) { courseToAdd = course; } else if (course.getCourseNumber() &lt; courseToAdd.getCourseNumber()) { courseToAdd = course; } else if (course.getCourseName().compareTo(courseToAdd.getCourseName()) &lt; 0) { courseToAdd = course; } } } if (courseToAdd != null) { schedule.add(courseToAdd.getCourseName()); // so we don't keep checking the available courses we have processed temp.remove(courseToAdd.getCourseName()); } else { // we should always have a course to add after checking the classes // something is wrong so clear the schedule and return schedule.clear(); return; } } } /** * Checks if the prerequisites for the course have been taken. * @param course The course to check * @return true if the course does not have prerequisites or the prerequisites * have been taken, false otherwise */ private boolean havePrerequisitesBeenTaken(Course course) { List prerequisites = course.getPrerequisites(); if (prerequisites == null || prerequisites.size() == 0) { return true; } for (int i = 0; i &lt; prerequisites.size(); i++) { if (!schedule.contains(prerequisites.get(i)) || !havePrerequisitesBeenTaken((Course) availableCourses.get(prerequisites.get(i)))) { return false; } } return true; } /** * Add a course object to the available courses using the data from the course description. * @param courseDescription The course description to add * @throws InvalidCourseNameException if an invalid course name is found for the course or its prerequisites */ private void addCourseToAvailableCourses(String courseDescription) throws InvalidCourseNameException { Course course = new Course(); int colonIndex = courseDescription.indexOf(':'); String courseName = courseDescription.substring(0, colonIndex); if (isValidCourseName(courseName)) { course.setCourseName(courseDescription.substring(0, colonIndex)); String prerequisites = courseDescription.substring(colonIndex); if (prerequisites.length() &gt; 1) { prerequisites = prerequisites.substring(1); StringTokenizer tokenizer = new StringTokenizer(prerequisites, " "); while (tokenizer.hasMoreTokens()) { String prerequisite = tokenizer.nextToken(); if (isValidCourseName(prerequisite)) { course.addPrerequisite(prerequisite); } else { throw new InvalidCourseNameException("Invalid course name: " + courseName); } } } } else { throw new InvalidCourseNameException("Invalid course name: " + courseName); } availableCourses.put(courseName, course); } /** * Determine if the course name follows the valid pattern - * 3-4 upper case characters followed by a number from 000 - 999. * @param courseName The course name to validate * @return true if the course name matches the pattern, false otherwise */ private boolean isValidCourseName(String courseName) { // validate the course name - i.e. "CSE111" or "MATH999" Pattern courseNamePattern = Pattern.compile("^[A-Z]{3,4}[1-9][0-9]{2}$"); Matcher matcher = courseNamePattern.matcher(courseName); return matcher.matches(); } /** * Determine if the course description follows the valid pattern - * {course name}:[ {course name} {course name}]. * @param courseDescription The course description to validate * @return true if the course description matches the pattern, false otherwise */ private boolean isValidCourseDescription(String courseDescription) { // validate the course description - i.e. "CSE111: CSE110 MATH101" // or "CSE110:" Pattern courseDescriptionPattern = Pattern.compile("^[A-Z]{3,4}[1-9][0-9]{2}(:$|:(\\s[A-Z]{3,4}[1-9][0-9]{2})+)"); Matcher matcher = courseDescriptionPattern.matcher(courseDescription); return matcher.matches(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T10:14:13.900", "Id": "17313", "Score": "2", "body": "Please read again the section on generics in a recent Java book. You have it wrong. `List prerequisites` should be `List<String> prerequisites`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T05:45:28.703", "Id": "19156", "Score": "0", "body": "please use \"descriptive\" title in future." } ]
[ { "body": "<p>Yes, this code is hard to follow. Some thoughts:</p>\n\n<ul>\n<li>use generics, e.g. <code>private List&lt;String&gt; prerequisites</code></li>\n<li>Provide useful constructors. E.g. Does a course without name make any sense? If not, the course name should be a constructor parameter</li>\n<li>honour encapsulation, prefer immutable data. Is it ever required to rename an existing course? If not, setCourseName shouldn't be public</li>\n<li>use the right representation. E.g. you often need the course prefix and the course number. Maybe it would be the best to split the course name already in the constructor, and store the parts, not the full name. This is also in the spirit of a \"fail early\" strategy.</li>\n</ul>\n\n<p>If I have time, I'll look deeper in the code. I think there are probably much more things that could be improved.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T15:19:21.593", "Id": "17271", "Score": "0", "body": "Thanks Landei. On your comment regarding \"..storing the parts, not the full name. This is also in the spirit of \"fail early\" strategy.\" Would it be correct to validate the incoming course name in the constructor? So would I throw an exception from the constructor if the course name was bad?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T19:04:53.170", "Id": "17284", "Score": "0", "body": "Yes. It's always good to check things, and to give an early and precise feedback about what's wrong with it, instead of letting it explode somwhere in the guts of your application. You should be especially cautious of `null` values." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T15:10:30.357", "Id": "10866", "ParentId": "10858", "Score": "6" } }, { "body": "<p><strong>A class should know &amp; do everything about itself</strong></p>\n\n<ul>\n<li><code>IsValidCourseName</code> and <code>isValidCourseDescription</code> should be in the\n<code>Course</code> class</li>\n</ul>\n\n<p><strong>Design should reflect your domain</strong></p>\n\n<ul>\n<li><p>What are we talking about here? A University, yes? Use that to frame\nyour design. What things are in there and what do we do with them?\nWhat attributes to these things have?</p></li>\n<li><p>I think there should be a <code>Schedule</code> class. This schedule may be\nordered, i.e. \"scheduled\" or it may be unordered, i.e. \"just a list of\ncourses I've signed up for.\"</p></li>\n<li><p>Maybe a <code>Schedule</code> has a boolean to indicated that it's been\nscheduled, or maybe theres a separate class <code>CourseLoad</code> to\nencapsulate the idea that this is a list of courses not yet\nscheduled.</p></li>\n<li><p>Maybe a <code>CourseCatalog</code> should encapsulate all the \"available\ncourses\" stuff.</p></li>\n<li><p>Then client code is necessarily written &amp; reads in terms of your\nbusiness model. e.g. compare: <code>public String[]\nscheduleCourses(String[] param0)</code> and <code>public Schedule\nscheduleCourses(CourseLoad newCourseLoad)</code>. It becomes virtually self\ndocumenting.</p></li>\n<li><p>You should get 10 lashes for every parameter name like <code>param0</code></p></li>\n<li><p><code>havePrerequisitesBeenTaken()</code> is totally baffling. Where the hell\ndid <code>courseDescription</code> come from? It's not in <code>Course</code>. The actual\ncode suggests that if a course has a prerequisite then, by\ndefinition, it has not been taken. Yet your comments say otherwise.\nThat makes no sense. And I had to study the code too much to figure\nthat out.</p></li>\n</ul>\n\n<p><strong>I like the CourseScheduler as a separate class</strong></p>\n\n<ul>\n<li><p>Separating out complex algorithms is a good way to contain complexity\nand keep other classes cleaner and clearer. This separation enhances \nmaintenance.</p></li>\n<li><p>Single Responsibility Principle (SRP) says a class should do only\none thing. In this case \"schedule courses.\" It should not be\nbuilding the available courses prerequisite map.</p></li>\n</ul>\n\n<p><strong>Design &amp; coding principles are fractal</strong></p>\n\n<ul>\n<li><p>A <a href=\"https://en.wikipedia.org/wiki/Fractal\" rel=\"nofollow noreferrer\">fractal</a> is a self-similar pattern, and likewise good design\nprinciples should be applied at all levels of your code. Abstraction\nand encapsulation apples at module, class, method, code block levels.</p></li>\n<li><p>I.E. make classes, methods, code bits as needed to express things in\nbusiness and process terms as much as practical. \"Push details down\".\nOtherwise you tend to obscure what's going on.</p></li>\n<li><p><code>buildSchedule()</code> is just one such method that is cluttered and it's\nfunction is not readily apparent without some deliberate diving into\nthe details. Yes, at some point the code must do what it does, but at\nthe conceptual level of \"how to build a schedule\" I want to see the\nconceptual steps expressed.</p></li>\n<li><p>The <code>CourseScheduler</code> class is cluttered because it's doing more than\njust producing a schedule. Specifically it seems to be the course\ncatalog as well.</p></li>\n</ul>\n\n<p><strong>Refactoring</strong></p>\n\n<p>Refactoring is a term with a technical meaning. Refactoring is the act of changing code without changing it's behavior (i.e. without breaking it!). There is <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201485672\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">an excellent book on the subject</a> that should be on every programmer's bookshelf - hear me now and believe me later.</p>\n\n<p>Good OO design <em>significantly</em> enhances your ability to refactor. So what, you say? Invariably code must be changed, either to fix bugs or add functionality. So the act of refactoring really starts with a software design that is flexible and extensible.</p>\n\n<p>Refactoring is not a measure of design quality. It is not what you do only after you've delivered your final product. It is what you do from the very beginning of writing your code, staring with a blank sheet of paper (metaphorically speaking, of course). <strong>Continuous Refactoring</strong> means write what you need now. As you add stuff, refactor as needed to (a) not break what you have (b) apply and maintain good design and coding principles when adding code and (c) ultimately enhance future changes.</p>\n\n<ul>\n<li><p><code>buildSchedule()</code> should have the catalog &amp; student's course list\npassed into it. Now buildSchedule can deal with any catalog and any\ncourse list. If the catalog mapping algorithm changes,\n<code>buildSchedule()</code> does not change.</p></li>\n<li><p>When you have complex or obscure logic consider refactoring. Compare:\n<code>if (prerequisites == null || prerequisites.size() == 0)</code> vice\n<code>if(course.prerequisitesAreMet())</code>. Note that (a) As changed I can\ntell what's going and (b) the original code is not in the <code>Course</code>\nclass, yet it has to know how to figure out prerequisites for the\nstupid course.</p></li>\n</ul>\n\n<p>Good luck!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-04-13T15:41:07.843", "Id": "10867", "ParentId": "10858", "Score": "15" } }, { "body": "<p>It seems to me, that according to your use of <code>Course</code> the code would be better if you:</p>\n\n<ol>\n<li>add parameters to ctor (course name, and prerequisites) </li>\n<li>make courses <code>Comparable</code></li>\n</ol>\n\n<p>Then you can verify if the course name is in proper format and split it by parts (name and number) once and forever, and implement courses comparition logic inside the class, avoiding ugly code in client's classes. It will significantly improve encapsulation and release client's code from details of course class.</p>\n\n<p>If ctor finds that something wrong with course name/number, whatever, it may throw an exception.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T16:05:00.270", "Id": "10868", "ParentId": "10858", "Score": "2" } } ]
{ "AcceptedAnswerId": "10867", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-04-13T11:37:23.963", "Id": "10858", "Score": "8", "Tags": [ "java", "sorting", "interview-questions", "graph" ], "Title": "Reorder a list of courses, given their prerequisites" }
10858
<p>I have the following code that our users will use to embed a widget on their page:</p> <pre><code>var ttp_number = "1Z123489754897"; var ttp_key = "1234567890123457890123"; var ttp_width = 850; var ttp_height = 650; var ttp_m_width = 260; var ttp_m_height = 200; (function(){ document.write('&lt;div id="ttp"&gt;&lt;/div&gt;'); s=document.createElement('script'); s.type="text/javascript"; s.src="//example.com/embed.js"; setTimeout("document.getElementById('ttp').appendChild(s);",1); })(); </code></pre> <p>Is there a way to reorganize or make this more compact (other than minifying)?</p> <p>Right now the big list of variables feels inefficient just declaring them one at a time, but I'm not sure what the alternate would be.</p> <p>NOTE: I need to keep the script as compact as possible as the people who are copy/pasting this code many times know very little (if any) javascript, so if they some massive block of code, they'll freak out or stand a bigger chance of screwing it up.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T18:50:15.497", "Id": "17281", "Score": "0", "body": "What is the purpose of the setTimeout?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T18:55:02.493", "Id": "17283", "Score": "0", "body": "Honestly, not sure. Saw it in use somewhere a while back with a script used to asynchronously load a script." } ]
[ { "body": "<ul>\n<li><p><strong>Don't make your code more compact, it's a futile exercise. Use a minifier or even a compiler/optimizer. Your source code should be as readable as possible</strong></p></li>\n<li><p><code>document.write</code> is evil, don't use it.</p></li>\n</ul>\n\n<p>Here's how I would write it:</p>\n\n<pre><code>var tpp = {\n number: \"1Z123489754897\",\n key: \"1234567890123457890123\",\n width: 850,\n height: 200,\n \"m width\": 260,\n \"m height\": 200\n};\n\nfunction init(settings) {\n var div, script;\n div = document.createElement(\"div\");\n div.id = \"ttp\";\n document.body.appendChild(div);\n script = document.createElement(\"script\");\n script.src = \"//example.com/embed.js\";\n script.type = \"text/javascript\";\n document.body.appendChild(script);\n}\n\nwindow.attachEvent(\"load\", function() {\n init(tpp);\n});\n/* or */\nwindow.addEventListener(\"load\", function() {\n init(tpp);\n});\n</code></pre>\n\n<ul>\n<li><p>Adding the event listener on <code>window.load</code> avoids having to do the setTimeout later on.</p></li>\n<li><p>Also, when doing a setTimeout, don't use the <code>eval</code> variant, use an anonymous function:</p></li>\n</ul>\n\n<hr>\n\n<pre><code>setTimeout(function () {\n document.getElementById('ttp').appendChild(s);\n}, 1);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T18:53:17.677", "Id": "17282", "Score": "0", "body": "This is a snippet of code someone would copy/paste from our app and into their site. Giving them a huge block of code will likely freak them the heck out (many of these people know very little javascript...just basic HTML/CSS)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T19:25:05.317", "Id": "17286", "Score": "0", "body": "@Shpigford they shouldn't freak out because of huge blocks of code as long as they are understandable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T19:37:03.163", "Id": "17287", "Score": "1", "body": "These are people that don't know _any_ javascript. They won't understand it regardless of how readable it is. Simple as that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T18:49:55.343", "Id": "10873", "ParentId": "10872", "Score": "2" } }, { "body": "<p>This is the shortest version I could think of, without resorting to some code golf:</p>\n\n<pre><code>// Use an array instead of separate variables\n// You could extract it into variables in your script if you need to\nvar __ttp = [ \"1Z123\", \"1234\", 850, 650, 260, 200 ];\n\nvar script = document.createElement('script');\nscript.type = 'text/javascript';\nscript.src = '//example.com/embed.js';\n\n// Unless you need to create a separate div, you can append the script tag to the body\ndocument.body.appendChild(script);\n</code></pre>\n\n<p>Removing the comments and blank lines would make it into just 5 lines of code.</p>\n\n<p>If you need a separate div, you could replace the last line with this one:</p>\n\n<pre><code>var div = document.createElement('div');\ndiv.id = 'ttp';\ndocument.body.appendChild(div).appendChild(script);\n</code></pre>\n\n<p>Disclaimer: I have no idea whether you might need to use <code>setTimeout</code> to run the code above.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T21:08:35.040", "Id": "11736", "ParentId": "10872", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T18:46:34.003", "Id": "10872", "Score": "1", "Tags": [ "javascript" ], "Title": "Embedding a widget to a page" }
10872
<p>I have been doing some personal projects for fun and most of them have visual representation of boards (ej: sudoku solvers, chess PGN viewer, etc) and I always end up doing something like this:</p> <pre><code>var wid=10; var hei=6; var len=(wid*hei); var map="005000200000000008000600000006000700000040000000500030400000".split(""); var str="&lt;table id=\"board\" cellpadding=\"0\" cellspacing=\"0\"&gt;&lt;tbody&gt;&lt;tr&gt;"; for(var i=0;i&lt;len;i++){ if(i&amp;&amp;!(i%wid)){ str+="&lt;/tr&gt;&lt;tr&gt;"; } str+="&lt;td&gt;"+((map[i]!=0)?map[i]:"&amp;nbsp;")+"&lt;/td&gt;"; } str+="&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;"; document.body.innerHTML+=str; </code></pre> <p>with CSS styles like:</p> <pre><code>*{margin:0;padding:0;} #board{margin:15px auto;text-align:center;} #board,#board td{border:1px solid #000;} #board td{width:45px;height:47px;font-size:20px;} </code></pre> <p>I want to know if there is a better, more readable way to achieve this?, maybe using <code>arr.join()</code>?</p>
[]
[ { "body": "<p>IMO you're right, using <code>join</code> would solve part of the problem (a global <code>replace</code> using a <code>RegExp</code> can also help, for instance converting the zeroes into spaces). I'd also suggest using something else to separate rows, this way you won't need the variables <code>wid</code>, <code>hei</code> and <code>len</code> (besides making your map more readable):</p>\n\n<pre><code>var map=\"0050002000-0000000800-0600000006-0007000000-4000000050-0030400000\"\n .split(\"\").join(\"&lt;/td&gt;&lt;td&gt;\")\n .replace(/&lt;td&gt;-&lt;\\/td&gt;/g, \"&lt;/tr&gt;&lt;tr&gt;\") // replace \"-\" columns to rows\n .replace(/0/g, \"&amp;nbsp;\");\n\nvar str=\"&lt;table id=\\\"board\\\" cellpadding=\\\"0\\\" cellspacing=\\\"0\\\"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;\" +\n map + \"&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;\";\n</code></pre>\n\n<p>Working example at <a href=\"http://jsfiddle.net/mgibsonbr/HVbVp/\" rel=\"nofollow\">jsFiddle</a></p>\n\n<p>An alternative (which for my tastes is even better) is only using a string for each row, starting with an array alredy:</p>\n\n<pre><code>var map = [\"0050002000\",\n \"0000000800\",\n \"0600000006\",\n \"0007000000\",\n \"4000000050\",\n \"0030400000\"]\n .join('-') // Necessary for the rest of the code to work\n ...\n</code></pre>\n\n<p>This makes the tabular nature of the data visually evident.</p>\n\n<p>Lastly, if you <strong>can't</strong> (or, for any reason, don't want to) change the format of your initial map (inserting those <code>-</code> for row separation), one solution would be using a custom regex to insert them for you:</p>\n\n<pre><code>var regex = new RegExp('(.{' + wid + '})','g'); // groups \"wid\" digits\nvar map = \"005000200000000008000600000006000700000040000000500030400000\"\n .replace(regex, '$1-') // inserts a \"-\" after each group\n .replace(/-$/, \"\") // removes the last \"-\"\n ...\n</code></pre>\n\n<p>As you can see <a href=\"http://jsfiddle.net/mgibsonbr/HVbVp/1/\" rel=\"nofollow\">here</a>, the result is the same.</p>\n\n<p><em>Edit:</em> seeing your performance tests, I decided to add <a href=\"http://jsperf.com/boardgenerating/2\" rel=\"nofollow\">another test case</a> modifying your first sample (the fastest), replacing string concatenation to a list of strings with a single join in the end (the most recommended way of doing this). However, the results surprised me: your first version is still faster...</p>\n\n<p>I guess JS array operations are not really as fast as they could be... (I'd expect engine implementors to provide ultra-fast versions of those) Or maybe the issue is with regex processing? (I could try using a string only <code>replaceAll</code>, if only the language had such a function built-in...) Well, I guess your version wins in the performance metric. Now that I know string concat is not as bad as people paint it, I won't be ashamed to use it more often... :P</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T02:46:00.077", "Id": "17298", "Score": "0", "body": "your skills are awesome, this answer is perfect. Thank you :D!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T03:33:02.153", "Id": "17299", "Score": "0", "body": "just another thing, I think in the second example you meant `[\"...\",\"...\"]` instead of `[\"...\"+\"...\"]`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T03:49:01.853", "Id": "17300", "Score": "0", "body": "I feel weird posting 3 messages in a row, but I think they must exist: I did a performance test in case someone is interested http://jsperf.com/boardgenerating" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T04:43:40.240", "Id": "17301", "Score": "0", "body": "you're right about the `,` - answer updated. I also added another test case to your [performance test](http://jsperf.com/boardgenerating/2), but the results surprised me! See the edit above." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T00:15:44.193", "Id": "10881", "ParentId": "10875", "Score": "4" } }, { "body": "<p>Despite already having accepted an answer, I'd like to point out a different way to approach this. </p>\n\n<p>Since you are building the board with JavaScript I'm assuming that you want to modify the content of the board dynamically. (If not then the question would be why you are using JavaScript and not a server-side generation).</p>\n\n<p>In that case it could make sense to separate generation and filling the board. That way you could simply exchange each method without affecting the other. </p>\n\n<p>For generation you could continue to use your solution just with empty or default values, or use DOM generation:</p>\n\n<pre><code>var rowCount = 6;\nvar colCount = 10;\nvar board = document.createElement('table');\nfor (var r = 0; r &lt; rowCount; r++) {\n var row = board.insertRow();\n for (var c = 0; c &lt; colCount; c++) {\n row.insertCell();\n }\n}\n</code></pre>\n\n<p>Or simply use static HTML.</p>\n\n<p>And then you write a function that sets the value of a cell which will work no matter how you created the board. Something like:</p>\n\n<pre><code>function setBoardValue(board, x, y, value) {\n board.rows(y).cells(x).innerHTML = value;\n}\n</code></pre>\n\n<p>And then you can loop over your \"map\" in anyway you like and call it:</p>\n\n<pre><code>var map=\"005000200000000008000600000006000700000040000000500030400000\".split(\"\");\n\nfor (var i=0;i&lt;len;i++){\n setBoardValue(board, i % colCount, Math.floor(i / rowCount), map[i] != 0 ? map[i] : \"&amp;nbsp;\");\n}\n</code></pre>\n\n<p>In the end this solution if technically slower that your solution, but usually not in an amount that would be noticeable by the user and you have an advantage with the separation of the concerns.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T09:57:01.617", "Id": "10925", "ParentId": "10875", "Score": "5" } } ]
{ "AcceptedAnswerId": "10881", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T19:14:21.663", "Id": "10875", "Score": "4", "Tags": [ "javascript" ], "Title": "Array to Grid using a table" }
10875
<p>Prolog is a general purpose dynamically typed logic programming language associated with artificial intelligence and computational linguistics.</p> <p>Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is declarative: the program logic is expressed in terms of relations, represented as facts and rules. The execution of a Prolog program is a non-deterministic search through the solution space where the programmer specifies the constraints on an answer. This allows Prolog programs to be concise and declarative. While the language is built over first-order logic as a formalism, it includes constructs in higher order logic as well.</p> <p><strong>Getting Started</strong></p> <p>The popular compilers for Prolog include <a href="http://www.swi-prolog.org/" rel="nofollow">swi-prolog</a> and <a href="http://www.gprolog.org/" rel="nofollow">GNU Prolog</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T21:42:48.823", "Id": "10876", "Score": "0", "Tags": null, "Title": null }
10876
Prolog is a general purpose logic programming language associated with artificial intelligence and computational linguistics.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T21:42:48.823", "Id": "10877", "Score": "0", "Tags": null, "Title": null }
10877
<p>I have the following PHP function, which is admittedly not quite as robust as it could be (I'm missing some sanity checks including a proper one for <code>$sendTo</code> for example; odd choices in text formatting, too) but I don't see why it shouldn't work. A version of it certainly worked the other day, though I made a few small changes (allegedly for the better!) today. When the function executes, my condition <code>if (mail(etc))</code> indeed appends a success string to my content.</p> <pre><code>&lt;?php $FROM_EMAIL = "foo@bar.com"; $email = "foo@bar.com"; $content = ""; $emailMessage = ""; $sendTo = ""; if ($_SERVER['REQUEST_METHOD'] === 'POST') { foreach ($_POST as $key =&gt; $value) { $value = (string) $value; if ($key === "DESCRIPTION_OF_ITEMS") $value = str_replace("\r", '&lt;br&gt;', $value); if ($value !== "" &amp;&amp; $key !== "hiddenField" &amp;&amp; $key !== "button2" &amp;&amp; $key !== "cloneAdmin") $emailMessage .= "&lt;strong&gt;$key&lt;/strong&gt; - $value &lt;br/&gt;\n"; if ($key === "EMAIL") $sendTo = $value; } if ($emailMessage !== "") { $content .= "&lt;h3&gt;Thank you for submitting your registration form... we'll get back to you shortly.&lt;/h3&gt;&lt;p&gt;You can expect to receive an email with the following registration information:&lt;/p&gt;"; $content .= $emailMessage; if (mail("foobar@bazbat.com,$sendTo", "Foobar Registration Form", $emailMessage, "MIME-Version: 1.0\r\nContent-type: text/html; charset=iso-8859-1\r\nFrom: $FROM_EMAIL\r\nReply-to: $email")) { $content .= "&lt;h3&gt;Email successfully sent!&lt;/h3&gt;"; } else { $content .= "&lt;h3&gt;We encountered an error and the email was not successfully sent.&lt;/h3&gt;"; } } else { $content .= "No Email message"; } $content .= "&lt;/p&gt;"; } else { $content .= "&lt;/p&gt;&lt;h3&gt;A blank or invalid form was sent; your submission has not been successful.&lt;/h3&gt;"; } ?&gt; </code></pre> <p>For the record, I tried the <code>mail()</code> function in its most basic form as well:</p> <pre><code>mail('foo@bar.com', 'My Subject', $emailMessage); </code></pre> <p>and it didn't make a difference. The successful trial earlier this week used the additional header parts.</p> <p>Unfortunately I don't have access to the PHP logs; I only have FTP access. Also as you may have been able to guess from the coding style, I'm generally more of a JavaScript guy, so I'm not sure what my options are for capturing errors without the PHP log.</p> <p>Is it possible that there's just a problem (or security measures?) with the mail server? That the PHP code is fine and the problem is elsewhere? Maybe my own mail server is flagging spam and not even passing it into my junk box?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T08:43:59.830", "Id": "17309", "Score": "0", "body": "No idea, the code looks ok. Well, I can post some paranoid ideas, but it seems to me that the problem is outside. Anyway, try `diff` and figure what have you changed actually?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T14:31:02.250", "Id": "17353", "Score": "0", "body": "Thanks for looking, Michael. Diff just reveals some bad code that I inherited; `$$var = $var` and stuff. I rolled back to the original version and had the same problem, making it even more likely that it's outside of this code. Thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T00:39:53.337", "Id": "17370", "Score": "0", "body": "No problems! Good luck!" } ]
[ { "body": "<p>Don't know if you wanted a full review or not so I supplied one since I was going over it anyways. Not really much wrong, mostly aesthetics. I could find no errors in your code, but maybe one of these fixes will ninja your problem away. You never know, the all-powerful PHP god's might be feeling better today :)</p>\n\n<p><strong>POST Data</strong></p>\n\n<p>Not sure if better, but if I'm looking for <code>$_POST</code> variables, I usually just do the following. Up to you though, nothing wrong with what you've got.</p>\n\n<pre><code>if($_POST) { etc... }\n</code></pre>\n\n<p>You should have some sort of sanitizer for those user inputs though. This is the only real issue I see with your code. Take a look at <a href=\"http://us3.php.net/manual/en/function.filter-input.php\" rel=\"nofollow\"><code>filter_input</code></a> if you have PHP 5.2 or greater, otherwise you'll have to take a look around at what others are doing. It is never a good idea to take raw user input and run it in your program. That can lead to all sorts of nasty things.</p>\n\n<p><strong>Ignoring Keys</strong></p>\n\n<p>If you have a list of keys, or other items that you want to exclude, make them into an array and then check against it. Its cleaner than having a bunch of if statements and allows for extension later.</p>\n\n<pre><code>$exceptions = array(\n 'hiddenField',\n 'button2',\n 'cloneAdmin',\n);\n\nif ($value !== \"\" &amp;&amp; ! in_array($key, $exceptions)) { etc... }\n</code></pre>\n\n<p>Also, please use curly braces everywhere and not just on outter or large if statements. Yes PHP can work without them, but debugging your code will become very difficult later. Many might argue this point, but it truly is easier to read.</p>\n\n<p>Since you are already checking if the value is blank, you might as well move that to the beginning and place all other checks inside it. What's the use of running all that code if the value is blank or a key you don't want to process? Better yet, just add the following to the top of the foreach loop and it will skip those records entirely.</p>\n\n<pre><code>if($value === '' || in_array($key, $exceptions)) { continue; }\n</code></pre>\n\n<p><strong>Multiple If Statements</strong></p>\n\n<p>Don't use if statements for checking variables that you know a range of values for. Switch statements are faster and easier to read.</p>\n\n<pre><code>//Don't do this\nif($key === 'DESCRIPTION_OF_ITEMS') { etc... }\nif($key === 'EMAIL') { etc... }\n\n//Do this\nswitch($key) {\n case 'DESCRIPTION_OF_ITEMS':\n //etc...\n break;\n case ''EMAIL':\n //etc...\n break;\n}\n</code></pre>\n\n<p><strong>Long Variables</strong></p>\n\n<p>Heredoc will make your long variables easier to read.</p>\n\n<pre><code>$content .= &lt;&lt;HTML\n&lt;h3&gt;Thank you for submitting your registration form... we'll get back to you shortly.&lt;/h3&gt;\n&lt;p&gt;You can expect to receive an email with the following registration information:&lt;/p&gt;\n$emailMessage\nHTML;\n</code></pre>\n\n<p><strong>Long Strings as Arguments</strong></p>\n\n<p>If you are going to use long strings in functions you should replace them with variables, even if you aren't going to use those variables again. It makes it cleaner and easier to read.</p>\n\n<pre><code>$recipients = array();//You'll see why I used an array soon\n$recipients[] = \"foobar@bazbat.com\";\n$recipients[] = \"$sendTo\";\n$recipients = implode(', ', $recipients);//See :)\n\n$subject = \"Foobar Registration Form\";\n\n$headers = array();//Same as recipients\n$headers[] = \"MIME-Version: 1.0\";\n$headers[] = \"Content-type: text/html;\";//This line didn't originally have \"\\r\\n\" so maybe this was your problem?\n$headers[] = \"charset=iso-8859-1\";\n$headers[] = \"From: $FROM_EMAIL\";\n$headers[] = \"Reply-to: $email\";\n$headers = implode(\"\\r\\n\", $headers);\n\nmail($recipients, $subject, $emailMessage, $headers);//See much cleaner\n</code></pre>\n\n<p>Sorry I couldn't be of more use in finding your error. Since you are indeed receiving a success string, I would say that your send to line is just wrong somehow. Try dumping its contents before sending the message to manually check if anything is wrong. Only other thing I can think of is that maybe your server doesn't have the <code>mail()</code> function installed. Though, since you said it succeeded at some point, I don't know what to tell you. Check <code>php_info()</code> anyways to see if its enabled. As for if this is the wrong stackoverflow subsite? Not really. It could have gone on stackoverflow and no one would have complained. Here you just get the added benefit that I reviewed your code too :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-21T20:22:48.190", "Id": "17638", "Score": "0", "body": "Thanks for the super-detailed response and code review. Since it's largely inherited code, it becomes a 2-step process for me: 1. fix some crap they've provided (trust me, it was even worse!) and 2. fix the stuff you've suggested -- in particular, I like the organizational trick of using an array and then imploding it. Nice! I'll let you know if any ninjitsu is released from the changes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-21T23:22:08.000", "Id": "17645", "Score": "0", "body": "No prob. The implode trick actually wasn't mine, I found it on the PHP manual. Lots of good tricks there :) Hope you find the issue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-23T16:27:23.513", "Id": "17704", "Score": "0", "body": "Just realized I had put the wrong PHP version in there for filter_input, went ahead and changed that. (Should have been >=5.2)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T20:13:26.040", "Id": "11050", "ParentId": "10882", "Score": "3" } } ]
{ "AcceptedAnswerId": "11050", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T04:46:28.163", "Id": "10882", "Score": "5", "Tags": [ "php", "email" ], "Title": "Sanity check for mail code" }
10882
<p>I was writing a program that used a bit of recursion with objects, and it wasn't working at all. After debugging I realized that JS's evil scope was playing nasty tricks.</p> <p>To spare you guys a wall of <s>text</s> code, I wrote a smaller program:</p> <pre><code>//Class definition and framework: TestClass=function(label,level){ this.label=label; this.level=level; } TestClass.prototype.recur=function(){ r=Math.random(); //initialise a local variable document.write(this.label+":"+r+"&lt;BR/&gt;"); if(this.level==0){return;} //exit after this if level==0, we don't want to blow up the call stack x=new TestClass("inner1",0) x.recur(); document.write(this.label+":"+r+"&lt;BR/&gt;"); //Check if r has changed y=new TestClass("inner2",0) y.recur(); document.write(this.label+":"+r+"&lt;BR/&gt;"); //check if r has changed } //Run this: a=new TestClass("outer",1); a.recur(); </code></pre> <p>Output:</p> <pre><code>outer:0.5542382076382637 inner1:0.7689833084587008 outer:0.7689833084587008 inner2:0.24465859192423522 outer:0.24465859192423522 </code></pre> <p>As one can see, the value of <code>r</code> in the outer function has changed. From this, I see that JS joins the scope of a function with a function (recursively) called in itself. This seems slightly icky and illogical.</p> <p>My own solution to this was to make every locally initialized variable a member variable. In this example, I would replace all instances of <code>r</code> with <code>this.r</code>.</p> <p>Then, since I like my objects to be clean, I wrote a garbage collector. Final code would be somewhat like:</p> <pre><code>//Class definition and framework: TestClass=function(label,level){ this.label=label; this.level=level; } TestClass.allowedProperties=["label","level"] // do NOT blow these up during garbage collection TestClass.prototype.recur=function(){ this.r=Math.random(); //initialise a local variable document.write(this.label+":"+this.r+"&lt;BR/&gt;"); if(this.level==0){return;} //exit after this if level==0, we don't want to blow up the call stack x=new TestClass("inner1",0) x.recur(); document.write(this.label+":"+this.r+"&lt;BR/&gt;"); //Check if r has changed y=new TestClass("inner2",0) y.recur(); document.write(this.label+":"+this.r+"&lt;BR/&gt;"); //check if r has changed } //Garbage collector: TestClass.prototype.cleanup=function(){ for(x in this){ if(TestClass.allowedProperties.indexOf(x)==-1){ delete this[x]; } } } //Run this: a=new TestClass("outer",1); a.recur(); a.cleanup(); </code></pre> <p>This manages the job reasonably well, and cleans up after itself. But I feel that this is a rather inelegant way to do it. Is there a better, elegant way to deal with this form of evil javascript scoping?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T07:27:50.223", "Id": "17307", "Score": "2", "body": "`x = foo` is global, `var x = foo` is local" } ]
[ { "body": "<p>\"<em>From this, I see that JS joins the scope of a function with a function (recursively) called in itself.</em>\"</p>\n\n<p>No, it doesn't. You created a global variable called \"r\", not a method variable, and so there is only one \"r\", and it is accessible to all your JavaScript code.</p>\n\n<p><strong>Thou shalt always use <code>var</code> to declare a variable.</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T08:23:05.983", "Id": "17348", "Score": "0", "body": "Strange. I'm self-taught, so this may have slipped me... Though I distinctly remember `var` global-ifying stuff. :/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T12:29:18.190", "Id": "17351", "Score": "0", "body": "Wikipedia's [ECMAScript_syntax](http://en.wikipedia.org/wiki/ECMAScript_syntax#Variables) article has a good description of JavaScript's scoping issues. There are several things that are non-intuitive, and yes, depending on where you place the `var` statement, it can create a global variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T14:35:05.753", "Id": "17354", "Score": "0", "body": "Ooh thanks! I've always been wary of JS scope. Scared of it more like ;-)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T03:21:19.043", "Id": "10904", "ParentId": "10883", "Score": "1" } } ]
{ "AcceptedAnswerId": "10904", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T07:03:21.893", "Id": "10883", "Score": "0", "Tags": [ "javascript" ], "Title": "JS scope of member functions" }
10883
<p><a href="http://scrapy.org/" rel="nofollow">Scrapy</a> is a fast open-source high-level screen scraping and web crawling framework written in python, used to crawl websites and extract structured data from their pages. It can be used for a wide range of purposes, from data mining to monitoring and automated testing.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T08:19:35.430", "Id": "10884", "Score": "0", "Tags": null, "Title": null }
10884
Scrapy is a fast open-source high-level screen scraping and web crawling framework written in python, used to crawl websites and extract structured data from their pages. It can be used for a wide range of purposes, from data mining to monitoring and automated testing.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T08:19:35.430", "Id": "10885", "Score": "0", "Tags": null, "Title": null }
10885
<pre><code>&lt;? $debug = (isset($_GET['debug']) &amp;&amp; !empty($_GET['debug']))? $_GET['debug'] : false; define('TYPE_A', 'A'); define('TYPE_O', 'O'); define('DEBUG_STAT', $debug); //get params from $_GET or setup default value $payment_type = ((isset($_GET['payment']) &amp;&amp; !empty($_GET['payment'])))? $_GET['payment'] : 'fghue'; $currency = ((isset($_GET['currency']) &amp;&amp; !empty($_GET['currency'])))? $_GET['currency'] : 'GBP'; $type = ((isset($_GET['type']) &amp;&amp; !empty($_GET['type'])))? $_GET['type'] : 'O'; //get site id by site name $site_filter = array('siteone' =&gt; 30, 'site2' =&gt; 9, 'site3' =&gt; 12 ); $site_name = (isset($_GET['site']) &amp;&amp; !empty($_GET['site']))? $_GET['site'] : 'site1'; $site_id = (array_key_exists($site_name, $site_filter)) ? $site_filter[$site_name] : $site_filter['siteone']; //select statistic from period $period_time = array( 'start' =&gt; '2012-01-01', 'end' =&gt; '2012-03-31' ); ShowAdmHeader(); echo ("ver 1.4"); if ( defined('DEBUG_STAT') &amp;&amp; TRUE == DEBUG_STAT ) { echo "&lt;p&gt;" . $payment_type . "/" . $currency . "/" . $site_id . "/" . $site_name . "/" . $type ."&lt;/p&gt;"; } $sql = new SQL(); $dbc = new MYDB(); if(defined(DEBUG_STAT) === true) echo "&lt;p&gt;Create params array&lt;/p&gt;"; //Data to create query $params = array( 'payment' =&gt; $payment_type, 'currency' =&gt; $currency, 'type' =&gt; $type, 'site' =&gt; $site_name ); if(DEBUG_STAT) echo "&lt;p&gt;Try to get order message&lt;/p&gt;"; $res1 = get_order_message($sql, $dbc, $params, $site_id, $period_time); if(!is_array($res1) || empty($res1)) { trigger_error(__FUNCTION__.': Order message array is empty ', E_USER_WARNING); } $res2 = get_order_date($sql, $dbc, $params, $site_id, $period_time); if(!is_array($res2) || empty($res2)) { trigger_error(__FUNCTION__.': Order date array is empty ', E_USER_WARNING); } $explanations = array(); $output = array(); foreach ($res1 as $r) { $period = $r['period']; $msg = $r['msg']; $cnt = $r['cnt']; if ($r['CHARGED'] || $r['REFUNDED']) { $msg = 'Approved'; $cnt = intval($r['CHARGED']) + intval($r['REFUNDED']); } elseif (!$msg) continue; if (strpos($msg,"TRANSID=")===0) $msg = "{fraud filter}"; $index = $explanations[$msg]; if (!$index) { if ($msg) $explanations[$msg] = count($explanations)+1; $index = $explanations[$msg]; } if ($data[$period][$index]) $data[$period][$index] += $cnt; else $data[$period][$index] = $cnt; } $explanations['other'] = count($explanations) + 1; $index = $explanations['other']; foreach ($res2 as $r) { $period = $r['period']; $cnt = $r['cnt']; $data[$period][$index] = $cnt; } $cnt = count($explanations); $type_filter = array('A', 'O'); $out = get_filter_line($type_filter, $params, 'type'); print_out($out); $out = get_filter_line(array_flip($site_filter), $params, 'site'); print_out($out); $payment_filter = array('dkijhfw','fghue','sdgsdg','payspace'); $out = get_filter_line($payment_filter, $params, 'payment'); print_out($out); $currency_filter = array('GBP','USD','CAD','AUD','EUR','INR','ZAR'); $out = get_filter_line($currency_filter, $params, 'currency'); print_out($out); echo '&lt;hr&gt;'; echo '&lt;table&gt;&lt;tr&gt;&lt;td valign=top&gt;'; echo "&lt;table border='1'&gt;"; echo "&lt;tr&gt;&lt;td&gt;&amp;nbsp;&lt;/td&gt;"; for ($i=1;$i&lt;$cnt;$i++) { echo "&lt;td&gt;A&lt;small&gt;".($i)."&lt;/small&gt;&lt;/td&gt;"; } echo "&lt;/tr&gt;"; foreach ($data as $k=&gt;$r) { echo "&lt;tr&gt;&lt;td&gt;&lt;b&gt;".$k."&lt;/td&gt;"; for ($i=1;$i&lt;$cnt;$i++) { if ($r[$i]) { if ($i==1) $color = '&lt;font color="green"&gt;'; else $color = ''; echo "&lt;td&gt;".$color.$r[$i]."&lt;/td&gt;"; if ($i &gt; 1 &amp;&amp; $i&lt;$cnt) $r[$cnt] = $r[$cnt] - $r[$i]; } else echo "&lt;td&gt;&amp;nbsp;&lt;/td&gt;"; } echo "&lt;/tr&gt;"; } echo '&lt;/table&gt;'; echo '&lt;/td&gt;&lt;td valign="top"&gt;'; foreach ($explanations as $k=&gt;$v) { if ($v&lt;$cnt) echo "&lt;nobr&gt;A&lt;small&gt;".$v."&lt;/small&gt; - ".$k."&lt;/nobr&gt;&lt;br&gt;"; } echo '&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;'; ShowAdmFooter(); function get_filter_line(array $data, $params_get, $type ) { $out = null; //save current position value $current_position = $params_get[$type]; if(empty($data)) { trigger_error(__FUNCTION__.': Parameter $data is empty', E_USER_WARNING); return false; } foreach ($data as $value) { $params_get[$type] = $value; $url = http_build_query($params_get, '', '&amp;'); if ($current_position == $value) { //don't create link to current position $out .= "&lt;b style='margin-left:20px;'&gt;{$value}&lt;/b&gt;"; } else { $out .= "&lt;a style='margin-left:20px;' href=?{$url}&gt;{$value}&lt;/a&gt;"; } } return $out; } function print_out($data) { if(empty($data)) return; echo "&lt;div style='margin: 5px 0 5px 0;'&gt;"; echo $data; echo "&lt;/div&gt;"; } function get_url_params(array $params_get) { pr($params_get); $param = array(); foreach ($params_get as $param_name =&gt; $param_val) { if(empty($param_val)) { trigger_error(__FUNCTION__.": Parameter $param_name is empty", E_USER_WARNING); } $param[$param_name] = $param_val; } pr($param); return http_build_query($param, '', '&amp;'); } function get_order_date(SQL $sql, DatingDB $dbc, array $params, $site_id, array $period) { if(!isset($params['type']) || empty($params['type']) ) { trigger_error(__FUNCTION__.": Parameter type in params is empty", E_USER_WARNING); return false; } switch($params['type']) { case TYPE_A: if(DEBUG_STAT) echo "get sql by type A"; create_sql_type_repeat($sql); break; case TYPE_O: if(DEBUG_STAT) echo "get sql by type 0"; create_sql_type_first($sql); break; default: trigger_error(__FUNCTION__.": Parameter type in params has wrong value", E_USER_WARNING); return false; } sql_append_common_params($sql, $params['currency'], $site_id, $params['type'], $period['start'], $period['end']); if (isset($params['payment']) &amp;&amp; !empty($params['payment']) ) { $sql-&gt;append(" AND o.type_payment = :s:type_payment: ", array('type_payment' =&gt; $params['payment'])); } $sql-&gt;append(" GROUP BY period "); if(DEBUG_STAT) pr($sql-&gt;show()); $res = $dbc-&gt;GetAll(array("balancing_mode"=&gt;'secondary_slave'), $sql); return $res; } function create_sql_type_first(SQL $sql) { if(!($sql instanceof SQL)) { exit('sql in create_sql_type_first is not instanceof SQL'); trigger_error(__FUNCTION__.": Result of get_order_data_by_period() is empty", E_USER_WARNING); return false; } $sql-&gt;create(" SELECT date(tdate) as period, count(*) as cnt FROM orders o WHERE o.apr_code IS NOT NULL AND o.apr_code &lt;&gt; '' "); return true; } function create_sql_type_repeat(SQL $sql) { if(!($sql instanceof SQL)) { exit('sql in create_sql_type_repeat is not instanceof SQL'); trigger_error(__FUNCTION__.": Result of get_order_data_by_period() is empty", E_USER_WARNING); return false; } $sql-&gt;create(" SELECT date(tdate) as period, count(*) as cnt FROM orders o INNER JOIN repeat_scheduled rs ON (o.user_id = rs.pid AND rs.placed_on = date(o.tdate) AND o.id = rs.order_id_created) WHERE o.apr_code IS NOT NULL AND o.apr_code &lt;&gt; '' AND rs.is_retrying = 0 AND rs.status = 'FAILED' "); return true; } function sql_append_common_params(SQL $sql, $currency, $site_id, $type, $period_start, $period_end) { $arg_list = func_get_args(); for ($i = 1; $i &lt; count($arg_list); $i++) { if(empty($arg_list[$i])) { trigger_error(__FUNCTION__.": We don't have {$arg_list[$i]}", E_USER_WARNING); } } $sql-&gt;append(" AND o.currency = :s:currency: ", array('currency' =&gt; $currency.":1")); $sql-&gt;append(" AND o.siteID = :i:siteID: ", array('siteID' =&gt; $site_id)); $sql-&gt;append(" AND o.type = :s:type: ", array('type' =&gt; $type)); $sql-&gt;append(" AND DATE(o.tdate) BETWEEN :s:start: AND :s:end: ", array('start' =&gt; $period_start, 'end'=&gt; $period_end) ); return true; } function get_order_message(SQL $sql, DatingDB $dbc, array $params, $site_id, array $period_time) { if(DEBUG_STAT) echo "&lt;p&gt;Call get_order_message&lt;/p&gt;"; $type = $params['type']; $payment_type = $params['payment']; $currency = $params['currency']; switch($type) { case TYPE_A: if ($payment_type=='fghue') { $sql-&gt;create(" SELECT date(tdate) as period, sum(if(o.apr_code='CHARGED',1,0)) as 'CHARGED', sum(if(o.apr_code='REFUNDED',1,0)) as 'REFUNDED', SUBSTRING(note,LOCATE('&lt;resulttext&gt;',note)+LENGTH('&lt;resulttext&gt;'),LOCATE('&lt;/resulttext&gt;',note)-LOCATE('&lt;resulttext&gt;',note)-LENGTH('&lt;/resulttext&gt;')+1) as msg, count(*) as cnt FROM orders o INNER JOIN repeat_scheduled rs ON (o.user_id = rs.pid AND rs.placed_on = date(o.tdate) AND o.id = rs.order_id_created) WHERE o.type_payment = 'fghue' "); } elseif ($payment_type=='sdgsdg') { $sql-&gt;create(" SELECT date(tdate) as period, sum(if(o.apr_code='CHARGED',1,0)) as 'CHARGED', sum(if(o.apr_code='REFUNDED',1,0)) as 'REFUNDED', SUBSTRING(note,LOCATE('&lt;text&gt;',note)+LENGTH('&lt;text&gt;'),LOCATE('&lt;/text&gt;',note)-LOCATE('&lt;text&gt;',note)-LENGTH('&lt;/text&gt;')+1) as msg, count(*) as cnt FROM orders o INNER JOIN repeat_scheduled rs ON (o.user_id = rs.pid AND rs.placed_on = date(o.tdate) AND o.id = rs.order_id_created) WHERE o.type_payment = 'sdgsdg' "); } elseif ($payment_type=='dfg') { $sql-&gt;create(" SELECT date(tdate) as period, sum(if(o.apr_code='CHARGED',1,0)) as 'CHARGED', sum(if(o.apr_code='REFUNDED',1,0)) as 'REFUNDED', SUBSTRING(note,LOCATE('[transactionError]',note)+LENGTH('[transactionError]'),LOCATE('[transactionStatus]',note)-LOCATE('[transactionError]',note)-LENGTH('[transactionStatus]')+1) as msg, count(*) as cnt FROM orders o INNER JOIN repeat_scheduled rs ON (o.user_id = rs.pid AND rs.placed_on = date(o.tdate) AND o.id = rs.order_id_created) WHERE o.type_payment = 'dfg' "); } elseif ($payment_type=='dkijhfw') { $sql-&gt;create(" SELECT date(tdate) as period, sum(if(o.apr_code='CHARGED',1,0)) as 'CHARGED', sum(if(o.apr_code='REFUNDED',1,0)) as 'REFUNDED', LEFT(SUBSTRING(note,LOCATE(:s:t1:,note)+LENGTH(:s:t1:),LOCATE(:s:t2:,note)-LOCATE(:s:t1:,note)-LENGTH(:s:t2:)-1), 40) as msg, count(*) as cnt FROM orders o INNER JOIN repeat_scheduled rs ON (o.user_id = rs.pid AND rs.placed_on = date(o.tdate) AND o.id = rs.order_id_created) WHERE o.type_payment = 'dkijhfw'", array('t1' =&gt; 'REASON :: ', 't2' =&gt; 'ERRCODE ::') ); } else { die('Payment system does not supported by this report'); } sql_append_common_params($sql, $currency, $site_id, $type, $period_time['start'], $period_time['end']); $sql-&gt;append(" AND rs.is_retrying = :i:is_retrying: ", array('is_retrying' =&gt; 0)); $sql-&gt;append(" GROUP BY period, msg "); break; case TYPE_O: if ($payment_type=='fghue') { $sql-&gt;create(" SELECT date(tdate) as period, sum(if(o.apr_code='CHARGED',1,0)) as 'CHARGED', sum(if(o.apr_code='REFUNDED',1,0)) as 'REFUNDED', SUBSTRING(note,LOCATE('&lt;resulttext&gt;',note)+LENGTH('&lt;resulttext&gt;'),LOCATE('&lt;/resulttext&gt;',note)-LOCATE('&lt;resulttext&gt;',note)-LENGTH('&lt;/resulttext&gt;')+1) as msg, count(*) as cnt FROM orders o WHERE o.type_payment = 'fghue' "); } elseif ($payment_type=='sdgsdg') { $sql-&gt;create(" SELECT date(tdate) as period, sum(if(o.apr_code='CHARGED',1,0)) as 'CHARGED', sum(if(o.apr_code='REFUNDED',1,0)) as 'REFUNDED', SUBSTRING(note,LOCATE('&lt;text&gt;',note)+LENGTH('&lt;text&gt;'),LOCATE('&lt;/text&gt;',note)-LOCATE('&lt;text&gt;',note)-LENGTH('&lt;/text&gt;')+1) as msg, count(*) as cnt FROM orders o WHERE o.type_payment = 'sdgsdg' "); } elseif ($payment_type=='sdgasdg') { $sql-&gt;create(" SELECT date(tdate) as period, sum(if(o.apr_code='CHARGED',1,0)) as 'CHARGED', sum(if(o.apr_code='REFUNDED',1,0)) as 'REFUNDED', SUBSTRING(note,LOCATE('[transactionError]',note)+LENGTH('[transactionError]'),LOCATE('[transactionStatus]',note)-LOCATE('[transactionError]',note)-LENGTH('[transactionStatus]')+1) as msg, count(*) as cnt FROM orders o WHERE o.type_payment = 'sdgasdg' "); } elseif ($payment_type=='dkijhfw') { $sql-&gt;create(" SELECT date(tdate) as period, sum(if(o.apr_code='CHARGED',1,0)) as 'CHARGED', sum(if(o.apr_code='REFUNDED',1,0)) as 'REFUNDED', LEFT(SUBSTRING(note,LOCATE(:s:t1:,note)+LENGTH(:s:t1:),LOCATE(:s:t2:,note)-LOCATE(:s:t1:,note)-LENGTH(:s:t2:)-1), 40) as msg, count(*) as cnt FROM orders o WHERE o.type_payment = 'dkijhfw'", array('t1' =&gt; 'REASON :: ', 't2' =&gt; 'ERRCODE ::') ); } else { die('Payment system does not supported by this report'); } sql_append_common_params($sql, $currency, $site_id, $type, $period_time['start'], $period_time['end']); $sql-&gt;append(" GROUP BY period, msg "); break; default: exit('Wrong payment type'); } if(DEBUG_STAT) { pr($sql-&gt;show()); } $res = $dbc-&gt;GetAll(array("balancing_mode"=&gt;'secondary_slave', 'cache'=&gt;true, 'lifetime'=&gt;3600), $sql); return $res; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T17:28:17.653", "Id": "17322", "Score": "1", "body": "I'm not even attempting to review uncommented code." } ]
[ { "body": "<p>I'll be honest, I just skimmed most of this. As GordonM said, it really should be commented, especially for such a large procedural file. If you are still watching this thread, here are a few things to look into.</p>\n\n<p><strong>WARNING</strong> Large wall of text ahead! <strong>WARNING</strong></p>\n\n<p><strong>Code Separation</strong></p>\n\n<p>This file is LARGE. Not in size, but in function. You should really think about separating your code into logical parts, before, after, and during the coding process. Separating the HTML from the PHP isn't just good practice, its easier to read and will allow others with less programming knowledge, such as designers, to work on the project with you. Some may argue that this is just a preference, but I'd argue its almost a necessity. <strong>Extending this advice:</strong> This also works for separating parts of code. If you are doing a form, create a new PHP file for form processing. Don't lump all your code into one file just because they do similar things. Even if you only separate your functions from your procedural code you will notice immediate results.</p>\n\n<p><strong>Using Functions</strong></p>\n\n<p>Using functions, properly, goes hand-in-hand with code separation, but deserves its own section. You have the right idea, but you can do so much more with your functions. You don't have to do everything within the same function, just as you don't have to do everything within the same file. Think of it as a small step on the way to code separation. Break everything down into reusable parts and make functions out of them.</p>\n\n<p>Take a look at your <code>get_order_message</code> function. You use very similar code blocks throughout that entire function. I didn't read every single line, but from what I gather there are only 2 real changes between each <code>$sql-&gt;create()</code> calls. Create another function to do those SQL calls and pass the right variables and SQL string parts. After you've done that you'll notice a hefty chunk has been taken out of your code. Take a look at your <code>get_order_message</code> after adding said function. There are still some things that still need to be changed, but this will get you started.</p>\n\n<pre><code>function sqlCreate($substring, $type) {\n $sql-&gt;create(\"\n SELECT\n date(tdate) as period, \n sum(if(o.apr_code='CHARGED',1,0)) as 'CHARGED', \n sum(if(o.apr_code='REFUNDED',1,0)) as 'REFUNDED', \n SUBSTRING(note, $substring +1) as msg,\n count(*) as cnt \n FROM\n orders o\n INNER JOIN\n repeat_scheduled rs ON (\n o.user_id = rs.pid AND rs.placed_on = date(o.tdate) AND o.id = rs.order_id_created\n ) \n WHERE\n o.type_payment = $type \n \");\n\n}\n\nfunction get_order_message() {\n sqlCreate(\n \"LOCATE('&lt;resulttext&gt;',note)+LENGTH('&lt;resulttext&gt;'),LOCATE('&lt;/resulttext&gt;',note)-LOCATE('&lt;resulttext&gt;',note)-LENGTH('&lt;/resulttext&gt;')\",\n $payment_type\n );\n}\n</code></pre>\n\n<p>Go wild with it, get your code as reusable as possible. While not always practical it will get you in the right mindset. Reusable is better. Not just for OOP, but for procedural programming as well. The less you have to type, the better and the less you have to type the less you will have to update and maintain.</p>\n\n<p><strong>Using Loops</strong></p>\n\n<p>Don't be afraid of loops either (for, while, foreach, etc...). You have multiple instances where you could replace a large chunk of code with just a few lines and be done. Not to mention this makes your code extendable. This is just an example:</p>\n\n<pre><code>/*This...\n$payment_type = ((isset($_GET['payment']) &amp;&amp; !empty($_GET['payment'])))? $_GET['payment'] : 'fghue';\n$currency = ((isset($_GET['currency']) &amp;&amp; !empty($_GET['currency'])))? $_GET['currency'] : 'GBP';\n$type = ((isset($_GET['type'])\ncan be converted to this with just a few tweaks...*/\n$paymentInfo = array(\n 'payment' =&gt; '',\n 'currentcy' =&gt; '',\n 'type' =&gt; ''\n);\nforeach(array_keys($paymentInfo) as $key) { $paymentInfo[$key] = $_GET[$key]; }\n</code></pre>\n\n<p><strong>Ternary Operators</strong></p>\n\n<p>Ternary operators are good so long as they are understandable. Once they start getting too bulky they lose their legibility and usefulness. If you wish to use ternary operators, you should start condensing where you can. That is, after all, the whole point of using them in the first place. You can start with those <code>$_GET</code> calls.</p>\n\n<pre><code>function filter($var, $default = FALSE) {\n return (isset($_GET[$var]) &amp;&amp; ! empty($_GET[$var]) ? $_GET[$var] : $default);\n}\n\n$payment_type = filter('payment', 'fghue');\n</code></pre>\n\n<p>See how I slipped a function in there? Just abstracting it that much made that ternary operation so much easier to read.</p>\n\n<p>But you can do more. If your PHP version is 5.2 or greater you can just use the <code>filter_input()</code> method. It is a PHP function that does exactly what you are already doing, plus more. If there is a value to return it will return it based on the filter flags you provide, otherwise it will return FALSE. Of course, just using <code>filter_input</code> by itself wont be much shorter than what you already have, but combine that with the function I gave you above and:</p>\n\n<pre><code>function filter($var, $flags = null) {\n $method = array(\n 'get' =&gt; INPUT_GET,\n 'post' =&gt; INPUT_POST,\n );\n $filter = array(\n 'string' =&gt; FILTER_SANITIZE_STRING | FILTER_SANITIZE_STRIPPED,\n 'int' =&gt; FILTER_VALIDATE_INT,\n );\n\n if( ! $flags) {\n $filterType = $filter['string'];\n $methodType = $method['get'];\n } else {\n extract($flags);//sets $filterType and $methodType\n $filterType = $filter[$filterType];\n $methodType = $method[$methodType];\n }\n return filter_input($methodType, $var, $filterType);\n}\n\n$flags = array(\n 'filterType' =&gt; 'string',\n 'methodType' =&gt; 'get'\n);\n$payment_type = filter('payment');//with defaults\n$payment_type = filter('payment', $flags);//with custom settings\n\n//If you want to check if it was set to give it a default value...\n$payment_type = $payment_type ?: 'fghue';//PHP 5.3 and later can use ternary shorthand \"?:\"\n$payment_type = $payment_type ? $payment_type : 'fghue';//Older cannot\n</code></pre>\n\n<p><strong>Magic Values/Variables</strong></p>\n\n<p>All those random strings <code>fghue</code> are what I mean by \"magic\". They came out of no where and mean absolutely nothing to a majority of us. And in a year when you are looking back on this project it may not mean anything to you either. Make life simpler by telling us what those strings are. Its called self-documenting code and makes reading your code easier. While this may make your code larger, it will be for the right reasons. No one is going to complain about you making your code more legible, in fact many programmers might just break into sobs of joy.</p>\n\n<pre><code>define('descriptive_name', 'fghue');//if the name isn't enough add a comment\n//etc...\n$payment_type = $payment_type ?: descriptive_name;\n</code></pre>\n\n<p><strong>HTML Output</strong></p>\n\n<p>Don't echo HTML output unless absolutely necessary. In case you are confused, its only necessary when you need to use PHP variables in it, and not always then. This is another one of those \"Separation of Code\" things. You retain tag highlighting and autocompletion features as well as other benefits. If you MUST echo HTML output try to use heredoc as it is still more readable than other alternatives.</p>\n\n<pre><code> echo &lt;&lt;&lt;HTML\n&lt;a href=\"$href\"&gt;$link&lt;/a&gt;\n&lt;$tag&gt;asdf&lt;/$tag&gt;\nHTML;//notice this closure element is not indented\n</code></pre>\n\n<p>Much better to just escape from PHP and then enter back in to echo a single variable if you can.</p>\n\n<pre><code>... ?&gt;\n&lt;a href=\"&lt;?php echo $href; ?&gt;\"&gt;&lt;?php echo $link; ?&gt;&lt;/a&gt;\n&lt;?php ...\n</code></pre>\n\n<p><strong>Discalimer: Convert it to a Class</strong></p>\n\n<p><strong>Don't!</strong> No matter what anyone else says, don't do it. Don't worry, I'm not against OOP and I'm not trying to steer you wrong. I'm trying to save you a lot of heartache and frustration. You obviously aren't ready for OOP quite yet. Don't take that the wrong way, I'm still struggling with it myself. It takes quite a bit of practice, and before you can get started you have to know your basics. Take it slow. Don't immediately jump into converting all your PHP files into classes because someone told you it was better. You'll only give yourself a headache and discourage yourself. I hated seeing answers like that when browsing forums and I'll never give that advice to anyone because of it. Don't get me wrong, OOP is definately a life saver and something you should eventually look into, but you should be comfortable and proficient with procedural programming first. The only reason I mentioned this at all is because of how likely it is that you WILL receive this \"advice\" from someone at some point. Just go on ignoring them until you are ready to tackle it on your own.</p>\n\n<p><strong>Conclusion</strong></p>\n\n<p>I hope these suggestions helped and that I didn't go off on too much of a tangeant or lose you somewhere. I kind of got carried away. Ask questions, not just here, but on other forums as well, thats how we learn :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-19T21:04:06.020", "Id": "11022", "ParentId": "10886", "Score": "5" } }, { "body": "<p>@mseancole answer covers quite a lot, but one security issue wasn't mentioned, so I'll mention it here:</p>\n\n<p>Your code is vulnerable to XSS, eg via</p>\n\n<pre><code>/script.php?debug=1&amp;payment=&lt;script&gt;alert(1)&lt;/script&gt;\n</code></pre>\n\n<p>Whenever you echo variables that contain non-hardcoded data supplied by non-priviledged entities (eg direct user input, stuff from the database - which is also ultimately user input, etc), you should encode relevant characters via</p>\n\n<pre><code>htmlspecialchars($variable, ENT_QUOTES, 'UTF-8');\n</code></pre>\n\n<p>If you don't do this, an attacker can inject a javascript key logger, perform phishing attacks, bypass CSRF protection and thus do anything the user can do, steal cookies, etc. It only requires the victim to click on a link or visit a website where the attacker can post javascript code. All this will happen in the background, so the victim will not be aware of any of it happening.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-25T18:32:21.523", "Id": "94685", "ParentId": "10886", "Score": "1" } }, { "body": "<pre><code>$debug = (isset($_GET['debug']) &amp;&amp; !empty($_GET['debug']))? $_GET['debug'] : false;\n</code></pre>\n\n<p>is the same as</p>\n\n<pre><code>$debug = !empty ($_GET['debug']) ? $ $_GET['debug'] : false;\n</code></pre>\n\n<p>because <code>empty</code> has an <code>isset</code> call internally.</p>\n\n<pre><code>if(defined(DEBUG_STAT) === true)\n</code></pre>\n\n<p><code>defined</code> only returns a bool, so removing <code>=== true</code> does the same thing.</p>\n\n<p>Always add braces to <code>if</code>s. There's really no reason not to.</p>\n\n<p>Always be consistent. For example, you have different brace styles between</p>\n\n<pre><code>if(!is_array($res1) || empty($res1)) { \n trigger_error(__FUNCTION__.': Order message array is empty ', E_USER_WARNING); \n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>if ($r['CHARGED'] || $r['REFUNDED'])\n{\n $msg = 'Approved';\n $cnt = intval($r['CHARGED']) + intval($r['REFUNDED']);\n}\n</code></pre>\n\n<p>If you're unsure, follow a standard (<a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md\" rel=\"nofollow\">PSR-2</a> is good)</p>\n\n<p>Separate the PHP and HTML, or use Twig. For example, this:</p>\n\n<pre><code>echo '&lt;hr&gt;';\n\necho '&lt;table&gt;&lt;tr&gt;&lt;td valign=top&gt;';\n\n echo \"&lt;table border='1'&gt;\";\n echo \"&lt;tr&gt;&lt;td&gt;&amp;nbsp;&lt;/td&gt;\";\n for ($i=1;$i&lt;$cnt;$i++)\n {\n echo \"&lt;td&gt;A&lt;small&gt;\".($i).\"&lt;/small&gt;&lt;/td&gt;\";\n }\n</code></pre>\n\n<p>shouldn't exist.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-25T21:42:37.183", "Id": "94697", "ParentId": "10886", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T10:38:21.433", "Id": "10886", "Score": "1", "Tags": [ "php" ], "Title": "PHP report from order table" }
10886
<p>I am very new to Objective-C as well as objected oriented programming, and in a book I am studying from there is an exercise in which I was supposed to create a class called <code>Rational</code>, that has hidden data members called numerator and denominator, and methods to add, multiply, subtract and divide the Rational objects (the objects are just fractions) together. For some reason when I run the program it becomes extremely slow when calculating. I am using ARC on X-Code, and I am wondering if it has to do with memory management issues.</p> <p>Here is the .m file of the class:</p> <pre><code>#import "Rational.h" @interface Rational (privateMethods) -(int) gcd:(int) a: (int) b; -(Rational*) simplifyFraction:(Rational*)fraction; @end @implementation Rational @synthesize numerator, denominator; -(Rational*) multiplyFraction:(Rational *)fraction1 :(Rational *)fraction2{ fraction1.numerator = fraction1.numerator * fraction2.numerator; fraction1.denominator = fraction1.denominator * fraction2.denominator; fraction1 = [self simplifyFraction:fraction1]; return fraction1; } -(Rational*) addFraction:(Rational *)fraction1 :(Rational *)fraction2{ Rational * returnFraction = [[Rational alloc] init]; fraction1.numerator = fraction1.numerator*fraction2.denominator; fraction2.numerator = fraction2.numerator *fraction1.denominator; fraction1.denominator = fraction1.denominator*fraction2.denominator; fraction2.denominator = fraction1.denominator; returnFraction.numerator = fraction1.numerator + fraction2.numerator; returnFraction.denominator = fraction1.denominator; returnFraction = [self simplifyFraction:returnFraction]; return returnFraction; } -(Rational*) subtractFraction:(Rational *)fraction1 :(Rational *)fraction2{ Rational * returnFraction = [[Rational alloc] init]; fraction1.numerator = fraction1.numerator*fraction2.denominator; fraction2.numerator = fraction2.numerator *fraction1.denominator; fraction1.denominator = fraction1.denominator*fraction2.denominator; fraction2.denominator = fraction1.denominator; returnFraction.numerator = fraction1.numerator - fraction2.numerator; returnFraction.denominator = fraction1.denominator; returnFraction = [self simplifyFraction:returnFraction]; return returnFraction; } -(Rational*) divideFraction:(Rational *)fraction1 :(Rational *)fraction2{ Rational * returnFraction = [[Rational alloc] init]; const int temp = fraction2.denominator; fraction2.denominator = fraction2.numerator; fraction2.numerator = temp; returnFraction.numerator = fraction1.numerator * fraction2.numerator; returnFraction.denominator = fraction2.denominator * fraction1.denominator; returnFraction = [self simplifyFraction:returnFraction]; return returnFraction; } -(void) printObject:(Rational *)fraction{ printf("%i/%i",fraction.numerator, fraction.denominator); printf("\n"); } -(void) printRoundedFloat:(Rational *)fraction{ float number = (float)fraction.numerator/fraction.denominator; printf("%f", number); printf("\n"); } -(int)gcd:(int)a :(int)b{ if (b==0) { return a; } else return [self gcd:b :a%b]; } -(Rational*) simplifyFraction:(Rational *)fraction{ if (fraction.denominator == 0) { NSLog(@"ERROR: YOU CAN NOT HAVE ZERO IN THE DENOMINATOR"); } else{ int i = fraction.numerator &gt; fraction.denominator ? fraction.numerator:fraction.denominator; while (i&gt;1) { if (fraction.numerator % i == 0 &amp;&amp; fraction.denominator%i==0) { fraction.numerator/=i; fraction.denominator/=i; } --i; } } return fraction; } -(void) dealloc{ } @end </code></pre> <p>Here is the Main.m file of the program:</p> <pre><code>import &lt;Foundation/Foundation.h&gt; import "Rational.h" int main (int argc, const char * argv[]) { @autoreleasepool { Rational * newFraction = [[Rational alloc] init]; Rational * otherFraction = [[Rational alloc] init]; newFraction.numerator = 1; newFraction.denominator = 25; printf("Fraction 1 is: "); [newFraction printObject:newFraction]; otherFraction.numerator = 1; otherFraction.denominator = 5; printf("Fraction 2 is: "); [otherFraction printObject:otherFraction]; printf("\nThe Fractions Added togeher are: "); id number = [newFraction addFraction:newFraction :otherFraction]; [number printObject:number]; printf("Rounded: "); [number printRoundedFloat:number]; printf("\nThe Fractions subtracted are: "); number = [number subtractFraction:newFraction :otherFraction]; [number printObject:number]; printf("Rounded: "); [number printRoundedFloat:number]; printf("\nThe Fractions multiplied are: "); number = [number multiplyFraction:newFraction :otherFraction]; [number printObject:number]; printf("Rounded: "); [number printRoundedFloat:number]; printf("\nThe Fractions divided are: "); number = [number divideFraction:newFraction :otherFraction]; [number printObject:number]; printf("Rounded: "); [number printRoundedFloat:number]; } return 0; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T03:08:14.117", "Id": "17314", "Score": "2", "body": "Memory management *could* be the issue here; but can you give us a clear definition of what you mean by 'it becomes extremely slow'. Is this during the first pass, just in specific messages, do you have to run it a few times ? Also, perhaps try just disabling arc and see what that does ? This question has instructions on how to do this: http://stackoverflow.com/questions/7837024/how-to-disable-xcode4-2-automatic-reference-counting" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T12:59:50.247", "Id": "17315", "Score": "0", "body": "Each method runs fine individually, but when I call them all in the main, it takes about 2 seconds for both the multiplication and division to compute.. I've tried disabling arc and adding release statements, but it is still slow. I also tried it on another computer to assure it is not a hardware issue. It seems strange to take so long since the program is so small.." } ]
[ { "body": "<p>I just had a flash of inspiration, although possibly not related.</p>\n\n<p>What happens if you change this method signature:</p>\n\n<pre><code>-(void) printObject:(Rational *)fraction{\n\n printf(\"%i/%i\",fraction.numerator, fraction.denominator);\n\n printf(\"\\n\");\n}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>-(void) printObject\n{\n printf(\"%i/%i\",self.numerator, self.denominator);\n\n printf(\"\\n\");\n}\n</code></pre>\n\n<p>And then</p>\n\n<pre><code>[newFraction printObject:newFraction];\n</code></pre>\n\n<p>to</p>\n\n<pre><code>[newFraction printObject];\n</code></pre>\n\n<p>And so on...</p>\n\n<p>Seems odd that you're passing the object to a message that belongs to the object you're passing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T18:31:43.053", "Id": "17316", "Score": "0", "body": "Although this didn't speed it up at all, I really appreciate this. I am new to OOP, and your code helped me understand the concept of self a lot better. I didn't realize that self would refer to the object that had been initialized. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T15:54:02.680", "Id": "17385", "Score": "2", "body": "In fact the original form of the method did not use self at all so should have been a class method. However, rather than having a method called `printObject` why not override `description`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T02:48:35.073", "Id": "103121", "Score": "0", "body": "We really shouldn't be printing objects. JeremyP is right--the correct solution is overriding `description`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T17:07:31.697", "Id": "10888", "ParentId": "10887", "Score": "1" } }, { "body": "<p>You shouldn't be modifying the objects passed to the methods. If the user does not expect this, it could cause strange behavior later.</p>\n\n<pre><code>-(void) addFraction:(Rational *)fraction1 :(Rational *)fraction2\n{\n const int num1 = fraction1.numerator * fraction2.denominator;\n const int num2 = fraction2.numerator * fraction1.denominator;\n\n self.numerator = num1 + num2;\n self.denominator = fraction1.denominator * fraction2.denominator;\n\n [self simplifyFraction:self];\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-29T12:19:54.040", "Id": "14118", "ParentId": "10887", "Score": "1" } }, { "body": "<p>One thing to note here is that for some reason you coded up a <code>gcd</code> function, but do not utilize it in your <code>simplifyFraction</code> method.</p>\n\n<p>By definition of gcd, it returns the greatest common divisor. Therefore, to simplify a fraction, you need simply to divide both the numerator and denominator by the gcd(numerator, denominator).</p>\n\n<p>This would simplify your code a bit, make it more readable, and probably increase its speed.</p>\n\n<p>Also, your division method is only made more complicated by having code such as:</p>\n\n<pre><code>returnFraction.numerator = fraction1.numerator * fraction2.numerator;\n</code></pre>\n\n<p>when intuitively it should be:</p>\n\n<pre><code>returnFraction.numerator = fraction1.numerator * fraction2.denominator;\n</code></pre>\n\n<p>I would eliminate the temp variable and essentially duplicate the style of the multiplication method to fix this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T00:47:20.470", "Id": "57629", "ParentId": "10887", "Score": "3" } }, { "body": "<pre><code>@interface Rational (privateMethods)\n\n-(int) gcd:(int) a: (int) b;\n-(Rational*) simplifyFraction:(Rational*)fraction;\n\n@end\n</code></pre>\n\n<p>This really should be a class extension rather than a private category. A class extension means leaving the parenthesis out, and perhaps more importantly it means if we add a method to the interface here and don't implement it, the IDE will give us a warning. Although honestly, it probably simply shouldn't exist at all--and we don't even necessarily need to declare the methods here even.</p>\n\n<p>The <code>gcd</code> function, which should be named <code>greatestCommonDenominator</code> instead, isn't necessarily specific to fractions. It can exist as a regular C function outside the class. And honestly, I don't have a problem with exposing the function in the header file.</p>\n\n<p>Anyway, to make it a regular C-function outside the class, just remove all of the existing stuff outside the <code>@interface</code> and <code>@implementation</code> sections, and write the function as such (above the <code>@interface</code>):</p>\n\n<pre><code>int greatestCommonDenominator(int a, int b) {\n if (b==0) {\n return a;\n } else {\n return greatestCommonDenominator(b, a%b);\n }\n}\n</code></pre>\n\n<hr>\n\n<p>The other method, <code>simplifyFraction:</code>, shouldn't take an argument. Instead, it should simplify <code>self</code>... the instance which called the method.</p>\n\n<p>In fact, this logic should be applied to almost every method in your class. Our instances methods should use <code>self</code> in some way. If we're not using <code>self</code>, it should be a class method.</p>\n\n<hr>\n\n<pre><code>-(void) printObject:(Rational *)fraction{\n\n printf(\"%i/%i\",fraction.numerator, fraction.denominator);\n\n printf(\"\\n\");\n}\n\n-(void) printRoundedFloat:(Rational *)fraction{\n\n float number = (float)fraction.numerator/fraction.denominator;\n\n printf(\"%f\", number);\n\n printf(\"\\n\");\n}\n</code></pre>\n\n<p>It's a pretty hard and fast rule in OOP that objects shouldn't \"print\" themselves. Instead, we return a string, and let whoever is using the object do with that string whatever it wants. Both of these methods should be removed, and instead, we can offer:</p>\n\n<pre><code>- (NSString *)description {\n return [NSString stringWithFormat:@\"%i/%i\", self.numerator, self.denominator];\n}\n</code></pre>\n\n<p>And rather than returning some special format for the string representation of the float value, why don't we just turn it into a float value and return that value?</p>\n\n<pre><code>- (float)floatValue {\n return (float)self.numerator/(float)self.denominator;\n}\n</code></pre>\n\n<p>We can also do this for <code>double</code>, and potentially for integer values as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T02:45:05.237", "Id": "57636", "ParentId": "10887", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T02:59:51.773", "Id": "10887", "Score": "5", "Tags": [ "performance", "beginner", "object-oriented", "objective-c", "rational-numbers" ], "Title": "Rational class to handle fractions" }
10887
<p>Can someone please critique my C++ sample here?</p> <pre><code>#include &lt;iostream&gt; //console io #include &lt;string&gt; //string handling #include &lt;algorithm&gt; //transform using namespace std; struct to_upper { int operator() (int ch) { return toupper(ch); } }; void encrypt_vigenere(const string&amp; plaintext, const string&amp; key, string&amp; ciphertext){ int i, j, ch; for(i = 0, j = 0; i &lt; plaintext.length(); ++i, j++) { if(j &gt;= key.length()) j = 0; if(plaintext[i] &gt;= 'A' &amp;&amp; plaintext[i] &lt;= 'Z') ch = ((plaintext[i] - 'A') + (key[j] - 'A')) % 26; else ch = plaintext[i] - 'A'; //only encrypt A-Z ciphertext.append(string(1, (char)(ch + 'A'))); } } void decrypt_vigenere(const string&amp; ciphertext, const string&amp; key, string&amp; plaintext){ int i, j, ch; for(i = 0, j = 0; i &lt; ciphertext.length(); ++i, j++) { if(j &gt;= key.length()) j = 0; if(ciphertext[i] &gt;= 'A' &amp;&amp; ciphertext[i] &lt;= 'Z') ch = ((ciphertext[i] - 'A') + 26 - (key[j] - 'A')) % 26; else ch = ciphertext[i] - 'A'; //only decrypt A-Z plaintext.append(string(1, (char)(ch + 'A'))); } } int main(int argc, char* argv[]) { cout &lt;&lt; "Enter plaintext to encrypt:\n"; char plaintext[256] = {0}; char key[256] = {0}; cin.getline (plaintext,256); cout &lt;&lt; "Text to encrypt: " &lt;&lt; plaintext &lt;&lt; endl; cin.clear(); //clears any cin errors cout &lt;&lt; "Enter key (can be any string):"; cin.getline (key, 256); //uppercase KEY transform(key, key+strlen(key), key, to_upper()); cout &lt;&lt; "key chosen: " &lt;&lt; key &lt;&lt; endl; string cipher; //uppercase plaintext transform(plaintext, plaintext+strlen(plaintext), plaintext, to_upper()); encrypt_vigenere(plaintext, key, cipher); string decrypted; decrypt_vigenere(cipher, key, decrypted); cout &lt;&lt; "Vigenere encrypted text: " &lt;&lt; cipher &lt;&lt; " decrypted: " &lt;&lt; decrypted &lt;&lt; endl; return 0; } </code></pre>
[]
[ { "body": "<p><em><strong>Return Values</em></strong></p>\n\n<p>I would modify the encrypt and decrypt functions to return a string value rather than take a string reference.</p>\n\n<p>From a design point of view this bring several advantages:</p>\n\n<ol>\n<li>It never makes more sense to use the reference to provide any input other than the empty string, so I would codify this in the parameter list.</li>\n<li>Any compiler worth its salt will apply a <a href=\"http://en.wikipedia.org/wiki/Return_value_optimization\" rel=\"nofollow\">return value optimization</a>, so there should be no performance hit.</li>\n<li>It de-clutters the call site and improves readability.</li>\n</ol>\n\n<p><em><strong>String Concatenation</em></strong></p>\n\n<p>Prefer</p>\n\n<pre><code>ciphertext += (char)(ch + 'A');\n</code></pre>\n\n<p>over</p>\n\n<pre><code>ciphertext.append(string(1, (char)(ch + 'A')));\n</code></pre>\n\n<p>For any reasonable implementation, there should be no performance difference.</p>\n\n<hr>\n\n<p>Here's the amended code:</p>\n\n<pre><code>string encrypt_vigenere(const string&amp; plaintext, const string&amp; key){\n string ciphertext;\n int i, j, ch;\n for(i = 0, j = 0; i &lt; plaintext.length(); ++i, j++) {\n if(j &gt;= key.length()) \n j = 0;\n if(plaintext[i] &gt;= 'A' &amp;&amp; plaintext[i] &lt;= 'Z')\n ch = ((plaintext[i] - 'A') + (key[j] - 'A')) % 26;\n else\n ch = plaintext[i] - 'A'; //only encrypt A-Z\n ciphertext += (char)(ch + 'A');\n }\n return ciphertext;\n}\n\nstring decrypt_vigenere(const string&amp; ciphertext, const string&amp; key){\n string plaintext;\n int i, j, ch;\n for(i = 0, j = 0; i &lt; ciphertext.length(); ++i, j++) {\n if(j &gt;= key.length()) \n j = 0;\n\n if(ciphertext[i] &gt;= 'A' &amp;&amp; ciphertext[i] &lt;= 'Z')\n ch = ((ciphertext[i] - 'A') + 26 - (key[j] - 'A')) % 26;\n else\n ch = ciphertext[i] - 'A'; //only decrypt A-Z\n\n plaintext += (char)(ch + 'A');\n }\n return plaintext;\n}\n\n\nint main(int argc, char* argv[])\n{\n cout &lt;&lt; \"Enter plaintext to encrypt:\\n\";\n char plaintext[256] = {0};\n char key[256] = {0};\n cin.getline (plaintext,256);\n cout &lt;&lt; \"Text to encrypt: \" &lt;&lt; plaintext &lt;&lt; endl;\n\n cin.clear(); //clears any cin errors \n\n cout &lt;&lt; \"Enter key (can be any string):\";\n\n cin.getline (key, 256);\n\n //uppercase KEY\n transform(key, key+strlen(key), key, to_upper());\n\n cout &lt;&lt; \"key chosen: \" &lt;&lt; key &lt;&lt; endl;\n\n transform(plaintext, plaintext+strlen(plaintext), plaintext, to_upper());\n string cipher = encrypt_vigenere(plaintext, key);\n\n string decrypted = decrypt_vigenere(cipher, key);\n\n cout &lt;&lt; \"Vigenere encrypted text: \" &lt;&lt; cipher &lt;&lt; \" decrypted: \" &lt;&lt; decrypted &lt;&lt; endl;\n\n return 0;\n}\n</code></pre>\n\n<hr>\n\n<p>On a more minor note, I'm not a big fan of this comment:</p>\n\n<pre><code>//uppercase KEY\ntransform(key, key+strlen(key), key, to_upper());\n</code></pre>\n\n<p>The comments should explain the why, not the what (which is already self evident). I would prefer a comment explaining why you always return the uppercase of the key and cipher.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T01:03:34.153", "Id": "17343", "Score": "0", "body": "In the line `transform(key, key+strlen(key), key, to_upper())` `to_upper()` will cause a syntax error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T09:03:32.627", "Id": "17349", "Score": "1", "body": "@afishwhoswimsaround No syntax error there, `to_upper` is a struct in the asker's code (Which happens to be a functor struct), so `to_upper()` will create a temporary default-constructed to_upper object" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T10:17:20.913", "Id": "17350", "Score": "0", "body": "You are right, I missed that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T20:04:55.617", "Id": "10895", "ParentId": "10894", "Score": "10" } }, { "body": "<h3>General Coding Style</h3>\n\n<p>Please don't do this:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>I know every C++ books starts with this line. Fine it works for ten line programs they show in books. But when you start writing real programs this becomes a pain because of the clashes it can introduces as a result real programs will not have this in them. So get used to not using it.</p>\n\n<p>There are a couple of alternatives:</p>\n\n<ul>\n<li>Prefix everything with std::</li>\n<li>Use the <code>using</code> declaration to bring specific types/objects from a namespace\n<ul>\n<li>Be selective and bind them as tight as you can.</li>\n</ul></li>\n</ul>\n\n<p>There is already a toupper() defined by the standard (and you are using it).</p>\n\n<pre><code>struct to_upper {\n int operator() (int ch)\n {\n return toupper(ch);\n }\n};\n</code></pre>\n\n<p>Just use that in your transform (note you will need to specify ::toupper).</p>\n\n<pre><code> std::transform(begin, end, dst, ::toupper);\n</code></pre>\n\n<p>One variable per line:</p>\n\n<pre><code>int i, j, ch;\n</code></pre>\n\n<p>And make them readable (you don't need to obtuse and make them 100 characters) but one character variables are a pain when you are trying to spot all their uses in you code. Also note You can declare loop variables as part of the for(). Declare your variables as close to the use point as you can.</p>\n\n<p>Be consistent in your usage:</p>\n\n<pre><code>for(i = 0, j = 0; i &lt; plaintext.length(); ++i, j++) {\n</code></pre>\n\n<p>Why is it <code>++i</code> yet you use <code>j++</code>. It makes me look at the code to see if there is something special I should notice (there does not seem to be). So you are wasting my time makeing me thing why is he doing that.</p>\n\n<p>Personally (and this is just a thing I would do you can take it or leave it). I would replace this:</p>\n\n<pre><code> if(j &gt;= key.length()) \n j = 0;\n</code></pre>\n\n<p>With (obviously removing it from the for() aswell):</p>\n\n<pre><code> // Increment and wrap `j`\n j = (j + 1) % key.length();\n</code></pre>\n\n<p>Pretty sure you de-crypt is not working.</p>\n\n<pre><code> if(plaintext[i] &gt;= 'A' &amp;&amp; plaintext[i] &lt;= 'Z')\n ch = ((plaintext[i] - 'A') + (key[j] - 'A')) % 26;\n else\n ch = plaintext[i] - 'A'; //only encrypt A-Z\n ciphertext.append(string(1, (char)(ch + 'A')));\n</code></pre>\n\n<p>If you are going to read user input then use a std::string. It works in exactly the same way and makes things easier (you don't need to detect and fix very long strings).</p>\n\n<pre><code>char plaintext[256] = {0};\ncin.getline (plaintext,256);\n\n// Easier as\n\nstd::string plaintext;\nstd::getline(std::cin, plaintext);\n</code></pre>\n\n<p>Again declare your variables as close to the point you are going to use them. Don't get trapped in the C style of putting the variables at the top of the function.</p>\n\n<p>OK. So you clear the error state.</p>\n\n<pre><code>cin.clear(); //clears any cin errors \n</code></pre>\n\n<p>But you don't really do anything about it.<br>\nThis gives you a false sense of security. Best avoided. If you are going to handle errors do so properly or not at all.</p>\n\n<h3>Algorithm usage</h3>\n\n<p>You obviously have seen how the standard libs use algorithms.</p>\n\n<pre><code>transform(key, key+strlen(key), key, to_upper());\n</code></pre>\n\n<p>There are a couple of other places you can use the standard algorithms to make your code clearer. The encryption and de-cryption loops are exactly the place this kind of things work well in:</p>\n\n<pre><code>for(i = 0, j = 0; i &lt; plaintext.length(); ++i, j++) {\n if(j &gt;= key.length()) \n j = 0;\n if(plaintext[i] &gt;= 'A' &amp;&amp; plaintext[i] &lt;= 'Z')\n ch = ((plaintext[i] - 'A') + (key[j] - 'A')) % 26;\n else\n ch = plaintext[i] - 'A'; //only encrypt A-Z\n ciphertext.append(string(1, (char)(ch + 'A')));\n}\n</code></pre>\n\n<p>I would re-write as:</p>\n\n<pre><code>ciphertext.resize(plaintext.size());\nstd::transform(plaintext.begin(), plaintext.end(), ciphertext.begin(), MyCrypt(key));\n</code></pre>\n\n<p>Then just write your crypt function as a nice functor:</p>\n\n<pre><code>struct MyCrypt\n{\n std::string key;\n mutable std::size_t keyIndex;\n\n MyCrypt(std::string const&amp; key): key(key), keyIndex(0) {}\n char operator()(char const&amp; plain) const\n {\n char keyChar = key[keyIndex] - 'A';\n keyIndex = (keyIndex + 1) % key.size();\n\n return (plain &gt;= 'A' &amp;&amp; plain &lt;= 'Z')\n ? (plain - 'A' + keyChar) % 26;\n : plain - 'A';\n }\n};\n</code></pre>\n\n<h3>Your function</h3>\n\n<p>I would take this a step further and make your function work with any input type. So you are basically applying the standard convention of using iterators to specify your inputs/outputs and your encryption falls into that category.</p>\n\n<p>Your algorithm should not care where the plain text is coming from nor where it is going too.</p>\n\n<p>So I would change your function interface too:</p>\n\n<pre><code>template&lt;typename II, typename IO&gt;\nvoid encrypt_vigenere(string const&amp; key, II begin, II end, IO dst)\n{\n std::transform(begin, end, dst, MyCrypt(key));\n}\n</code></pre>\n\n<p>Now when you call it you don't even need to copy things into strings you can just encrypt the input into the output:</p>\n\n<pre><code>encrypt_vigenere(\"My long key that nobody well guess\",\n std::istreambuf_iterator&lt;char&gt;(std::cin),\n std::istreambuf_iterator&lt;char&gt;(),\n std::ostream_iterator&lt;char&gt;(std::cout)\n );\n</code></pre>\n\n<h3>Update: Correct way to write functor:</h3>\n\n<pre><code>// Alternative Version 1:\nstruct MyCrypt\n{\n std::string key;\n std::size_t&amp; keyIndex;\n\n MyCrypt(std::string const&amp; key, std::size_t&amp; keyIndex)\n : key(key)\n , keyIndex(keyIndex)\n {\n keyIndex = 0;\n }\n char operator()(char const&amp; plain) const\n {\n char keyChar = key[keyIndex] - 'A';\n keyIndex = (keyIndex + 1) % key.size();\n\n return (plain &gt;= 'A' &amp;&amp; plain &lt;= 'Z')\n ? (plain - 'A' + keyChar) % 26;\n : plain - 'A';\n }\n};\n\n\n// Usage:\nstd::size_t keyIndex;\nstd::transform(begin, end, dst, MyCrypt(key, keyIndex));\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>// Alternative Version 2\nstruct MyCrypt\n{\n std::string key;\n std::size_t keyIndex;\n\n MyCrypt(std::string const&amp; key)\n : key(key)\n , keyIndex(0)\n {}\n char operator()(char const&amp; plain)\n {\n char keyChar = key[keyIndex] - 'A';\n keyIndex = (keyIndex + 1) % key.size();\n\n return (plain &gt;= 'A' &amp;&amp; plain &lt;= 'Z')\n ? (plain - 'A' + keyChar) % 26;\n : plain - 'A';\n }\n};\n\n\n// Usage:\nMyCrypt crypt(key);\nstd::transform(begin, end, dst, crypt);\n</code></pre>\n\n<p>Strictly speaking either of these would be more correct.<br>\nBut I find both have disadvantages. The first version requires that you keep the index outside the functor (so that functor can retain its const(ness) while mutating the keyIndex). While the second version requires you to remove the const(ness) of the <code>operator()</code> which also means you can not dynamical create and pass it as a parameter (as it would be a temporary and thus us required to be const) to the algorithms. Instead you need to create an object and pass the object.</p>\n\n<p>Thus I prefer using the method I initially showed above (it bends the rules) but in my opinion makes the code easier to read/maintain and understand.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T00:56:57.280", "Id": "17342", "Score": "0", "body": "There is but one thing I could add to this answer, so I'm not answering separately: if you have a capable compiler, a lambda might be even more suitable than a hand-crafted functor (you get the same thing but \"in-place\")." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T13:27:06.627", "Id": "17383", "Score": "0", "body": "A lambda wont be suitable in this case as state needs to be maintained (keyIndex). Hence why a struct functor is used instead of a function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T07:49:09.390", "Id": "17396", "Score": "0", "body": "You could capture those as variables from the outside scope." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-12T21:09:33.173", "Id": "82345", "Score": "0", "body": "This is incorrect, though it probably works on most implementations. See http://en.cppreference.com/w/cpp/algorithm/transform: \"std::transform does not guarantee in-order application of unary_op or binary_op.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-12T21:56:37.580", "Id": "82349", "Score": "0", "body": "@ruds: incorrect. `std::transform()` uses `Input Iterator` Input iterator only have the capability for forward movements (with operator++) then can not move backwards and they can not randomly move between elements. So effectively this means transform must act upon the elements in order." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-13T04:10:39.517", "Id": "82389", "Score": "0", "body": "Even though `std::transform` is required to operate on input iterators, nothing prevents an implementation from specializing for random access iterators, nor from copying the functor passed to it and applying two different copies to different elements of the input.\n\nOn the whole, passing functions with side effects to the functional algorithms of the C++ standard library is distasteful for aesthetic reasons, and I'm not at all convinced that it's portable to rely on the implementation in this way." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T21:41:00.067", "Id": "10899", "ParentId": "10894", "Score": "21" } }, { "body": "<p>In addition to what cmh and Loki have said, here are a few pet peeves of mine:</p>\n<ol>\n<li><p><strong>Ban C-style casts from your code-base.</strong> They are dangerous (they are an everything-goes cast which severely undermines the type system) and too innocuous. Casts should stand out.</p>\n<p>So instead of <code>(char) foo</code>, use <code>static_cast&lt;char&gt;(foo)</code>; yes, it’s long and ugly. That’s intentional to make the cast stand out.</p>\n</li>\n<li><p><strong>Break the logic into smaller non-repeating blocks.</strong> With Loki’s amendments this is obsolete but in general look how similar your encrypt and decrypt functions are. You should strive to reduce this redundancy. If I remember my Vigenère correctly these functions are symmetrical and can be implemented by the same logic.</p>\n<p>You are also converting quite a lot between chars and numbers by adding or subtracting <code>'A'</code>. Encapsulate this into a pair of functions, it makes the code cleaner.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T15:16:56.770", "Id": "10909", "ParentId": "10894", "Score": "9" } }, { "body": "<p>Other than (perhaps) avoiding classifying other \"things\" as upper-case letters, I'm not sure why you'd use <code>x &gt;= 'A' &amp;&amp; x &lt;= 'Z'</code> instead of <code>isupper(x)</code>.</p>\n\n<p>I'm also a bit bothered by having <code>key[index] - 'A'</code> where the key is used -- I'd prefer to transform the entire key to the <code>key[i]-'A'</code> at initialization, and just use those values from then on.</p>\n\n<p>I don't think the encryption really works correctly as given. In particular, I believe it transforms 'A' .. 'Z' into the range 0..26 instead of producing output in the range 'A'..'Z' again.</p>\n\n<p>I think a bit more can also be done to merge the code for encrypting and decrypting together -- basically the only difference between them is adding vs. subtracting at one point. To keep as much code in common as possible, I'd use code something like this:</p>\n\n<pre><code>class BaseCrypt { \n int clamp(int val, int max) {\n if (val &lt; 0) val += max;\n else if (val &gt;= max) val -= max;\n return val;\n }\nprotected:\n std::string key;\n size_t index;\n\n template &lt;class xfm&gt;\n char xform(char input) {\n static unsigned const int letters = 26;\n if (!isupper(input))\n return input;\n int pos = input - 'A';\n int e_pos = xfm()(pos, key[index]);\n e_pos = clamp(e_pos, letters);\n char val = e_pos + 'A';\n index = (index + 1) % key.length();\n return val;\n }\npublic:\n BaseCrypt(std::string init) : index(0) { \n std::transform(\n init.begin(), \n init.end(), \n std::back_inserter(key),\n [](char ch) { return ::toupper(ch) - 'A'; });\n }\n};\n\nstruct encrypt : private BaseCrypt { \n encrypt(std::string const &amp;key) : BaseCrypt(key) {}\n char operator()(unsigned char input) { \n return xform&lt;std::plus&lt;char&gt; &gt;(input);\n }\n};\n\nstruct decrypt : private BaseCrypt { \n decrypt(std::string const &amp;key) : BaseCrypt(key) {}\n char operator()(unsigned char input) { \n return xform&lt;std::minus&lt;char&gt; &gt;(input);\n }\n};\n</code></pre>\n\n<p>Some might disagree with my expanding such a simple encryption algorithm out to its component operations like I have in <code>xform</code>, but it's been my experience, that at least when you get to real encryption algorithms, it pays to be extremely explicit about everything (even at the expense of some verbosity, much as I usually dislike that), and generate all the intermediate values so 1) you can look at them when debugging the code, and 2) you can assure that intermediate values don't get extended out to larger sizes and such, which can produce code that works most of the time, but then fails inexplicably for some tiny fraction of possible inputs (years ago I spent something like three days on some DES code with exactly that sort of problem).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T03:02:57.440", "Id": "10937", "ParentId": "10894", "Score": "5" } } ]
{ "AcceptedAnswerId": "10899", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T18:51:59.013", "Id": "10894", "Score": "18", "Tags": [ "c++", "vigenere-cipher" ], "Title": "Vigenere encryption" }
10894
<p>This shows the minimum of letters needed for a palindrome. It needs tweaking since it works fine for words 1-9 characters, but becomes slow for words with 10-12 characters, and for 13+ characters it really takes a lot of time. Any help is appreciated.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;conio.h&gt; #include &lt;string.h&gt; #include &lt;malloc.h&gt; typedef struct _el { char ch; struct _el* next; } lst; typedef struct _lst { char* string; struct _lst* next; } elmt; char* _remove(char*, int); int min(int , int); elmt* _ncptr(char [], int, elmt*, int ); int minfinal(char [], int, int ); elmt* _add(elmt* root, elmt* elm); int _count(elmt* root); int _last_p(elmt* root); int ispnd(char [], int); int __exist (elmt* root, char* str, int h); int max(int, int); lst* add(lst* root, char n); int exist(lst* root, char n); int main() { int l, min; char b[50]; printf("Insert the word:"); scanf("%s", b); l = strlen(b) - 1; printf("%d letters needed.\n", minfinal(b, 0, l)); _getch(); return 0; } int min(int a, int b) { return ((a&gt;b) ? b : a); } elmt* _ncptr(char v[], int quant, elmt* root, int count) { int cnt_, lvar; int len = strlen(v)-1; if(!root) { root = (elmt*)malloc(sizeof(elmt)); root-&gt;string = (char*)malloc(len+1); strcpy(root-&gt;string, v); root-&gt;next = '\0'; } if(quant == 0) return root; if(count &gt; 0) { int i; elmt *n_el, *tmp = root; i = 0; while(i &lt; count) { int j; j = 0; for(j = 0; j &lt; strlen(tmp-&gt;string); j++) { n_el = (elmt*)malloc(sizeof(elmt)); n_el-&gt;string = _remove(tmp-&gt;string, j); n_el-&gt;next = '\0'; if(__exist(root, n_el-&gt;string, i+j+1)) continue; root = _add(root, n_el); } tmp = tmp-&gt;next; i++; } return( _ncptr( v, quant-1, root, _count(root)-count ) ); } else { //MAYBE IT's FIRST CALL OF THE FUNCTION int i,j; elmt* n_el; i = strlen(v); for(j = 0; j &lt; i; j++) { n_el = (elmt*)malloc(sizeof(elmt)); n_el-&gt;string = _remove(v, j); n_el-&gt;next = '\0'; root = _add(root, n_el); } return( _ncptr( v, quant-1, root, _count(root) ) ); } } char* _remove(char* str, int i) { int j,k; char* nstr = (char*)malloc(strlen(str)); nstr[0] = '\0'; for(j = 0, k = 0; j &lt; strlen(str); j++) { if(j == i) { continue; } nstr[k] = str[j]; k++; } nstr[k] = '\0'; return nstr; } elmt* _add(elmt* root, elmt* elm) { elm-&gt;next = root; return elm; } int _count(elmt* root) { long int l_var; for( l_var = 0; root &amp;&amp; root-&gt;string; l_var++, root=root-&gt;next ); return l_var; } int minfinal(char v[], int n, int i) { elmt* g = NULL; if(ispnd(v, i)) return 0; g = _ncptr(v, i, g, 0); return( strlen(v) - _last_p(g) ); } int ispnd(char v[], int z) { int i, j, k; k = 0; for(i = 0, j = z; i &lt; j; i++, j--) { if(v[i] != v[j]) { k = 1; break; } } return !k; } int _last_p(elmt* root) { int l_var = 0; for(; root; root=root-&gt;next ) { if(strlen(root-&gt;string) == 0) continue; if(!ispnd(root-&gt;string, strlen(root-&gt;string)-1)) continue; l_var = max( l_var, strlen(root-&gt;string) ); } return l_var; } int __exist (elmt* lstt, char* str, int h) { int i,j; for(j=0; lstt, j &lt;= h; lstt = lstt-&gt;next, j++ ) { i = strcmp(lstt-&gt;string, str); if(!i) return 1; } return 0; } int max(int a, int b) { return (a &gt; b ? a : b ); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T18:17:46.993", "Id": "17325", "Score": "0", "body": "I don't completely understand your approach. But it seems like it is doing more than necessary. Why so much string manipulation?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T18:21:15.117", "Id": "17326", "Score": "0", "body": "I tried to do it in many ways, and I was getting so many errors. So I ended up with this version, where it removes the letters from the string one by one, and, it stores them in a linked list. for example. for the word 'abaca', the program generates baca, aaca, abca, abaa, abac, and for each of these it does the same thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T19:27:27.147", "Id": "17327", "Score": "0", "body": "So; SRIS => SIRIS, ROT => ROTOR, etc. Insert anything anywhere?" } ]
[ { "body": "<p>(Previous Answer removed)</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>Now that I understand the problem better, I see that my previous answer is no good. I think you need a new algorithm. What you have currently is getting into a combinatorial explosion. Try using a string difference algorithm against the reversed string. For example:</p>\n\n<p>input: abca</p>\n\n<p>reversed: acba</p>\n\n<p>difference:</p>\n\n<pre><code>abc a\na cba\n</code></pre>\n\n<p>So you can now see that you need to insert one letter to make the string match the reversed string. String differences can be determined relatively efficiently using dynamic programming.</p>\n\n<p>Here is another example:</p>\n\n<p>input: tostotor</p>\n\n<p>reversed: rototsot</p>\n\n<p>difference:</p>\n\n<pre><code>t ostot or\n ro totso t\n</code></pre>\n\n<p>So three letters are needed to make them match.</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>You can find more information on how to determine the differences between strings here: <a href=\"https://stackoverflow.com/questions/208094/how-to-find-difference-between-two-strings\">https://stackoverflow.com/questions/208094/how-to-find-difference-between-two-strings</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T18:34:50.553", "Id": "17328", "Score": "0", "body": "the problem is that for words like \"tostotor\", there are only needed 3 letters. TOSTOTOR becomes ROTOSTSOTOR. How would your approach solve this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T18:42:39.773", "Id": "17329", "Score": "0", "body": "@cprogcr: Ok, I'm not understanding the rules then. Any letters can be inserted at any place? Can letters be reordered?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T18:44:11.033", "Id": "17330", "Score": "0", "body": "Yeah, that is the TRUE problem. But letters cannot be reordered. you can insert anywhere, but no reordering." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T19:00:01.450", "Id": "17331", "Score": "0", "body": "@cprogcr: Ok, my initial answer isn't very helpful then. I've revised it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T19:43:57.327", "Id": "17332", "Score": "0", "body": "Hmmm wait a second, totso != ostot" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T19:48:56.513", "Id": "17333", "Score": "0", "body": "@cprogcr: I don't understand the issue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T19:56:16.130", "Id": "17334", "Score": "0", "body": "well the same would be to say tostoto r and r ototsot. so the it's not possible to make the difference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T20:11:56.233", "Id": "17336", "Score": "0", "body": "\"tostoto r\" and \"r ototsot\" don't have matching letters at the same position, so that wouldn't be a solution to the difference algorithm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T20:24:01.677", "Id": "17337", "Score": "0", "body": "what about totso and ostot ? please explain how should the algo work?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T22:26:47.030", "Id": "17338", "Score": "0", "body": "@cprogcr: I've added a link to my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T05:39:56.500", "Id": "17345", "Score": "0", "body": "longest common subsequence did the trick. :) thanks" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T18:30:21.293", "Id": "10897", "ParentId": "10896", "Score": "2" } }, { "body": "<p>This is an obvious candidate: (there are more lines containing this anti-pattern):</p>\n\n<pre><code>for(j = 0, k = 0; j &lt; strlen(str); j++) {...}\n</code></pre>\n\n<p>Will result in the strlen being called on every iteration, nmaking the whole thing an O(N*N) operation.</p>\n\n<p>A better way to do the same would be:</p>\n\n<pre><code>size_t len,j,k;\n\nlen = strlen(str);\nfor (j=k=0; j &lt; len;j++) {...}\n</code></pre>\n\n<p>Next:</p>\n\n<pre><code>char* _remove(char*, int);\nelmt* _ncptr(char [], int, elmt*, int );\nelmt* _add(elmt* root, elmt* elm);\nint _count(elmt* root);\nint _last_p(elmt* root);\nint __exist (elmt* root, char* str, int h);\n</code></pre>\n\n<p>Identifiers with leading underscores are reserved for the implementation and / or the library. </p>\n\n<p>In short: don't use them (unless you are implementing the implemnetation or the library, but in that case you would not ask this question, methinks)</p>\n\n<p>Next: the _remove function is terrible. I malloc() one byte too short, calls strlen() at every heartbeat, and ignores the existing string functions.</p>\n\n<pre><code>char *newremove(char *org, size_t pos) {\n size_t len;\n char *new;\n\n len = strlen(org) \n new = malloc(1+len);\n\n if (pos &lt; len) {\n memcpy(new, org, pos);\n memcpy(new+pos,org+pos+1, len-pos);\n }\n\n else {\n memcpy(new, org, len+1);\n }\n\nreturn new;\n</code></pre>\n\n<p>}</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T19:59:17.270", "Id": "17335", "Score": "0", "body": "yet it is too slow." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T19:36:37.050", "Id": "10898", "ParentId": "10896", "Score": "3" } }, { "body": "<p>I think your question could be stated as:</p>\n\n<ul>\n<li>Determine the minimum number of letters to be added to a given string in order to make it into a palindrome.</li>\n</ul>\n\n<p>You can do some work analytically. I'll use upper-case letters A, B, C, ... for the given letters; I'll use lower-case letters a, b, c for those added to make a palindrome.</p>\n\n<ol>\n<li>For an L-character string, the maximum number of characters that must be added is L-1.</li>\n<li>In general, there are numerous ways to make a palindrome from a string.</li>\n<li>Any single character is already a palindrome (L-1 = 0).</li>\n<li>For a two-character string, there are two cases:\n<ul>\n<li>AA (0 to add; it is already a palindrome).</li>\n<li>AB (1 to add &mdash; bAB or ABa).</li>\n</ul></li>\n<li>For a three-character string, there are <s>four</s> five cases:\n<ul>\n<li>ABC (2 to add &mdash; cbABC).</li>\n<li>AAB (1 to add &mdash; bAAB).</li>\n<li>ABB (1 to add &mdash; ABBa).</li>\n<li>ABA (0 to add; it is already a palindrome).</li>\n<li>AAA (0 to add; it is already a palindrome).</li>\n</ul></li>\n<li>For a four-character string, there are at least ten cases:\n<ul>\n<li>ABCD (3 to add &mdash; dcbABCD).</li>\n<li>AABC (2 to add &mdash; cbAABC).</li>\n<li>ABAC (1 to add &mdash; cABAC).</li>\n<li>ABCA (1 to add &mdash; ABCbA).</li>\n<li>ABBA (0 to add; it is already a palindrome).</li>\n<li>ABAA (1 to add &mdash; ABAbA).</li>\n<li>ABAB (1 to add &mdash; bABAB).</li>\n<li>ABBB (1 to add &mdash; ABBBa).</li>\n<li>AAAA (0 to add; it is already a palindrome).</li>\n<li>AABB (2 to add &mdash; bbAABB).</li>\n</ul></li>\n</ol>\n\n<p>Starting with these cases, we can see that:</p>\n\n<ul>\n<li>Check whether the pattern is a palindrome.\n<ul>\n<li>If yes, the number of characters to add is 0.</li>\n</ul></li>\n<li>Given the length, L, and the number of distinct characters, D,\n<ul>\n<li>If L = D, then you need to add L-1 characters.</li>\n</ul></li>\n<li>Otherwise, you can lop off the last character, make an palindrome from the L-1 character string, and add the last character again at front and back.\n<ul>\n<li>That's a nice recursive function.</li>\n<li>The question is, does that add the minimum characters each time?</li>\n</ul></li>\n</ul>\n\n<p>Let's revisit the case of L=4. X will be the number of extra characters required.</p>\n\n<ul>\n<li>ABCD\n<ul>\n<li>Drop D, palindrome from ABC (L=3, D=3)</li>\n<li>Drop C, palindrome from AB (L=2, D=2)\n<ul>\n<li>Drop B, palindrome from A (L=1, D=1)</li>\n<li>A is a palindrome ⟶ A (X=0)</li>\n<li>Add B to front and back ⟶ bAB (X=1)</li>\n</ul></li>\n<li>Add C to front and back ⟶ cbABC (X=2)</li>\n<li>Add D to front and back ⟶ dcbABCD (X=3)</li>\n</ul></li>\n<li>AABC\n<ul>\n<li>Drop C, palindrome from AAB (L=3, D=2)</li>\n<li>Drop B, palindrome from AA (L=2, D=1)\n<ul>\n<li>AA is a palindrome ⟶ AA (X=0)</li>\n</ul></li>\n<li>Add B to front and back ⟶ bAAB (X=1)</li>\n<li>Add C to front and back ⟶ cbAABC (X=2)</li>\n</ul></li>\n<li>ABAC\n<ul>\n<li>Drop C, palindrome from ABA (L=3, D=2)</li>\n<li>ABA is a palindrome ⟶ ABA (X=0)</li>\n<li>Add C to front and back ⟶ cABAC (X=1)</li>\n</ul></li>\n<li>ABBA\n<ul>\n<li>ABBA is a palindrome ⟶ ABBA (X=0)</li>\n</ul></li>\n<li>ABAA\n<ul>\n<li>Drop A, palindrome from ABA (L=3, D=2)</li>\n<li>ABA is a palindrome ⟶ ABA (X=0)</li>\n<li>Add A to front and back ⟶ aABAA (X=1)</li>\n</ul></li>\n<li>ABAB\n<ul>\n<li>Drop B, palindrome from ABA (L=3, D=2)</li>\n<li>ABA is a palindrome ⟶ ABA (X=0)</li>\n<li>Add B to front and back ⟶ BABAB (X=1)</li>\n</ul></li>\n<li>AAAA\n<ul>\n<li>ABBA is a palindrome ⟶ ABBA (X=0)</li>\n</ul></li>\n<li>AABB\n<ul>\n<li>Drop B, find palindrome from AAB (L=3, D=2)</li>\n<li>Drop B, find palindrome from AA (L=2, D=1)\n<ul>\n<li>AA is a palindrome ⟶ AA (X=0)</li>\n</ul></li>\n<li>Add B to front and back ⟶ bAAB (X=1)</li>\n<li>Add B to front and back ⟶ bbAABB (X=2)</li>\n</ul></li>\n</ul>\n\n<p>So far, so good...but there are two cases not treated:</p>\n\n<ul>\n<li>ABBB\n<ul>\n<li>In this example, dropping the last character is bad; it leads to bbbABBB, which is much longer than what you get if you drop the first character (namely ABBBa).</li>\n</ul></li>\n<li>ABCA\n<ul>\n<li>In this example, if you go about dropping the last character, you also end up with a much longer string than is necessary.</li>\n</ul></li>\n</ul>\n\n<p>How can we refine things?</p>\n\n<p>If the first and last character are the same (but the string is not a palindrome), then drop first and last character, find a palindrome for the shorter string, and then reinstate the first and last. For the ABCA example, that gives:</p>\n\n<ul>\n<li>ABCA\n<ul>\n<li>Drop leading and trailing A; palindrome from BC (L=2, D=2)</li>\n<li>Drop C; palindrome from B (L=1, D=1)\n<ul>\n<li>B is a palindrome ⟶ B (X=0)</li>\n</ul></li>\n<li>Add C at front and back ⟶ cBC (X=1)</li>\n<li>Add A at front and back ⟶ AcBCA (X=1 &mdash; because we removed 2 and restored 2)</li>\n</ul></li>\n</ul>\n\n<p>That still leaves the ABBB example causing grief. We can note that AAAB is very similar to ABBB, but AAAB would work fine with the algorithm originally proposed, producing BAAAB (X=1).</p>\n\n<p>Maybe the trick is to find the longest sequence of a single character repeating at either end. If the longer of these is L/2 or greater, then you simply add the other part as a 'mirror' of itself. With the AAAB and ABBB cases:</p>\n\n<ul>\n<li>The longest repeat is 3 (AAA or BBB); and that's more than L/2, so the other part is added as a mirror of itself (but a mirror of 1 letter is that letter).</li>\n<li>AAAB adds the B in mirror, producing BAAAB (X=1).</li>\n<li>ABBB adds the A in mirror, producing ABBBA (X=1).</li>\n<li>Applied to AABB, there are two different 2-letter sequences, which are both L/2 long; it is arbitrary which is processed, and you end up with either BBAABB or AABBAA (X=2).</li>\n</ul>\n\n<p>Looking at a longer sample, what about AACADEFFFFABA?</p>\n\n<ul>\n<li>The strings start and end with A; remove it and find a palindrome for ACADEFFFFAB.\n<ul>\n<li>Arbitrarily drop B; find a palindrome for ACADEFFFFA.</li>\n<li>The strings start and end with A; find a palindrome for CADEFFFF.\n<ul>\n<li>There's a run of 4 F's at the end; that's L/2.</li>\n<li>Add the mirror of CADE to give a palindrome ⟶ CADEFFFFEDAC (X=4)</li>\n</ul></li>\n<li>Add A to both ends ⟶ ACADEFFFFEDACA (X=4)</li>\n<li>Add B to both ends ⟶ BACADEFFFEDACAB (X=5)</li>\n</ul></li>\n<li>Add A to both ends ⟶ ABACADEFFFFEDACABA (X=5)</li>\n</ul>\n\n<p>That seems to be about right...</p>\n\n<p>Let's look at another longer sample:</p>\n\n<ul>\n<li>ABCDEFCBA\n<ul>\n<li>Drop the leading and trailing A's; find a palindrome for BCDEFCB.</li>\n<li>Drop the leading and trailing B's; find a palindrome for CDEFC.\n<ul>\n<li>Drop the leading and trailing C's; find a palindrome for DEF.</li>\n<li>Drop the F; find a palindrome for DE.\n<ul>\n<li>Drop the E; find a palindrome for D.</li>\n<li>D is a palindrome ⟶ D (X=0).</li>\n<li>Add E to front and back ⟶ EDE (X=1).</li>\n</ul></li>\n<li>Add F to front and back ⟶ FEDEF (X=2).</li>\n<li>Add C to front and back ⟶ CFEDEFC (X=2).</li>\n</ul></li>\n<li>Add B to front and back ⟶ BCFEDEFCB (X=2).</li>\n<li>Add A to front and back ⟶ ABCFEDEFCBA (X=2).</li>\n</ul></li>\n</ul>\n\n<p>That too looks about right.</p>\n\n<p>From here, I think it is a SMOP (Simple Matter of Programming).</p>\n\n<hr>\n\n<p>[<em>Later</em>] There is probably still some refinement required...</p>\n\n<p>Consider:</p>\n\n<pre><code>CABLEWASIEREISAWELBA (C Able Was I Ere I Saw Elba)\n</code></pre>\n\n<p>Clearly, the minimum change is to add a C to the end:</p>\n\n<pre><code>CABLEWASIEREISAWELBAc\n</code></pre>\n\n<p>When I first wrote up the 'longest repeat' criterion, I had 'longest palindrome', and that was probably a better choice. In this case, the longest palindrome from the end is clearly everything except the leading C, and then you end up with the minimum change. A repeat is a special case of palindrome, of course.</p>\n\n<p>It does lead to the question of what happens with:</p>\n\n<p>XYZABLEWASIEREISAWELBAOBSEQUIOUSNESS</p>\n\n<p>There, you have a 17-letter anagram (Able ...) with 16 letters surrounding it. Does that help at all? A little. As you strip off the end characters (from OBSEQUIOUSNESS), you eventually end up with the anagram exposed, at which point you generate:</p>\n\n<pre><code>XYZABLEWASIEREISAWELBAzyx\n</code></pre>\n\n<p>and then you add back the OBSEQUIOUSNESS to yield:</p>\n\n<pre><code>ssensuoiuqesboXYZABLEWASIEREISAWELBAzyxOBSEQUIOUSNESS\n</code></pre>\n\n<p>So, the longest trailing or leading palindrome refinement seems to be about right.</p>\n\n<p>How should the tests be prioritized? Should the leading/trailing palindrome be found before the leading/trailing same letter? Consider:</p>\n\n<pre><code>AABLEWASIEREISAWELBA (A Able Was I Ere I Saw Elba)\n</code></pre>\n\n<p>The leading and trailing letters are the same, but there's the humongous trailing anagram.</p>\n\n<p>If you drop the leading and trailing A, then you process:</p>\n\n<pre><code>ABLEWASIEREISAWELB\n</code></pre>\n\n<p>The leading/trailing letters are different, so the trailing palindrome is spotted, and you end up with:</p>\n\n<pre><code>AABLEWASIEREISAWELBaA\n</code></pre>\n\n<p>If you did the trailing palindrome first, you end up with essentially the same answer:</p>\n\n<pre><code>AABLEWASIEREISAWELBAa\n</code></pre>\n\n<p>So, maybe the sequencing is not critical. The common letter at the end is simpler than 'the longest leading/trailing palindrome', so that makes sense as the test to perform first, unless someone devises an example where it leads to the wrong answer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T23:44:56.997", "Id": "10901", "ParentId": "10896", "Score": "2" } }, { "body": "<p>Even though I dont really understand C</p>\n<p>Do you know about <a href=\"http://en.wikipedia.org/wiki/Levenshtein_distance\" rel=\"nofollow noreferrer\">Levenshtein distance</a>? It's very fast</p>\n<p>It's just to find de minimum edit distance between 2 strings</p>\n<p>I tried to pass the reversed string and curiously I got a result that was the double from what I espected. But taking a look seems like a rule that by dividing the result by 2 it gives the answer I want.</p>\n<p>But take care as soon as I'm not sure of what you are trying to get I might be wrong because that calculation of distance considers insertions and deletions at any positions not only begin and end.</p>\n<p>And if you are interested only in insertions you probably would like to remove the part of deletions from Levensthein algorithm</p>\n<blockquote>\n<p>some tests I did (considering insertions, deletions AND replacements):</p>\n<p>AAAA = 0</p>\n<p>AAAB = 1</p>\n<p>AABB = 2</p>\n<p>ABBA = 0</p>\n<p>ABAB = 1</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T05:06:16.587", "Id": "17344", "Score": "0", "body": "it gives a result, but not the minimum." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T00:29:44.333", "Id": "10902", "ParentId": "10896", "Score": "1" } } ]
{ "AcceptedAnswerId": "10897", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T18:05:50.537", "Id": "10896", "Score": "3", "Tags": [ "performance", "c", "palindrome" ], "Title": "Showing the minimum of letters needed for a palindrome" }
10896
<p>When releasing objects that might have been retained during the app's lifetime, how do you check if the object really exists and prevent releasing a nil object?</p> <p>Here's how I'm doing it:</p> <pre><code>- (void)dealloc{ if(account_) [account_ release]; account_ = nil; [super dealloc]; } </code></pre>
[]
[ { "body": "<pre><code>- (void)dealloc{\n if(account_)\n</code></pre>\n\n<p>You don't need to do this. Objective-C ignores attempts to call methods on nil objects. So you call <code>release</code> and nothing will happen if its already nil</p>\n\n<pre><code> [account_ release];\n account_ = nil;\n</code></pre>\n\n<p>Your object is being destroyed, there isn't a whole lot of point in setting values to nil</p>\n\n<pre><code> [super dealloc];\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T07:42:15.207", "Id": "17347", "Score": "0", "body": "What happens if the object has already been released but the reference, for some reason, isn't nil? It has happened to me before, I suppose something wrong I made along the way?\n\nThe error I get is along the lines of \"Deallocated reference cannot be released again.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T12:50:33.280", "Id": "17352", "Score": "1", "body": "@Solivagant, you should set the reference to be nil after you release it, unless the variable is going out of scope anyways. (Actually, to make it easier you should use the ARC feature in the newest versions of XCode. It takes care of release/retain for you automatically)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T01:02:27.023", "Id": "10903", "ParentId": "10900", "Score": "6" } } ]
{ "AcceptedAnswerId": "10903", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-14T23:34:18.553", "Id": "10900", "Score": "1", "Tags": [ "objective-c" ], "Title": "Releasing retained objects inside dealloc" }
10900
<p>I have lots of classes that inherit from abstract base class, which has abstract method</p> <pre><code>public class BaseClass&lt;T&gt; { protected abstract void GetItems(); } </code></pre> <p>each subclass have almost the same implementation</p> <pre><code>protected override void GetItems() { // some preparation code here which is the same for all sublcasses // calls async method that handles the result in anonymous method // method name is different for each of the subclass that implements it _model.GetXXXAsync(a =&gt; { // same code here for all sublclasses }); } </code></pre> <p>So, basically, the difference is only in the GetXXXAsync method. This is the method signature:</p> <pre><code>void GetXXXAsync(Action&lt;EntityResultArgs&lt;T&gt;&gt; operationCompleted); </code></pre> <p>WHat would be the best way to refactor this code to place it in a base class, to avoud repeating 30 lines of code in each subclass, while changing only the method name and T type?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T13:06:52.447", "Id": "17382", "Score": "1", "body": "`GetItems` suggests that the method would return the object retrieved. Perhaps you want to call it \"PopulateItems\" instead, or something similar?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T17:06:28.310", "Id": "17389", "Score": "0", "body": ":) never actually thought about it, it is kind of \"out of context\". Thanks." } ]
[ { "body": "<p>You can create an <code>abstract</code> method that will wrap the <code>GetXXXAsync()</code> method:</p>\n\n<pre><code>public class BaseClass&lt;T&gt;\n{\n protected void Getitems()\n {\n // some preparation code here which is the same for all sublcasses\n\n GetItemsInternal(a =&gt;\n {\n // same code here for all sublclasses\n });\n }\n\n // probably needs a better name\n protected abstract void GetItemsInternal(Action&lt;EntityResultArgs&lt;T&gt;&gt; operationComplete);\n}\n\npublic class DerivedClass : BaseClass&lt;SomeType&gt;\n{\n protected override void GetItemsInternal(Action&lt;EntityResultArgs&lt;SomeType&gt;&gt; operationComplete)\n {\n _model.GetXXXAsync(operationComplete);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T11:32:02.800", "Id": "10907", "ParentId": "10906", "Score": "7" } }, { "body": "<p>An alternative using an abstract property.</p>\n\n<pre><code>public abstract class BaseClass&lt;T&gt;\n{\n protected abstract Action&lt;T&gt; GetAsync { get; }\n\n protected void GetItems()\n {\n // some preparation code here which is the same for all sublcasses\n\n GetAsync(a =&gt; \n {\n // same code here for all sublclasses\n });\n }\n}\n\npublic class DerivedClass : BaseClass&lt;SomeType&gt;\n{\n protected override Action&lt;SomeType&gt; GetAsync { get { return _model.GetXXXAsync; } }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T23:11:53.530", "Id": "17425", "Score": "0", "body": "Hi, Jeremy, as you can see above, the method is asynhronous, and therefore no return type." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T07:48:46.793", "Id": "17544", "Score": "0", "body": "This is certainly an alternative and I thought about it, but I don't see any advantage in doing it this way." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T04:24:36.213", "Id": "10941", "ParentId": "10906", "Score": "1" } } ]
{ "AcceptedAnswerId": "10907", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T11:00:17.983", "Id": "10906", "Score": "2", "Tags": [ "c#", "design-patterns" ], "Title": "How to make this code fit into the base class" }
10906
<p>This code implements a data structure for representing a Sudoku board, a very simple algorithm for setting up the board, and a GUI written in tkinter(requires tkinter and tkinter.tix).</p> <pre><code>#!/usr/bin/python # Sudoku board code, and Sudoku board generation code. # TODO: # - Sudoku Solver # - GUI Load/Save game (DONE) # - GUI Board Drawing (DONE) # - GUI Board Sync (DONE) # - GUI Board Interaction (DONE) # - GUI End Game Mode # - Reimplment SudokuBoard more efficently and with less complexity import random import time import os import tkinter.tix import pickle from tkinter import * from tkinter.constants import * from tkinter.tix import FileSelectBox, Tk random.seed(time.time()) # There are probably a few bugs in this class, and it could be implemented # better I think. class SudokuBoard: """ Data structure representing the board of a Sudoku game. """ def __init__(self): self.clear() def clear(self): """ Empty the board. """ self.grid = [[0 for x in range(9)] for y in range(9)] self.locked = [] def get_row(self, row): return self.grid[row] def get_cols(self, col): return [y[col] for y in self.grid] def get_nearest_region(self, col, row): """ Regions are 3x3 sections of the grid. """ def make_index(v): if v &lt;= 2: return 0 elif v &lt;= 5: return 3 else: return 6 return [y[make_index(col):make_index(col)+3] for y in self.grid[make_index(row):make_index(row)+3]] def set(self, col, row, v, lock=False): if v == self.grid[row][col] or (col, row) in self.locked: return for v2 in self.get_row(row): if v == v2: raise ValueError() for v2 in self.get_cols(col): if v == v2: raise ValueError() for y in self.get_nearest_region(col, row): for x in y: if v == x: raise ValueError() self.grid[row][col] = v if lock: self.locked.append((col, row)) def get(self, col, row): return self.grid[row][col] def __str__(self): strings = [] newline_counter = 0 for y in self.grid: strings.append("%d%d%d %d%d%d %d%d%d" % tuple(y)) newline_counter += 1 if newline_counter == 3: strings.append('') newline_counter = 0 return '\n'.join(strings) def sudogen_1(board): """ Algorithm: Add a random number between 1-9 to each subgrid in the board, do not add duplicate random numbers. """ board.clear() added = [0] for y in range(0, 9, 3): for x in range(0, 9, 3): if len(added) == 10: return i = 0 while i in added: i = random.randint(1, 9) try: board.set(random.randint(x, x+2), random.randint(y, y+2), i, lock=True) except ValueError: print("Board rule violation, this shouldn't happen!") added.append(i) def rgb(red, green, blue): """ Make a tkinter compatible RGB color. """ return "#%02x%02x%02x" % (red, green, blue) class SudokuGUI(Frame): board_generators = {"SudoGen v1 (Very Easy)":sudogen_1} board_generator = staticmethod(sudogen_1) def new_game(self): self.board.clear() self.board_generator(self.board) self.sync_board_and_canvas() def make_modal_window(self, title): window = Toplevel() window.title(title) window.attributes('-topmost', True) window.grab_set() window.focus_force() return window def load_game(self): def _load_game(filename): with open(filename, 'rb') as f: board = pickle.load(f) if not isinstance(board, SudokuBoard): # TODO: Report bad file return self.board = board self.sync_board_and_canvas() window.destroy() window = self.make_modal_window("Load Game") fbox = FileSelectBox(window, command=_load_game) fbox.pack() window.mainloop() def save_game(self): def _save_game(filename): with open(filename, 'wb') as f: pickle.dump(self.board, f, protocol=2) window.destroy() window = self.make_modal_window("Save Game") fbox = FileSelectBox(window, command=_save_game) fbox.pack() window.mainloop() def query_board(self): window = self.make_modal_window("Set Board Algorithm") scroll = Scrollbar(window) scroll.pack(side='right', fill='y') listbox = Listbox(window, yscrollcommand=scroll.set) scroll.config(command=listbox.yview) bframe = Frame(window) for s in self.board_generators.keys(): listbox.insert(-1, s) def do_ok(): self.board_generator = self.board_generators[listbox.get(ACTIVE)] window.destroy() def do_cancel(): window.destroy() cancel = Button(bframe, command=do_cancel, text="Cancel") cancel.pack(side='right', fill='x') ok = Button(bframe, command=do_ok, text="Ok") ok.pack(side='right', fill='x') listbox.pack(side='top', fill='both', expand='1') bframe.pack(side='top', fill='x', expand='1') window.mainloop() def make_grid(self): c = Canvas(self, bg=rgb(128,128,128), width='512', height='512') c.pack(side='top', fill='both', expand='1') self.rects = [[None for x in range(9)] for y in range(9)] self.handles = [[None for x in range(9)] for y in range(9)] rsize = 512/9 guidesize = 512/3 for y in range(9): for x in range(9): (xr, yr) = (x*guidesize, y*guidesize) self.rects[y][x] = c.create_rectangle(xr, yr, xr+guidesize, yr+guidesize, width=3) (xr, yr) = (x*rsize, y*rsize) r = c.create_rectangle(xr, yr, xr+rsize, yr+rsize) t = c.create_text(xr+rsize/2, yr+rsize/2, text="SUDO", font="System 15 bold") self.handles[y][x] = (r, t) self.canvas = c self.sync_board_and_canvas() def sync_board_and_canvas(self): g = self.board.grid for y in range(9): for x in range(9): if g[y][x] != 0: self.canvas.itemconfig(self.handles[y][x][1], text=str(g[y][x])) else: self.canvas.itemconfig(self.handles[y][x][1], text='') def canvas_click(self, event): print("Click! (%d,%d)" % (event.x, event.y)) self.canvas.focus_set() rsize = 512/9 (x,y) = (0, 0) if event.x &gt; rsize: x = int(event.x/rsize) if event.y &gt; rsize: y = int(event.y/rsize) print(x,y) if self.current: (tx, ty) = self.current #self.canvas.itemconfig(self.handles[ty][tx][0], fill=rgb(128,128,128)) self.current = (x,y) # BUG: Changing the color of the background of a tile erases parts of # the thick gridlines #self.canvas.itemconfig(self.handles[y][x][0], fill=rgb(255,255,255)) def canvas_key(self, event): print("Clack! (%s)" % (event.char)) if event.char.isdigit() and int(event.char) &gt; 0 and self.current: (x,y) = self.current #self.canvas.itemconfig(self.handles[y][x][0], fill=rgb(128,128,128)) try: self.board.set(x, y, int(event.char)) self.sync_board_and_canvas() except ValueError: # TODO: I'd rather set the erroneous value anyway and simply # not consider it valid, and perhaps set the text color # to red. pass def __init__(self, master, board): Frame.__init__(self, master) if master: master.title("SudokuGUI") self.board = board self.board_generator(board) bframe = Frame(self) self.ng = Button(bframe, command=self.new_game, text="New Game") self.ng.pack(side='left', fill='x', expand='1') self.sg = Button(bframe, command=self.save_game, text="Save Game") self.sg.pack(side='left', fill='x', expand='1') self.lg = Button(bframe, command=self.load_game, text="Load Game") self.lg.pack(side='left', fill='x', expand='1') self.query = Button(bframe, command=self.query_board, text="Set Board Algorithm") self.query.pack(side='left', fill='x', expand='1') bframe.pack(side='bottom', fill='x', expand='1') self.make_grid() self.canvas.bind("&lt;Button-1&gt;", self.canvas_click) self.canvas.bind("&lt;Key&gt;", self.canvas_key) self.current = None self.pack() if __name__ == '__main__': board = SudokuBoard() tk = Tk() gui = SudokuGUI(tk, board) gui.mainloop() </code></pre>
[]
[ { "body": "<p>In general I think the code is clear, self-explanatory and well implemented. For some points that could use improvement:</p>\n\n<ul>\n<li><p><code>SudokuBoard.get_nearest_region</code></p>\n\n<ul>\n<li><code>make_index</code> is unnecessary, use <code>v // 3 * 3</code> instead (in case you don't know, <code>//</code> means \"integer division\" in Python); (<em>Edit:</em> as @NolenRoyalty pointed out, keeping it is better for code clarity, though it can be simplified using the expression above)</li>\n<li><p>Since this function is only used in <code>set</code>, you might as well make its results more convenient for it (by flattening the result):</p>\n\n<pre><code>def make_index(v):\n \"\"\"Index of the closest row/column (to the top/left)\"\"\"\n return v // 3 * 3\nreturn [c for y in self.grid[make_index(row):make_index(row)+3] for c in y[make_index(col):make_index(col)+3]]\n</code></pre>\n\n<p>This way the calling code will be much simpler:</p>\n\n<pre><code>if v in self.get_row(row) + self.get_cols(col) + self.get_nearest_region(col,row):\n raise ValueError()\n</code></pre>\n\n<p>Note also that I replaced the 3 for loops for a single if, using list concat to get all the invalid values (maybe with some repetition) and <code>in</code> to check if your value is in that list. Set union would work too: <code>set(list1) | set(list2) | set(list3)</code> (I'm referring to the builtin type <a href=\"http://docs.python.org/library/stdtypes.html#set\" rel=\"nofollow\"><code>set</code></a>, not your <code>SudokuBoard.set</code> function).</p></li>\n</ul></li>\n<li><p>In <code>SudokuBoard.__str__</code>, you could use <code>enumerate</code> to get the index of each element together with the element, while iterating, and using remainder (modulus) to detect third rows:</p>\n\n<pre><code>strings = []\nfor index,y in enumerate(self.grid):\n strings.append(\"%d%d%d %d%d%d %d%d%d\" % tuple(y))\n if index % 3 == 2:\n strings.append('')\nreturn '\\n'.join(strings)\n</code></pre></li>\n<li><p>In <code>sudogen_1</code>, instead of repeateadly generating random numbers, you could just shuffle the interval and pick from it (since you don't want repeats):</p>\n\n<pre><code>board.clear()\nr_vals = range(1,9) # Generate all values from 1 to 9\nrandom.shuffle(r_vals) # Shuffle those values, to they will appear in random order\nfor y in range(0, 9, 3):\n for x in range(0, 9, 3):\n if not r_vals:\n return\n i = r_vals.pop() # Gets (and removes) one value from list\n try:\n board.set(random.randint(x, x+2), random.randint(y, y+2), i, lock=True)\n except ValueError:\n print(\"Board rule violation, this shouldn't happen!\")\n</code></pre></li>\n<li><p>In <code>sync_board_and_canvas</code> I'd personally not use that if-else, but move it to the <code>text</code> parameter only (that's a bit subjective though):</p>\n\n<pre><code>self.canvas.itemconfig(self.handles[y][x][1], \n text=str(g[y][x]) if g[y][x] else '')\n</code></pre></li>\n</ul>\n\n<p>That's it. I have no experience with tkinter, so I limited my feedback to general aspects of your code. Maybe someone with better knowledge of it can contribute with that other part.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T03:21:27.043", "Id": "17374", "Score": "0", "body": "Thanks. I didn't know about python's integer division operator, and it never occurred to me that it is much more efficient to shuffle a range of values once rather than generate and --possibly discard-- numbers over and over. I did actually decide to rewrite the board code a few hours ago, which can be seen here: [https://github.com/Mach1723/sudoku/blob/board_rewrite/sudoku.py](https://github.com/Mach1723/sudoku/blob/board_rewrite/sudoku.py). So that particular bit of code is much better now I think, but once again thanks for reviewing!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T07:50:55.973", "Id": "17376", "Score": "1", "body": "I agree that `make_index` is unnecessary but I think having a function like `def make_index(x): return x//3` would actually add to clarity, I know I used something similar when I wrote a sudoku solver. This is a great, comprehensive post though. +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T09:47:04.347", "Id": "17378", "Score": "0", "body": "@NolenRoyalty I agree, substituting this \"magic expression\" for a meaningul function would indeed add to clarity. Answer updated" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T09:48:22.543", "Id": "17379", "Score": "0", "body": "@mgibsonbr It also allows easier abtraction when you want to change the size of the board to some size other than 3x3." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T21:03:28.427", "Id": "10919", "ParentId": "10908", "Score": "3" } } ]
{ "AcceptedAnswerId": "10919", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T12:31:27.680", "Id": "10908", "Score": "5", "Tags": [ "python", "gui", "sudoku", "tkinter" ], "Title": "Python Sudoku GUI" }
10908
<p>This is my first useful bash script. It's meant to make it easy to switch between a "work" hosts file (that blocks sites like reddit.com, youtube.com, etc.) and my normal hosts file, and also to allow me to easily add/remove sites I want to block.</p> <p>I'm not sure if I'm doing everything right or securely, so please feel free to pick at anything.</p> <pre><code>#!/bin/bash usage() { cat &lt;&lt;EOF Usage: wrk [command] [host1 host2 ...] Commands: list list blocked hosts add [host ...] add a host to be blocked rm [host ...] remove hosts from block start start blocking stop stop blocking EOF } VARDIR="$HOME/abes_commands/var" # HOST_FILE - actual host file to be swapped around. # ORIG_FILE - original host file without any of the appended blocked hosts. # BLCK_FILE - list of blocked hosts. # BLCK_TEMP - temporary file used when removing hosts. HOST_FILE="/etc/hosts" ORIG_FILE="$VARDIR/original_host" BLCK_FILE="$VARDIR/blocked_host" BLCK_TEMP=`mktemp -t "blocked_hosts"` || `mktemp /tmp/blocked_hosts.XXXXXXX` || exit 1 # Make sure files exist. [[ -e $ORIG_FILE ]] || touch "$ORIG_FILE" [[ -e $BLCK_FILE ]] || touch "$BLCK_FILE" # Check to see if the block is currently active. ACTIVE_FLAG="$HOME/.wrk_block.flag" if [[ -e $ACTIVE_FLAG ]]; then IS_ACTIVE=0 else IS_ACTIVE=1 fi add_host() { local hosts=("$@") for host in "${hosts[@]:1}"; do # append host to blocked hosts list echo "127.0.0.1 $host" &gt;&gt; "$BLCK_FILE" echo -e "\033[0;32madded\033[0m $host" done } # todo: remove need for loop; do in one go rm_host() { local hosts=("$@") for host in "${hosts[@]:1}"; do # overwrite host list file with a copy removing a certain host awk -v host=$host 'NF==2 &amp;&amp; $2!=host { print }' "$BLCK_FILE" &gt; "$BLCK_TEMP" mv "$BLCK_TEMP" "$BLCK_FILE" echo -e "\033[0;31mremoved\033[0m $host" done } check_root() { if [[ "`whoami`" != "root" ]]; then echo "You don't have sufficient priviledges to run this script (try sudo.)" exit 1 else [[ -e $HOST_FILE ]] || { echo "Can't find or access host file."; exit 1; } fi } start_block() { if [[ $IS_ACTIVE -ne 0 ]]; then cp "$HOST_FILE" "$ORIG_FILE" cat "$BLCK_FILE" &gt;&gt; "$HOST_FILE" touch "$ACTIVE_FLAG" echo "Block started." else echo "Already blocking." fi } stop_block() { if [[ $IS_ACTIVE -eq 0 ]]; then cp "$ORIG_FILE" "$HOST_FILE" [[ -e $ACTIVE_FLAG ]] &amp;&amp; rm "$ACTIVE_FLAG" echo "Stopped blocking." else echo "Not blocking." fi } case $1 in 'ls' | 'list') awk 'NF == 2 { print $2 }; END { if (!NR) print "Empty" }' "$BLCK_FILE";; 'add') [[ -z $2 ]] &amp;&amp; { usage; exit 1; } add_host $@;; 'rm' | 'remove') [[ -z $2 ]] &amp;&amp; { usage; exit 1; } rm_host $@;; 'start') check_root start_block;; 'stop') check_root stop_block;; *) usage;; esac </code></pre> <p>The <code>blocked_host</code> file is appended to the <code>hosts</code> file when blocking starts, and looks like this:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>127.0.0.1 www.reddit.com 127.0.0.1 reddit.com 127.0.0.1 www.news.ycombinator.com 127.0.0.1 news.ycombinator.com </code></pre> </blockquote>
[]
[ { "body": "<p>I think this is generally clean.</p>\n\n<h2>Style Points</h2>\n\n<p>use <code>$()</code> instead of <code>``</code>, it's clearer and they can be nested.</p>\n\n<p>E.g:</p>\n\n<pre><code>if [[ \"$(whoami)\" != \"root\" ]]; then\n echo \"You don't have sufficient priviledges to run this script (try sudo.)\"\n exit 1\n</code></pre>\n\n<p>Consider setting:</p>\n\n<pre><code>set -u #prevent unset variables\nset -e #stop on an error\n</code></pre>\n\n<p>At the top of your script.</p>\n\n<p>rm_host may benefit from rewriting using an inplace sed edit, rather than using awk to copy over the top of the old file.</p>\n\n<h2>Locks</h2>\n\n<p>Although unlikely, you may want to consider a <a href=\"http://linux.die.net/man/1/flock\" rel=\"nofollow\">lock</a> to prevent races between <code>add_host</code> and <code>rm_host</code>. <code>$ACTIVE_FLAG</code> would make a good lock.</p>\n\n<h2>$VARDIR</h2>\n\n<p>It looks like you intend this script to be used at differing privileges level (e.g. root and non-root). This will change the <code>$HOME</code> env variable and consequently the <code>$VARDIR</code> env variable. Potentially <code>{add,rm}_host</code> may act on different files to <code>{start,stop}_block</code>. Note that this won't present itself if you only use sudo. </p>\n\n<p>Reconsider what you want <code>$VARDIR</code> to be. On a a single user machine <code>/var/</code> may be a good choice. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-21T11:57:48.473", "Id": "17630", "Score": "0", "body": "Unfortunately Vim runs into problems when trying to syntax highlight `$(…)` but I’d still recommend it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-23T11:27:32.490", "Id": "17682", "Score": "0", "body": "Yes, that is annoying. I find that reloading the file will help for all existing `$(...)`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T17:21:42.450", "Id": "10911", "ParentId": "10910", "Score": "4" } }, { "body": "<p>For <code>ls</code>, do not print <code>Empty</code> if there is no hosts blocked. The correct way is to be silent if you find no data. This will (assuming some one else uses it) allow them not to special case the Empty case. That is the below should suffice.\n case ls | list)\n cut -f2 -d\\ &lt; \"$BLCK_FILE\";;</p>\n\n<p>Another style point. You might want to consider avoiding the superfluous quotes. That is, use case ls) rather than case 'ls'). I think the former is more often used, and clearer.</p>\n\n<p>Consider also that it could be used from a cron (to switch at particular times of the day.) So it might be better to assume that you don't have access to <code>$HOME</code> (As mentioned in the above comment)</p>\n\n<p><code>{start,stop}_block</code> consider using <code>exit 1</code> to indicate error. Perhaps</p>\n\n<pre><code>start_block()\n{\n [[ $IS_ACTIVE -ne 0 ]] || {exit 1}\n cp \"$HOST_FILE\" \"$ORIG_FILE\"\n cat \"$BLCK_FILE\" &gt;&gt; \"$HOST_FILE\"\n touch \"$ACTIVE_FLAG\"\n echo \"Block started.\"\n}\n</code></pre>\n\n<p>You might also want to think what the behavior would be, when you add a new host when a block is already in effect.</p>\n\n<p>I am not sure why you would need this. You are already doing this in <code>start_block</code></p>\n\n<pre><code># Make sure files exist.\n[[ -e $ORIG_FILE ]] || touch \"$ORIG_FILE\"\n</code></pre>\n\n<p>It is cleaner to use <code>id -g</code> rather than whoami.</p>\n\n<p>Your check_root may be better expressed as below because this is the only check you need to do.</p>\n\n<pre><code>check_root()\n{\n if [[ -w $HOST_FILE ]]; then\n echo \"You don't have sufficient priviledges to access $HOST_FILE\"\n exit 1\n fi\n}\n</code></pre>\n\n<p>It is considered a better practice in Unix to be silent when there is not much information to be added.</p>\n\n<pre><code># explode args into lines.\nargx() {\n for var in \"$@\"; do\n echo $var\n done\n}\nadd_host()\n{\n argx | sed -e 's/^/127.0.0.1 /g' &gt;&gt; \"$BLCK_FILE\"\n}\n\n# you can use comm to print a list of removed files.\nrm_host()\n{\n cat \"$BLCK_FILE\" |sort -u |comm -13 &lt;(argx |sort -u) - &gt; \"$BLCK_TEMP\"\n mv \"$BLCK_TEMP\" \"$BLCK_FILE\"\n}\n</code></pre>\n\n<p>You can reduce active flag checking to</p>\n\n<pre><code>ACTIVE_FLAG=\"$HOME/.wrk_block.flag\"\nIS_ACTIVE=$(test -e $ACTIVE_FLAG; echo $?)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T02:16:15.847", "Id": "11025", "ParentId": "10910", "Score": "2" } }, { "body": "<p>Your code is written very clearly and easy to read. </p>\n\n<ol>\n<li><p>I am only proficient in ksh programming but as far as I can see in your subroutines you loop through your argument list skipping the first entry. if you augment your command syntax and the hostlist now starts with the third argument you have to change the script at a lot of different places. this is annoying and error prone. so I would prefer assigning the arguments to named parameters as early as possible at least for all but the hosts, so</p>\n\n<pre><code>COMMAND=$1\nshift\n</code></pre></li>\n<li><p>I would write data to <code>stdout</code> but messages to <code>stderr</code>. Especially error messages or warnings should be written to <code>stderr</code>. the usage message also should be written to standard error</p></li>\n<li><p>I doubt that</p>\n\n<pre><code>BLCK_TEMP=`mktemp -t \"blocked_hosts\"` || `mktemp /tmp/blocked_hosts.XXXXXXX` || exit 1 \n</code></pre>\n\n<p>will work as you expected. You should test it.</p></li>\n<li><p>why not always use the directory <code>mktemp /tmp/blocked_hosts.XXXXXXX</code> or better <code>mktemp -t blocked_hosts.XXXXXXX</code>. </p></li>\n<li><p>if <code>mktemp -t \"blocked_hosts\"</code> is alreday in use why do you want to use <code>mktemp /tmp/blocked_hosts.XXXXXXX</code> (maybe this is in a different directory) and not <code>mktemp -t blocked_hosts.XXXXXXX</code>?</p></li>\n<li><p>I would write all constants a block of contiguous lines so</p>\n\n<pre><code>HOST_FILE=\"/etc/hosts\"\nORIG_FILE=\"$VARDIR/original_host\" \nACTIVE_FLAG=\"$HOME/.wrk_block.flag\" \n</code></pre>\n\n<p>The they are easy to find and to modify</p></li>\n<li><p>I would prefer error-codes different from <code>1</code> but errorcodes specific for my application. <code>1</code> is often generated by other commands. Also I would use different error codes for different errors.</p></li>\n<li><p>If I am using a command I did not need any messages that the command was successfully executed. Tools like <code>cron</code> generate mails if a command produces messages and mails them to the user. messages are necessary if something unexpected happens that perhaps needs special actions from the user. if the command executes successfully and nothing special happens this should not be told to the user or the calling program.</p></li>\n<li><p>I don't like/need/want coloured messages. Often I am not able to read them. </p></li>\n<li><p>If something unexpected happens I try to exit the script. This can be achieved by setting <code>-e</code> or a <code>trap</code> for <code>ERR</code>. In this case I remove the created files too.</p></li>\n<li><p>Instead of </p>\n\n<pre><code>Usage: wrk [command] [host1 host2 ...] \n</code></pre>\n\n<p>you can do </p>\n\n<pre><code>Usage: $(basename $0) [command] [host1 host2 ...] \n</code></pre>\n\n<p>If someone renames the file the appropriate file name is substituted in the usage message. But I am not sure if one should support the renaming of the file.</p></li>\n<li><p>in the start_blocking function:</p>\n\n<pre><code>cp \"$HOST_FILE\" \"$ORIG_FILE\"\ncat \"$BLCK_FILE\" &gt;&gt; \"$HOST_FILE\"\ntouch \"$ACTIVE_FLAG\" \n</code></pre>\n\n<p>I would first do the lock (create the <code>$ACIVE_FLAG</code> file) and then do my actions.</p></li>\n<li><p>in the stop_blocking function:</p>\n\n<pre><code> [[ -e $ACTIVE_FLAG ]] &amp;&amp; rm \"$ACTIVE_FLAG\" \n</code></pre>\n\n<p>if there is no <code>$ACTIVE_FLAG</code> I think that is worth a message to the user. I am not sure If you should proceed in this case and copy to the hosts file</p></li>\n<li><p>Related to:</p>\n\n<pre><code>cp \"$HOST_FILE\" \"$ORIG_FILE\" \ncat \"$BLCK_FILE\" &gt;&gt; \"$HOST_FILE\" \n</code></pre>\n\n<p>why <code>cp</code>in the first line and <code>cat</code> with <code>&gt;&gt;</code> in the next line. Is there a difference?</p></li>\n<li><p>will <code>$ACTIVE_FLAG</code> always be the same, also if a user executes the scrips with sudo or su(i don't know much about this). I think it should be a directory independent from the user and user settings</p></li>\n<li><p>you should test your code so that each command is executed at least once. your code can be tested easily because you can change the global variables so that you do no actually change a /etc/hosts file</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-21T09:59:08.727", "Id": "11057", "ParentId": "10910", "Score": "3" } } ]
{ "AcceptedAnswerId": "11057", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T15:38:12.703", "Id": "10910", "Score": "3", "Tags": [ "security", "bash", "linux" ], "Title": "Bash script to swap out, edit host files" }
10910
<p>I'm trying to put lots of buttons inside a div with a bunch of little windows that make content change in a neighbor div, but I’m quite new to jQuery and I'm sure that this code can be much simpler.</p> <p>It works, but it's just that I can see it's too long and repetitive I'm sure that it can be downsized.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>jQuery(function($) { function boton1(event) { $(".vitrina1").css("opacity","0"); $(".vitrina1").css("top","0"); $(".vitrina1").animate({"opacity":1,"top":0},300, "linear", null); $(".vitrina2").animate({"top":712},1, "linear", null); $(".vitrina3").animate({"top":1424},1, "linear", null); $(".vitrina4").animate({"top":2136},1, "linear", null); $(".vitrina5").animate({"top":2848},1, "linear", null); $(".vitrina6").animate({"top":3560},1, "linear", null); $(".vitrina7").animate({"top":4272},1, "linear", null); $(".vitrina8").animate({"top":4984},1, "linear", null); $(".vitrina9").animate({"top":5696},1, "linear", null); $(".vitrina10").animate({"top":6408},1, "linear", null); $(".vitrina11").animate({"top":7120},1, "linear", null); $(".vitrina12").animate({"top":7832},1, "linear", null); } function boton2(event) { $(".vitrina2").css("opacity","0"); $(".vitrina2").css("top","-712px"); $(".vitrina2").animate({"opacity":1,"top":-712},300, "linear", null); $(".vitrina1").animate({"top":712},1, "linear", null); $(".vitrina3").animate({"top":1424},1, "linear", null); $(".vitrina4").animate({"top":2136},1, "linear", null); $(".vitrina5").animate({"top":2848},1, "linear", null); $(".vitrina6").animate({"top":3560},1, "linear", null); $(".vitrina7").animate({"top":4272},1, "linear", null); $(".vitrina8").animate({"top":4984},1, "linear", null); $(".vitrina9").animate({"top":5696},1, "linear", null); $(".vitrina10").animate({"top":6408},1, "linear", null); $(".vitrina11").animate({"top":7120},1, "linear", null); $(".vitrina12").animate({"top":7832},1, "linear", null); } function boton3(event) { $(".vitrina3").css("opacity","0"); $(".vitrina3").css("top","-1424px"); $(".vitrina3").animate({"opacity":1,"top":-1424},300, "linear", null); $(".vitrina1").animate({"top":712},1, "linear", null); $(".vitrina2").animate({"top":712},1, "linear", null); $(".vitrina4").animate({"top":2136},1, "linear", null); $(".vitrina5").animate({"top":2848},1, "linear", null); $(".vitrina6").animate({"top":3560},1, "linear", null); $(".vitrina7").animate({"top":4272},1, "linear", null); $(".vitrina8").animate({"top":4984},1, "linear", null); $(".vitrina9").animate({"top":5696},1, "linear", null); $(".vitrina10").animate({"top":6408},1, "linear", null); $(".vitrina11").animate({"top":7120},1, "linear", null); $(".vitrina12").animate({"top":7832},1, "linear", null); } function boton4(event) { $(".vitrina4").css("opacity","0"); $(".vitrina4").css("top","-2136px"); $(".vitrina4").animate({"opacity":1,"top":-2136},300, "linear", null); $(".vitrina1").animate({"top":712},1, "linear", null); $(".vitrina2").animate({"top":712},1, "linear", null); $(".vitrina3").animate({"top":1424},1, "linear", null); $(".vitrina5").animate({"top":2848},1, "linear", null); $(".vitrina6").animate({"top":3560},1, "linear", null); $(".vitrina7").animate({"top":4272},1, "linear", null); $(".vitrina8").animate({"top":4984},1, "linear", null); $(".vitrina9").animate({"top":5696},1, "linear", null); $(".vitrina10").animate({"top":6408},1, "linear", null); $(".vitrina11").animate({"top":7120},1, "linear", null); $(".vitrina12").animate({"top":7832},1, "linear", null); } function boton5(event) { $(".vitrina5").css("opacity","0"); $(".vitrina5").css("top","-2848px"); $(".vitrina5").animate({"opacity":1,"top":-2848},300, "linear", null); $(".vitrina1").animate({"top":712},1, "linear", null); $(".vitrina2").animate({"top":712},1, "linear", null); $(".vitrina3").animate({"top":1424},1, "linear", null); $(".vitrina4").animate({"top":2136},1, "linear", null); $(".vitrina6").animate({"top":3560},1, "linear", null); $(".vitrina7").animate({"top":4272},1, "linear", null); $(".vitrina8").animate({"top":4984},1, "linear", null); $(".vitrina9").animate({"top":5696},1, "linear", null); $(".vitrina10").animate({"top":6408},1, "linear", null); $(".vitrina11").animate({"top":7120},1, "linear", null); $(".vitrina12").animate({"top":7832},1, "linear", null); } function boton6(event) { $(".vitrina6").css("opacity","0"); $(".vitrina6").css("top","-3560px"); $(".vitrina6").animate({"opacity":1,"top":-3560},300, "linear", null); $(".vitrina1").animate({"top":712},1, "linear", null); $(".vitrina2").animate({"top":712},1, "linear", null); $(".vitrina3").animate({"top":1424},1, "linear", null); $(".vitrina4").animate({"top":2136},1, "linear", null); $(".vitrina5").animate({"top":2848},1, "linear", null); $(".vitrina7").animate({"top":4272},1, "linear", null); $(".vitrina8").animate({"top":4984},1, "linear", null); $(".vitrina9").animate({"top":5696},1, "linear", null); $(".vitrina10").animate({"top":6408},1, "linear", null); $(".vitrina11").animate({"top":7120},1, "linear", null); $(".vitrina12").animate({"top":7832},1, "linear", null); } function boton7(event) { $(".vitrina7").css("opacity","0"); $(".vitrina7").css("top","-4272px"); $(".vitrina7").animate({"opacity":1,"top":-4272},300, "linear", null); $(".vitrina1").animate({"top":712},1, "linear", null); $(".vitrina2").animate({"top":712},1, "linear", null); $(".vitrina3").animate({"top":1424},1, "linear", null); $(".vitrina4").animate({"top":2136},1, "linear", null); $(".vitrina5").animate({"top":2848},1, "linear", null); $(".vitrina6").animate({"top":3560},1, "linear", null); $(".vitrina8").animate({"top":4984},1, "linear", null); $(".vitrina9").animate({"top":5696},1, "linear", null); $(".vitrina10").animate({"top":6408},1, "linear", null); $(".vitrina11").animate({"top":7120},1, "linear", null); $(".vitrina12").animate({"top":7832},1, "linear", null); } function boton8(event) { $(".vitrina8").css("opacity","0"); $(".vitrina8").css("top","-4984px"); $(".vitrina8").animate({"opacity":1,"top":-4984},300, "linear", null); $(".vitrina1").animate({"top":712},1, "linear", null); $(".vitrina2").animate({"top":712},1, "linear", null); $(".vitrina3").animate({"top":1424},1, "linear", null); $(".vitrina4").animate({"top":2136},1, "linear", null); $(".vitrina5").animate({"top":2848},1, "linear", null); $(".vitrina6").animate({"top":3560},1, "linear", null); $(".vitrina7").animate({"top":4272},1, "linear", null); $(".vitrina9").animate({"top":5696},1, "linear", null); $(".vitrina10").animate({"top":6408},1, "linear", null); $(".vitrina11").animate({"top":7120},1, "linear", null); $(".vitrina12").animate({"top":7832},1, "linear", null); } function boton9(event) { $(".vitrina9").css("opacity","0"); $(".vitrina9").css("top","-5696px"); $(".vitrina9").animate({"opacity":1,"top":-5696},300, "linear", null); $(".vitrina1").animate({"top":712},1, "linear", null); $(".vitrina2").animate({"top":712},1, "linear", null); $(".vitrina3").animate({"top":1424},1, "linear", null); $(".vitrina4").animate({"top":2136},1, "linear", null); $(".vitrina5").animate({"top":2848},1, "linear", null); $(".vitrina6").animate({"top":3560},1, "linear", null); $(".vitrina7").animate({"top":4272},1, "linear", null); $(".vitrina8").animate({"top":4984},1, "linear", null); $(".vitrina10").animate({"top":6408},1, "linear", null); $(".vitrina11").animate({"top":7120},1, "linear", null); $(".vitrina12").animate({"top":7832},1, "linear", null); } function boton10(event) { $(".vitrina10").css("opacity","0"); $(".vitrina10").css("top","-6408px"); $(".vitrina10").animate({"opacity":1,"top":-6408},300, "linear", null); $(".vitrina1").animate({"top":712},1, "linear", null); $(".vitrina2").animate({"top":712},1, "linear", null); $(".vitrina3").animate({"top":1424},1, "linear", null); $(".vitrina4").animate({"top":2136},1, "linear", null); $(".vitrina5").animate({"top":2848},1, "linear", null); $(".vitrina6").animate({"top":3560},1, "linear", null); $(".vitrina7").animate({"top":4272},1, "linear", null); $(".vitrina8").animate({"top":4984},1, "linear", null); $(".vitrina9").animate({"top":5696},1, "linear", null); $(".vitrina11").animate({"top":7120},1, "linear", null); $(".vitrina12").animate({"top":7832},1, "linear", null); } function boton11(event) { $(".vitrina11").css("opacity","0"); $(".vitrina11").css("top","-7120px"); $(".vitrina11").animate({"opacity":1,"top":-7120},300, "linear", null); $(".vitrina1").animate({"top":712},1, "linear", null); $(".vitrina2").animate({"top":712},1, "linear", null); $(".vitrina3").animate({"top":1424},1, "linear", null); $(".vitrina4").animate({"top":2136},1, "linear", null); $(".vitrina5").animate({"top":2848},1, "linear", null); $(".vitrina6").animate({"top":3560},1, "linear", null); $(".vitrina7").animate({"top":4272},1, "linear", null); $(".vitrina8").animate({"top":4984},1, "linear", null); $(".vitrina9").animate({"top":5696},1, "linear", null); $(".vitrina10").animate({"top":6408},1, "linear", null); $(".vitrina12").animate({"top":7832},1, "linear", null); } function boton12(event) { $(".vitrina12").css("opacity","0"); $(".vitrina12").css("top","-7832px"); $(".vitrina12").animate({"opacity":1,"top":-7832},300, "linear", null); $(".vitrina1").animate({"top":712},1, "linear", null); $(".vitrina2").animate({"top":712},1, "linear", null); $(".vitrina3").animate({"top":1424},1, "linear", null); $(".vitrina4").animate({"top":2136},1, "linear", null); $(".vitrina5").animate({"top":2848},1, "linear", null); $(".vitrina6").animate({"top":3560},1, "linear", null); $(".vitrina7").animate({"top":4272},1, "linear", null); $(".vitrina8").animate({"top":4984},1, "linear", null); $(".vitrina9").animate({"top":5696},1, "linear", null); $(".vitrina10").animate({"top":6408},1, "linear", null); $(".vitrina11").animate({"top":7120},1, "linear", null); } $('#btn1').bind('click', boton1); $('#btn2').bind('click', boton2); $('#btn3').bind('click', boton3); $('#btn4').bind('click', boton4); $('#btn5').bind('click', boton5); $('#btn6').bind('click', boton6); $('#btn7').bind('click', boton7); $('#btn8').bind('click', boton8); $('#btn9').bind('click', boton9); $('#btn10').bind('click', boton10); $('#btn11').bind('click', boton11); $('#btn12').bind('click', boton12); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#contenedorPrimario { position:relative;margin-left:auto;margin-right:auto;width:100%; background: url(../imagenes/fondo_index.jpg); width: 1100px; height: 800px;} .clear {clear:both;} #aparador {position:absolute; margin-top: 50px; margin-left: 456px; width:641px;overflow: hidden; height:712px; background:#666; margin-right: 20px; } #mercancia {position:absolute; width: 641px; height: 9324px; margin-top: 0px; visibility: visible; background: #fff; } .vitrina1, .vitrina2, .vitrina3, .vitrina4, .vitrina5, .vitrina6, .vitrina7, .vitrina8, .vitrina9, .vitrina10, .vitrina11, .vitrina12 { position:relative; width:641px; height: 712px; } .vitrina1 { /*background-color: #33CCCC;*/ background: #D2D2D2;} .vitrina2 { background-color: #999900;} .vitrina3 { background-color: #CC6600;} .vitrina4 { background-color: #AA0000;} .vitrina5 { background-color: #99CC33;} .vitrina6 { background-color: #0066CC;} .vitrina7 { background-color: #570699;} .vitrina8 { background-color: #CC33CC;} .vitrina9 { background-color: #02F965;} .vitrina10 { background-color: #FFFF00;} .vitrina11 { background-color: #C80461;} .vitrina12 { background-color: #000066;}</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div id="contenedorPrimario"&gt; &lt;div id="botones"&gt; &lt;div class="boton" id="btn1"&gt;&lt;a class="tooltip" rel="Contenedor 1"&gt;&lt;img src="imagenes/imagen1.jpg"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="boton" id="btn2"&gt;&lt;a class="tooltip" rel="Cajón&lt;br&gt;Contenedor 2"&gt;&lt;img src="imagenes/imagen2.jpg"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="boton" id="btn3"&gt;&lt;a class="tooltip" rel="Este es el Contendor&lt;br&gt;#3 Cajón 3"&gt;&lt;img src="imagenes/imagen3.jpg"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="boton" id="btn4"&gt;&lt;a class="tooltip" rel="Ejemplo de contenido&lt;br&gt;dentro del cajón&lt;br&gt;Contenedor 4"&gt;&lt;img src="imagenes/imagen4.jpg"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="boton" id="btn5"&gt;&lt;a class="tooltip" rel="Aqui texto"&gt;&lt;img src="imagenes/imagen5.jpg"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="boton" id="btn6"&gt;&lt;a class="tooltip" rel="Aqui texto"&gt;&lt;img src="imagenes/imagen6.jpg"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="boton" id="btn7"&gt;&lt;a class="tooltip" rel="Aqui texto"&gt;&lt;img src="imagenes/imagen7.jpg"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="boton" id="btn8"&gt;&lt;a class="tooltip" rel="Aqui texto"&gt;&lt;img src="imagenes/imagen8.jpg"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="boton" id="btn9"&gt;&lt;a class="tooltip" rel="Aqui texto"&gt;&lt;img src="imagenes/imagen9.jpg"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="boton" id="btn10"&gt;&lt;a class="tooltip" rel="Aqui texto"&gt;&lt;img src="imagenes/imagen10.jpg"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="boton" id="btn11"&gt;&lt;a class="tooltip" rel="Aqui texto"&gt;&lt;img src="imagenes/imagen11.jpg"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="boton" id="btn12"&gt;&lt;a class="tooltip" rel="Aqui texto"&gt;&lt;img src="imagenes/imagen12.jpg"&gt;&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id="sociales"&gt;Aqui van los iconos que controlan &lt;a id="redes2" href="#"&gt;redes sociales&lt;/a&gt; y el player&lt;/div&gt; &lt;div id="aparador"&gt; &lt;div id="mercancia"&gt; &lt;div class="vitrina1"&gt;&lt;img src="imagenes/principal_pic.jpg" width="652" height="568" alt=""&gt;&lt;h2&gt;Entra a la nueva era&lt;/h2&gt;&lt;/div&gt; &lt;div class="vitrina2"&gt;Hola 2&lt;/div&gt; &lt;div class="vitrina3"&gt;Hola 3&lt;/div&gt; &lt;div class="vitrina4"&gt;Hola 4&lt;/div&gt; &lt;div class="vitrina5"&gt;Hola 5&lt;/div&gt; &lt;div class="vitrina6"&gt;Hola 6&lt;/div&gt; &lt;div class="vitrina7"&gt;Hola 7&lt;/div&gt; &lt;div class="vitrina8"&gt;Hola 8&lt;/div&gt; &lt;div class="vitrina9"&gt;Hola 9&lt;/div&gt; &lt;div class="vitrina10"&gt;Hola 10&lt;/div&gt; &lt;div class="vitrina11"&gt;Hola 11&lt;/div&gt; &lt;div class="vitrina12"&gt;Hola 12&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>There, the thumbs or <code>boton</code>s on the left must change the content on the right.</p>
[]
[ { "body": "<p>It is very difficult to tell what you are trying to do from you code, but here is a very general example of a cleanup I would do on your code based on some assumptions.</p>\n\n<p><a href=\"http://jsfiddle.net/tgcNd/1\" rel=\"nofollow\">http://jsfiddle.net/tgcNd/1</a></p>\n\n<ol>\n<li><p>Combine your css changes into a single statement as Jonathjan Sampson suggested. </p>\n\n<pre><code>$(selector).css( { opacity: \"0\", top: \"0\" });\n</code></pre></li>\n<li><p>Alon has another valid point which is method chaining. This increases performance by decreasing the number of jQuery object looksups.</p>\n\n<pre><code>$(selector).css().css().animate(); //etc\n</code></pre></li>\n<li><p>Use jQuerys <code>on</code> for your event binding. Assuming the buttons share a parent you can monitor that parent for button presses. This reduces the number of bound events and increases performance.</p>\n\n<pre><code>$('#buttoncontainer').on('click', 'button', function() { ... });\n</code></pre></li>\n<li><p>Use a class or a general function so that you are not repeating code over and over again. In this simplified example I change the clicked button's state and then make a change to all other buttons by making use of the <code>not</code> method.</p>\n\n<pre><code>$(this).css( { opacity: \"0\", top: \"0\" });\n$('button').not(this).each(function() {\n console.log('animating button: ' + this.innerHTML);\n $(this).animate({\n //animate\n }, 1, \"linear\", null);\n});\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T03:36:13.123", "Id": "17355", "Score": "0", "body": "Sorry, you’re right... I posted the rest of the code, my screen is split in two, on the left I have this 12 tiles, every time I click in one of theme, any of them, the content on the right changes, fade in fade out so on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T03:56:25.890", "Id": "17356", "Score": "0", "body": "There are far better ways to do this (as you surmised). See this example. http://jsfiddle.net/dLGvg/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T04:00:14.067", "Id": "17357", "Score": "0", "body": "And this is the code working http://jsfiddle.net/tgcNd/4/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T04:13:58.017", "Id": "17358", "Score": "0", "body": "My God, that's it... it does the same but whiteout a thousand lines... Thank you, Thank you.\nThis is great. I promise Ill learn from it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T04:28:13.357", "Id": "17359", "Score": "0", "body": "one thing only, the content from the windows on the right are queried from a database...\nwill this work as well?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T04:35:48.460", "Id": "17360", "Score": "0", "body": "Yes, that can certainly work. My code just use the source of the thumbnail to set the main images src. But instead you could store on the thumbnail the main image's url. You can see how to do that in this fiddle - http://jsfiddle.net/BPtkC/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T04:50:33.660", "Id": "17361", "Score": "0", "body": "I tried it but it didnt work... http://jsfiddle.net/dLGvg/2/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T08:18:48.337", "Id": "17362", "Score": "0", "body": "The thing is, I'm not displaying images to the right, every div from the scrollable area has text-and different media content. It´s not a gallery." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T02:52:17.887", "Id": "10915", "ParentId": "10914", "Score": "1" } }, { "body": "<p><strong>EDIT:</strong> This is a new answer now that we see the HTML and understand what the OP is actually trying to do. There is a much, much simpler way to do this.</p>\n\n<p>Conceptually, instead of maintaining manually controlled relative positions of every <code>.vitrinaX</code> div, we just make them all absolutely positioned on top of one another with only one div visible at a time. To show a new one, we <code>fadeOut()</code> the current one (which we maintain a reference to with an <code>active</code> class and <code>fadeIn()</code> the new one. Since they are all on top of one another, it makes a smooth opacity transition from one to the other.</p>\n\n<p>Here's a working demo: <a href=\"http://jsfiddle.net/jfriend00/4UmQ5/\" rel=\"nofollow\">http://jsfiddle.net/jfriend00/4UmQ5/</a></p>\n\n<p>You can change ALL of your Javascript to this:</p>\n\n<pre><code>jQuery(function($) {\n $(\".boton\").click(function() {\n var id = this.id.replace(\"btn\", \"\");\n $(\"#mercancia .active\").removeClass(\"active\").fadeOut();\n $(\".vitrina\" + id).fadeIn().addClass(\"active\");\n });\n});\n</code></pre>\n\n<p>And, change this part of your CSS from this:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.vitrina1, .vitrina2, .vitrina3, .vitrina4, \n.vitrina5, .vitrina6, .vitrina7, .vitrina8, \n.vitrina9, .vitrina10, .vitrina11, .vitrina12 { \n position:relative; \n width:641px; \n height: 712px; \n }\n.vitrina1 { /*background-color: #33CCCC;*/ background: #D2D2D2;}\n</code></pre>\n\n<p>to this:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.vitrina1, .vitrina2, .vitrina3, .vitrina4, \n.vitrina5, .vitrina6, .vitrina7, .vitrina8, \n.vitrina9, .vitrina10, .vitrina11, .vitrina12 { \n position:absolute; \n width:641px; \n height: 712px; \n display: none;\n}\n.vitrina1 { \n /*background-color: #33CCCC;*/ background: #D2D2D2; \n display: block;\n}\n</code></pre>\n\n<p>And, then in your HTML, add the \"active\" class to this line:</p>\n\n<pre><code>&lt;div class=\"vitrina1 active\"&gt;Hola-Hello this his window #1&lt;/div&gt;\n</code></pre>\n\n<hr>\n\n<p>Here's the original answer before the actual HTML and actual rendering intent was disclosed</p>\n\n<p>It would be useful to both see the HTML and understand what you're really trying to do here. It may be much easier to add some appropriate classes and do things a simpler way, but we can't really tell without seeing the whole problem including the HTML and a description of what you're really trying to accomplish.</p>\n\n<p>From purely studying your code, it can be deduced to a pattern and that pattern can be generated with javascript rather than repeatedly typed out. Here's my first analysis of deducing the pattern to a couple loops of code. There's one loop to create each event handler and another loop inside each event handler to loop through each item and apply the desired change to each one:</p>\n\n<pre><code>jQuery(function ($) {\n for (var i = 1; i &lt;= 12; i++) {\n (function(i) {\n $(\"#btn\" + i).click(function (event) {\n $(\".vitrina\" + i).css({opacity: 0, top: 0});\n for (var j = 1; j &lt;= 12; j++) {\n var topVal = j - 1;\n if (j == i) {\n topVal = -topVal;\n }\n $(\".vitrina\" + j).animate({top: topVal * 712}, 1, \"linear\");\n }\n });\n })(i);\n }\n}); \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T03:14:44.550", "Id": "17363", "Score": "0", "body": "OK, thanks’ for such a fast response every one, and yes mrtsherman you’re right, here is the rest of the code ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T03:59:49.870", "Id": "17364", "Score": "0", "body": "Here you can see it in action.. http://jsfiddle.net/tgcNd/4/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T05:59:50.923", "Id": "17365", "Score": "0", "body": "@SamRamSan - can you describe what visual effect are you trying to achieve? All, I see is one div to the right moving into the visible position when you click on a square and I see no animation. That effect can be achieved very, very simply with 1/100th the complication you have now. Unless, there's supposed to be more to the switch than I currently see. Please explain what you are trying to achieve." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T07:51:38.033", "Id": "17366", "Score": "0", "body": "OK, I have as you can see, 12 tiles the left, those tiles are to be generated from a MySqk database, and will show a thumbnail.. when clicking on the thumb, the content on the right div will be populated from data coming from mysql as well.\n\nIts working ok but. The code for the whole thing is just too big, and repetitive. Now the info from the right will have or does have a slight fade out and fade in every time on or other tile is clicked. It’s already working, but it’s just very repetitive. \nThanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T16:41:16.597", "Id": "17367", "Score": "0", "body": "@SamRamSan - I've proposed a radically simpler idea that replaces all your code with 7 lines of code and needs a couple corresponding changes in HTML/CSS." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T02:52:25.367", "Id": "10916", "ParentId": "10914", "Score": "1" } }, { "body": "<p>I've no way to try this out, but with your actual code, without changin classes etc, this seems like the obvious way to do it, but maybe not the best...</p>\n\n<pre><code>var max = 12;\nvar animVitrina = function (btn) {\n var _ival = 712,\n _top = - ((btn - 1) * _ival);\n $('.vitrina' + btn).css({\n opacity : 0,\n top : _top\n }, 300).animate({\n opacity : 1,\n top : _top\n });\n _top = 0;\n for (var i = 1; i &lt; max; i++, _top += _ival) {\n if (i !== btn) {\n $('.vitrina' + i).animate({\n top : _top\n });\n }\n }\n};\nfor (var i = 1; i &lt; max; i++) {\n $('#btn' + i).on('click', animVitrina(i));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T04:00:36.203", "Id": "17368", "Score": "0", "body": "here you can see it at work http://jsfiddle.net/tgcNd/4/" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T02:57:16.747", "Id": "10917", "ParentId": "10914", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T02:34:44.307", "Id": "10914", "Score": "2", "Tags": [ "javascript", "beginner", "jquery", "html" ], "Title": "Inserting buttons inside a div" }
10914
<p>I just know there's a simpler, better way to do this. Will eventually append &lt;select&gt; options with these values (e.g. 01:30, 02:45, 10:15, etc.)</p> <pre><code>var arrHours=[] var i=0, j=0, k=0; for (i=0;i&lt;=23;i++) { for(j=0;j&lt;=45;j=j+15) { var m,n; m=i.toString(); n=j.toString(); if(m=="0") { m="00"; } if(m.length&lt;2) { m="0"+m; } if(n=="0") { n="00"; } arrHours.push(m+":"+n); } } for(k in arrHours) { $("#preview4").append(arrHours[k]+"&lt;BR&gt;"); } </code></pre> <p><em>ps. I prefer the semicolon</em>. ;)</p>
[]
[ { "body": "<p>I would do it like this. Note how the zero-padding is encapsulated in a function and how the double loops are turned into a single loop by using modulo and integer division. Also, the <code>var</code>s are pre-declared as is considered good style in JavaScript.</p>\n\n<pre><code>function zeroPad(number) {\n if (number &lt;= 9) {\n return \"0\" + number;\n } else {\n return number;\n }\n}\n\nvar i, hour, minute,\n arrHours = [];\nfor (i = 0; i &lt; 60 * 24; i += 15) {\n hour = Math.floor(i / 60);\n minute = i % 60;\n arrHours.push(zeroPad(hour) + \":\" + zeroPad(minute));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T12:42:05.520", "Id": "17381", "Score": "0", "body": "+0: I think it's much less readable to merge the two `for`s and use modulo and division; the rest of the suggestions are great though, good job." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T14:25:08.710", "Id": "17384", "Score": "0", "body": "It seems like this would also be faster by looping only once as well, right? Or, at the very least, consume less memory. This makes more sense to me than what I was doing. Thanks Raba." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T08:11:54.057", "Id": "10924", "ParentId": "10922", "Score": "4" } }, { "body": "<p>I would unroll the minutes loop to make code more readable:</p>\n\n<pre><code>var times = [], hour, i;\n\nfor (i = 0; i &lt; 24; ++i) {\n hour = (i &lt; 10 ? '0' : '') + i;\n times.push(hour + ':00');\n times.push(hour + ':15');\n times.push(hour + ':30');\n times.push(hour + ':45');\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-24T20:10:56.937", "Id": "11143", "ParentId": "10922", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T06:14:33.227", "Id": "10922", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Is there a \"code less\" way to construct this JS loop?" }
10922
<p>I've searched plenty on this topic and have gotten a lot of good (but different) results. Some of the results weren't quite related and it does seem to be a matter of preference in the end, but <strong>I'm interested in if I'm following good design principles or not</strong>.</p> <p><strong>If this is too vague of a question, feel free to delete it, but can you recommend where I post it instead?</strong></p> <p>Also, this is <strong>just an example</strong>. There are quite a few things in here I would normally do differently but for the sake of simplicity, I did it this way.</p> <p><strong>The code is long, but you should be able to just copy &amp; paste it directly into a single new PHP file and run it in your environment; there is no setup required.</strong></p> <h1>Specific questions</h1> <ul> <li>Is this the correct way to use exceptions and handle them on the caller side?</li> <li>Should I even be using exceptions for this?</li> <li>Are my skeleton custom exceptions correct?</li> </ul> <h1>Code</h1> <p>You can view a copy in a separate window <a href="http://codepad.org/yXAB9oEa" rel="nofollow">here</a>. I will paste it here. Save it and run it in your environment, it should work as-is without any modifications:</p> <h2>Beware: long code ahead</h2> <pre><code>&lt;?php error_reporting ( E_ALL | E_STRICT ); class MemberLoginException extends Exception { } class AccountsInsertException extends Exception { } class AccountsManager { protected $_accounts = array (); protected $_lcUsernames = array (); # all usernames in lowercase for checking if username is taken public function __construct ( array $accounts = null ) { $this-&gt;setAllAccounts ( $accounts ); } public function __destruct () { unset ( $this-&gt;_accounts, $this-&gt;_lcUsernames ); } public function __toString () { $return = ''; if ( count ( $this-&gt;_accounts ) &gt; 0 ) : $return = '&lt;table&gt;'; $return .= '&lt;tr&gt;&lt;th&gt;Username&lt;/th&gt;&lt;th&gt;Password&lt;/th&gt;&lt;/tr&gt;'; foreach ( $this-&gt;_accounts as $account ) : $return .= '&lt;tr&gt; &lt;td&gt;'. htmlentities ( $account['username'], ENT_QUOTES, 'UTF-8' ) . '&lt;/td&gt; &lt;td&gt;'. htmlentities ( $account['password'], ENT_QUOTES, 'UTF-8' ) . '&lt;/td&gt; &lt;/tr&gt;'; endforeach; $return .= '&lt;/table&gt;'; return $return; endif; } public function Clear () { $this-&gt;_accounts = array (); $this-&gt;_lcUsernames = array (); } public function Authenticate ( Member $member ) { $username = strtolower ( $member-&gt;getUsername () ); if ( count ( $this-&gt;_accounts ) ) : foreach ( $this-&gt;_accounts as $account ) : if ( strtolower ( $account['username'] ) == $username ) return ( bool ) ( $account['password'] == $member-&gt;getPassword () ); endforeach; else : return false; endif; } public function getAllAccounts () { return $this-&gt;_accounts; } public function setAllAccounts ( array $newValue = null ) { if ( is_null ( $newValue ) ) $this-&gt;_accounts = array (); else $this-&gt;_accounts = $newValue; $this-&gt;_lcUsernames = array (); foreach ( $this-&gt;_accounts as $account ) $this-&gt;_lcUsernames[] = strtolower ( $account['username'] ); return $this; } public function hasAccount ( $username ) { return in_array ( strtolower ( $username ), $this-&gt;_lcUsernames, false ); } public function AddAccount ( $username, $password ) { /* Faster to be redundant by storing a lowercase copy of the username for comparison if ( array_key_exists ( strtolower ( $username ), array_change_key_case ( $this-&gt;_accounts ) ) ) throw new AccountsInsertException ( 'Unable to create account; account already exists.' ); */ if ( $this-&gt;hasAccount ( $username ) ) throw new AccountsInsertException ( 'Unable to create account; account already exists.' ); $this-&gt;_accounts[] = array ( 'username' =&gt; $username, 'password' =&gt; $password, ); $this-&gt;_lcUsernames[] = strtolower ( $username ); return $this; } public function RemoveAccount ( $username ) { if ( $this-&gt;hasAccount ( $username ) ) : unset ( $this-&gt;_accounts[$username] ); unset ( $this-&gt;_lcUsernames [ strtolower ( $username ) ] ); endif; return $this; } public function __Debug () { echo "\r&lt;pre&gt;\r"; print_r ( $this-&gt;_accounts ); echo "\r&lt;/pre&gt;\r\r\r&lt;pre&gt;\r"; print_r ( $this-&gt;_lcUsernames ); echo "\r&lt;/pre&gt;\r\r"; } } class Member { protected $_username = ''; protected $_password = ''; public function __construct ( $username, $password ) { $this-&gt;setUsername ( $username ); $this-&gt;setPassword ( $password ); } public function getUsername () { return $this-&gt;_username; } public function setUsername ( $newValue ) { $this-&gt;_username = ( string ) $newValue; return $this; } public function getPassword () { return $this-&gt;_password; } public function setPassword ( $newValue ) { $this-&gt;_password = ( string ) $newValue; return $this; } } # create a new accounts manager which stores all accounts and handles authentication # the Member class would be responsible for setting session variables, etc. Manager just checks user/pass. $manager = new AccountsManager (); ?&gt;&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8" /&gt; &lt;style&gt; * { font-family: "Segoe UI", "Trebuchet MS", Tahoma, Arial, Helvetica, sans-serif; } body { margin: 4em 6em; line-height: 1.6em; font-size: smaller; } header { border-bottom: 2px solid #efefef; margin-bottom: 3em; padding-bottom: 1em; } h1, h2, h3, h4, h5, h6 { font-weight: normal; letter-spacing: 1px; color: royalblue; } h5, h6 { font-weight: bold; } header h1 sub, header h1 sup { font-size: small; color: #FF4400; letter-spacing: 2px; } section { border-bottom: 1px dotted #ccc; padding-bottom: 2em; margin-bottom: 3em; } table { border: 1px solid #eee; padding: 1em; border-right-width: 2px; border-bottom-width: 2px; } th { text-align: left; font-variant: small-caps; border-bottom: 1px dotted #ccc; padding-bottom: .75em; margin-bottom: .75em; letter-spacing: 1px; color: #FF4400; } td:hover { background-color: skyblue; } td { margin: 0; display: table-cell; padding: .5em; } pre { font-family: "Droid Sans Mono", Consolas, "Courier New", Courier, monospaced; border: 1px solid #E4E4E4; padding: 1em; line-height: 1em; } .error { color: red; border: 1px dotted #ccc; } .success { color: forestgreen; border: 1px dotted #e0e0e0; } .error, .success { padding: .75em; background-color: #FFFFCC; border: 1px solid #E4E4E4; } &lt;/style&gt; &lt;title&gt;Sample Login System - Test Exceptions&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;h1&gt;Simple Login System &lt;sup&gt;demonstrating exceptions&amp;hellip;&lt;/sup&gt;&lt;/h1&gt; &lt;/header&gt; &lt;section&gt; &lt;h2&gt;No database required&lt;/h2&gt; &lt;p&gt;To avoid time setting up your environment, this test simply uses a class that stores an array of accounts. Obviously, this isn't persistent (at this time) and it doesn't actually save anything anywhere except in the array during the script's lifetime. Upon the next request, the previous accounts will be erased.&lt;/p&gt; &lt;/section&gt; &lt;section&gt; &lt;h2&gt;Creating accounts...&lt;/h2&gt; &lt;?php $createList = array ( array ( 'username' =&gt; 'Daniel Elkins', 'password' =&gt; 'delkins[not-pass-for-anything]', ), array ( 'username' =&gt; 'Jennifer Lynn', 'password' =&gt; 'lilJenn', ), array ( 'username'=&gt; 'Charlie Dog', 'password'=&gt; 'grrrrr', ), ); if ( $manager-&gt;setAllAccounts ( $createList ) instanceof AccountsManager ) : ?&gt; &lt;p&gt;&lt;strong&gt;Accounts were created successfully!&lt;/strong&gt; They should be listed in a table below.&lt;/p&gt; &lt;?php else : ?&gt; &lt;p class="error"&gt;There was an error creating your accounts...&lt;/p&gt; &lt;?php endif; ?&gt; &lt;/section&gt; &lt;section&gt; &lt;h2&gt;List of accounts&lt;/h2&gt; &lt;?php echo $manager; ?&gt; &lt;/section&gt; &lt;section&gt; &lt;h2&gt;Trying to create one that already exists...&lt;/h2&gt; &lt;?php try { $manager-&gt;AddAccount ( 'Daniel Elkins', 'delkins[not-pass-for-anything]'); ?&gt; &lt;p class="success"&gt;Account created successfully!&lt;/p&gt; &lt;?php } catch ( AccountsInsertException $exception ) { ?&gt; &lt;p class="error"&gt;&lt;?= $exception-&gt;getMessage (); ?&gt;&lt;/p&gt; &lt;?php } ?&gt; &lt;/section&gt; &lt;section&gt; &lt;h2&gt;Showing accounts again&lt;/h2&gt; &lt;?php echo $manager; ?&gt; &lt;/section&gt; &lt;section&gt; &lt;h2&gt;Valid login test&lt;/h2&gt; &lt;p&gt;Logging in user `Daniel Elkins`&amp;hellip;&lt;/p&gt; &lt;?php if ( $manager-&gt;Authenticate ( new Member ( 'Daniel Elkins', 'delkins[not-pass-for-anything]' ) ) ) : ?&gt; &lt;p class="success"&gt;Authentication successful!&lt;/p&gt; &lt;?php else : ?&gt; &lt;p class="error"&gt;Unable to login; invalid username or password!&lt;/p&gt; &lt;?php endif; ?&gt; &lt;/section&gt; &lt;section&gt; &lt;h2&gt;&lt;strong&gt;Invalid&lt;/strong&gt; login test&lt;/h2&gt; &lt;p&gt;Logging in user `Doesnt_Exist`&amp;hellip;&lt;/p&gt; &lt;?php if ( $manager-&gt;Authenticate ( new Member ( 'Doesnt_Exist', '1234' ) ) ) : ?&gt; &lt;p class="success"&gt;Authentication successful!&lt;/p&gt; &lt;?php else : ?&gt; &lt;p class="error"&gt;Unable to login; invalid username or password!&lt;/p&gt; &lt;?php endif; ?&gt; &lt;/section&gt; &lt;section&gt; &lt;h2&gt;Debug information&lt;/h2&gt; &lt;?php $manager-&gt;__Debug (); ?&gt; &lt;/section&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-25T05:55:56.547", "Id": "96648", "Score": "0", "body": "When a user is unable to create an account because it already exists, you shouldn't throw an exception. I assume you know what you need to do in such scenario which would most likely be just to re-present the form with the error message. Exceptions are meant for when an object reaches a state where it does not know how to deal with it any further. Unless you intended to not let your object know what to do in such scenario, I think then an exception would be fine." } ]
[ { "body": "<p>Thought I see many questions to different pieces of the code, I'll answer to the question about exceptions only.</p>\n\n<p>I believe this is not good use of exceptions (one exception, actually). You use it just to indicate a problem in a function that can return a special value. This is not \"exceptional\" situation, but rather normal program flow. </p>\n\n<p>Consider constructor - what can you do if you can not create an object? Exception is the only choice (lets do not discuss general question about quality of class design where you can not avoid exceptions from ctor). </p>\n\n<p>Or, if a function sees a problem that it can not handle alone - memory allocation fault, for example (not the best example, probably).</p>\n\n<p>Exceptions are verfy inefficient and complicated way to transfer messages.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-18T03:56:35.323", "Id": "17433", "Score": "0", "body": "I suppose I could return different values. ex: '1' for for 'Account Already Exists', '2' for 'Invalid username', etc. But then where would those error messages be defined? In the script using the class? Should they be constants within the class and check return value with those: if ( $account->Login () == $account::INVALID_USERNAME ) echo 'Invalid username!'; Something like that? Can you provide an example of how you would do it? I've seen so many posts on StackOverflow saying in OOP, exceptions should be used for things like this, I'm confused." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-18T07:52:01.693", "Id": "17435", "Score": "0", "body": "This is really complicated issue. Exceptions use depends on overall system desing mainly. It is hard to give ultimate answer. In a simple case like your have presented here exceptions are overkill.\nConstants should be defined as class constants: `const CONST_NAME = const_value;` and then you can access them as static properties: `ClassName::CONST_NAME`\nTypical OOP system uses several `define` at the very beginning of execution to registed autoload function, etc. After that - class constants only." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-16T10:55:44.737", "Id": "22150", "Score": "0", "body": "+1 for \"Save exceptions for exceptional events\". I always felt that exceptions get overused, especially in PHP code (probably because they were a relatively recent addition to the language and programmers love shiny new things)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T20:08:12.600", "Id": "10930", "ParentId": "10923", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T06:42:44.680", "Id": "10923", "Score": "1", "Tags": [ "php", "exception-handling", "exception" ], "Title": "PHP - Is this proper use of exceptions for error handling within classes?" }
10923
<p>I've written some code to group a list of items into arbitrarily sized buckets. If the items are all the same and the and the count is a multiple of the bucket size a single bucket is returned, if the items are different then they are grouped into buckets of a given size.</p> <p>For example, with a bucket size of 3:</p> <pre><code>1,2 =&gt; [1,2] 1,2,3,4,5 =&gt; [1,2,3][4,5] 1,1,1,1,1,1 =&gt; [1,1,1,1,1,1] 1,1,1,1,1 =&gt; [1,1,1][1,1] </code></pre> <p>To achieve this I've written the following .Net extension method:</p> <pre><code>public static IEnumerable&lt;IList&lt;T&gt;&gt; GroupBySize&lt;T&gt;(this IEnumerable&lt;T&gt; source, int groupSize, Func&lt;T, T, bool&gt; comparer) { var result = new List&lt;List&lt;T&gt;&gt;(); if (source.IsNullOrEmpty()) return result; List&lt;T&gt; currentGroup = null; for (var i = groupSize; i &lt;= source.Count(); i += groupSize) { var possibleGroup = source.Slice(i - groupSize, groupSize); if (possibleGroup.All(x =&gt; comparer(x, possibleGroup.First()))) { if (currentGroup == null) { currentGroup = new List&lt;T&gt;(); result.Add(currentGroup); } currentGroup.AddRange(possibleGroup); } else { currentGroup = new List&lt;T&gt;(); currentGroup.AddRange(possibleGroup); result.Add(currentGroup); currentGroup = null; } } var remainingItems = source.Count() % groupSize; if (remainingItems &gt; 0) { result.Add(source.Slice(source.Count() - remainingItems, remainingItems).ToList()); } return result; } public static IEnumerable&lt;T&gt; Slice&lt;T&gt;(this IEnumerable&lt;T&gt; source, int start, int count) { return source.Skip(start).Take(count); } public static bool IsNullOrEmpty&lt;T&gt;(this IEnumerable&lt;T&gt; items) { // Taken from :http://haacked.com/archive/2010/06/10/checking-for-empty-enumerations.aspx return items == null || !items.Any(); } </code></pre> <p>The code passes the tests I've written, but it all (including the method name) feels a bit clunky.</p> <p>How could this be improved?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T16:10:04.970", "Id": "17386", "Score": "0", "body": "What should happen if you have something like `1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1` and why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T16:15:38.567", "Id": "17387", "Score": "0", "body": "I would expect something like this: [1, 1, 1] [1, 2, 1] [1, 1, 1] [1, 1] why, because the code is manipulating groups of products to apply line level margin erosion and that's the logic the business requires. The example you've given would never really happen in this particular problem domain, the closest would be 1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3 => [1, 1, 1] [1, 2, 3] [3, 3, 3] [3, 3]" } ]
[ { "body": "<p>I'm not sure you could make this code less clunky, it seems to me the code is reasonably simple, considering what it has to do.</p>\n\n<p>But I can see other problems in your code:</p>\n\n<ol>\n<li>The <code>comparer</code> parameter is probably not necessary in most cases, you can use <a href=\"http://msdn.microsoft.com/en-us/library/ms224763.aspx\" rel=\"nofollow\"><code>EqualityComparer&lt;T&gt;.Default</code></a> for this. But optional <code>comparer</code> makes sense to me.</li>\n<li>LINQ extension methods are usually lazy and that's what I would expect from this method too. For example, if I do something like <code>collection.GroupBySize(3).First()</code>, it's not necessary to create the whole (possibly very long) result, only to discard most of it. To do this, you can use <code>yield return</code>.</li>\n<li>You iterate the source collection (using LINQ methods) <em>a lot</em>. This can have terrible performance, especially if the source collection is something like a result of a LINQ database query, because it queries the database many times, which is not necessary. To fix this, you should write your method around a single <code>foreach (var item in source)</code> and don't use methods like <code>Count()</code>, <code>First()</code>, or <code>Skip()</code>.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T17:04:56.430", "Id": "10928", "ParentId": "10926", "Score": "3" } }, { "body": "<p>As svick said, you should make your method lazy and avoid iterating over the collection more than once. Heres an example of what it might look like: </p>\n\n<pre><code>public static IEnumerable&lt;IList&lt;T&gt;&gt; GroupBySizeNew&lt;T&gt;(this IEnumerable&lt;T&gt; source, int groupSize, Func&lt;T, T, bool&gt; comparer)\n{\n if (source == null || groupSize == 0)\n yield break;\n\n var wholeGroup = new List&lt;T&gt;();\n var singleGroup = new List&lt;T&gt;();\n var backlog = new Queue&lt;IList&lt;T&gt;&gt;();\n\n T first = default(T);\n bool allSame = true;\n int count = 0;\n\n foreach (T item in source)\n {\n if (count == 0)\n first = item;\n\n if (allSame &amp;&amp; !comparer(item, first))\n {\n while (backlog.Count &gt; 0)\n yield return backlog.Dequeue();\n allSame = false;\n }\n\n singleGroup.Add(item);\n if (allSame)\n wholeGroup.Add(item);\n\n if (singleGroup.Count == groupSize)\n {\n if (allSame)\n backlog.Enqueue(singleGroup);\n else\n yield return singleGroup;\n singleGroup = new List&lt;T&gt;();\n }\n count++;\n }\n\n if (count == 0)\n yield break;\n else if (allSame &amp;&amp; count % groupSize == 0)\n yield return wholeGroup;\n else\n {\n while (backlog.Count &gt; 0)\n yield return backlog.Dequeue();\n if (singleGroup.Count &gt; 0)\n yield return singleGroup;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-18T19:51:41.717", "Id": "17476", "Score": "1", "body": "One suggestion would be to use .Any() in place of your calls to .Count > 0." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-18T16:38:23.690", "Id": "10992", "ParentId": "10926", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T15:42:05.457", "Id": "10926", "Score": "3", "Tags": [ "c#" ], "Title": "Grouping Similar Items into buckets" }
10926